diff --git a/OVOW/engine/oneposeviagen/Amodal3R/amodal3r.egg-info/PKG-INFO b/OVOW/engine/oneposeviagen/Amodal3R/amodal3r.egg-info/PKG-INFO new file mode 100644 index 0000000000000000000000000000000000000000..d66a764e11f7c0943f12b12f0491d7e23a493a1a --- /dev/null +++ b/OVOW/engine/oneposeviagen/Amodal3R/amodal3r.egg-info/PKG-INFO @@ -0,0 +1,5 @@ +Metadata-Version: 2.4 +Name: amodal3r +Version: 0.1 +License-File: LICENSE.txt +Dynamic: license-file diff --git a/OVOW/engine/oneposeviagen/Amodal3R/amodal3r.egg-info/SOURCES.txt b/OVOW/engine/oneposeviagen/Amodal3R/amodal3r.egg-info/SOURCES.txt new file mode 100644 index 0000000000000000000000000000000000000000..96f424949d5d4a68a699b451f1cda6a2e7949c01 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Amodal3R/amodal3r.egg-info/SOURCES.txt @@ -0,0 +1,7 @@ +LICENSE.txt +README.md +setup.py +amodal3r.egg-info/PKG-INFO +amodal3r.egg-info/SOURCES.txt +amodal3r.egg-info/dependency_links.txt +amodal3r.egg-info/top_level.txt \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/Amodal3R/amodal3r.egg-info/dependency_links.txt b/OVOW/engine/oneposeviagen/Amodal3R/amodal3r.egg-info/dependency_links.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/OVOW/engine/oneposeviagen/Amodal3R/amodal3r.egg-info/dependency_links.txt @@ -0,0 +1 @@ + diff --git a/OVOW/engine/oneposeviagen/Amodal3R/amodal3r.egg-info/top_level.txt b/OVOW/engine/oneposeviagen/Amodal3R/amodal3r.egg-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/OVOW/engine/oneposeviagen/Amodal3R/amodal3r.egg-info/top_level.txt @@ -0,0 +1 @@ + diff --git a/OVOW/engine/oneposeviagen/Amodal3R/configs/slat.yaml b/OVOW/engine/oneposeviagen/Amodal3R/configs/slat.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3ab2ac9594312496cfdf480937ec978191796423 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Amodal3R/configs/slat.yaml @@ -0,0 +1,38 @@ +gpu_id: [0,1,2,3] + +exp_name: amodal3r/train_ss + +model: + ckpt_path: null + type: slat + +train_dataset: + dataset_name: amodal3r + data_root: ./dataset/abo_3dfuture_hssd + split: train + img_size: [512,512] + +test_dataset: + dataset_name: amodal3r + data_root: ./dataset/abo_3dfuture_hssd + split: test + img_size: [512,512] + +train: + batch_size: 2 + lr: 1e-4 + beta1: 0.9 + beta2: 0.95 + weight_decay: 0.1 + warmup_iters: 1000 + n_epoch: 12 + limit_train_batches: 1.0 + limit_val_batches: 1.0 + check_val_every_n_epoch: 1 + use_rand_views: False +test: + batch_size: 2 + +logger: + name: tensorboard + dir: logs/${exp_name} \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/Amodal3R/configs/ss.yaml b/OVOW/engine/oneposeviagen/Amodal3R/configs/ss.yaml new file mode 100644 index 0000000000000000000000000000000000000000..380486366394360974a62c42249d9ab757ada7f8 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Amodal3R/configs/ss.yaml @@ -0,0 +1,38 @@ +gpu_id: [0,1,2,3] + +exp_name: amodal3r/train_ss + +model: + ckpt_path: null + type: ss + +train_dataset: + dataset_name: amodal3r + data_root: ./dataset/abo_3dfuture_hssd + split: train + img_size: [512,512] + +test_dataset: + dataset_name: amodal3r + data_root: ./dataset/abo_3dfuture_hssd + split: test + img_size: [512,512] + +train: + batch_size: 8 + lr: 1e-4 + beta1: 0.9 + beta2: 0.95 + weight_decay: 0.1 + warmup_iters: 1000 + n_epoch: 12 + limit_train_batches: 1.0 + limit_val_batches: 1.0 + check_val_every_n_epoch: 1 + use_rand_views: False +test: + batch_size: 8 + +logger: + name: tensorboard + dir: logs/${exp_name} \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/Amodal3R/dataLoader/__init__.py b/OVOW/engine/oneposeviagen/Amodal3R/dataLoader/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3f70787a097575af21272eac8693b496b037bcb2 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Amodal3R/dataLoader/__init__.py @@ -0,0 +1,3 @@ +from dataLoader.amodal3r import Amodal3RData + +dataset_dict = {'amodal3r': Amodal3RData} \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/Amodal3R/dataLoader/amodal3r.py b/OVOW/engine/oneposeviagen/Amodal3R/dataLoader/amodal3r.py new file mode 100644 index 0000000000000000000000000000000000000000..8bb0c8b7b8c8889a5ac261edc6cf899c6d09b946 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Amodal3R/dataLoader/amodal3r.py @@ -0,0 +1,121 @@ +import numpy as np +import os +import random +from PIL import Image +import torch +import json +from dataLoader.utils import generate_random_mask, fov_to_ixt + +class Amodal3RData(torch.utils.data.Dataset): + def __init__(self, cfg): + super(Amodal3RData, self).__init__() + self.data_root = cfg.data_root + self.split = cfg.split + self.img_size = np.array(cfg.img_size) + self.img_downscale = self.img_size/512 + self.category = "combined" + + if self.category == "combined": + scenes_name = np.array([f for f in sorted(os.listdir(os.path.join(self.data_root, 'renders'))) if os.path.isdir(f'{self.data_root}/renders/{f}')]) + self.split_num = len(scenes_name) + elif self.category == "abo": + with open("./dataset/ABO/abo.txt", "r") as f: + base_scenes = f.readlines() + base_scenes = [f.strip() for f in base_scenes] + scenes_name = np.array([f for f in sorted(os.listdir(os.path.join(self.data_root, 'renders'))) if os.path.isdir(f'{self.data_root}/renders/{f}') and f in base_scenes]) + self.split_num = 4000 + elif self.category == "3df": + with open("./dataset/3dfuture/3dfuture.txt", "r") as f: + base_scenes = f.readlines() + base_scenes = [f.strip() for f in base_scenes] + scenes_name = np.array([f for f in sorted(os.listdir(os.path.join(self.data_root, 'renders'))) if os.path.isdir(f'{self.data_root}/renders/{f}') and f in base_scenes]) + self.split_num = 8000 + elif self.category == "hssd": + with open("./dataset/hssd/hssd.txt", "r") as f: + base_scenes = f.readlines() + base_scenes = [f.strip() for f in base_scenes] + scenes_name = np.array([f for f in sorted(os.listdir(os.path.join(self.data_root, 'renders'))) if os.path.isdir(f'{self.data_root}/renders/{f}') and f in base_scenes]) + self.split_num = 6000 + + self.split_num = 50 + + if self.split=='train': + self.scenes_name = scenes_name[:self.split_num] + else: + if self.category == "combined": + self.scenes_name = scenes_name[-100:] + else: + self.scenes_name = scenes_name[self.split_num:] + + print(self.category, " ", self.split, ": ", len(self.scenes_name)) + + + def build_metas(self, scene): + json_info = json.load(open(os.path.join(self.data_root, 'renders', scene, f'transforms.json'))) + b2c = np.array([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]]) + scene_info = {'ixts': [], 'c2ws': [], 'w2cs':[], 'img_paths': [], 'fovx': [], 'fovy':[], "mask_paths": []} + positions = [] + for idx, frame in enumerate(json_info['frames']): + c2w = np.array(frame['transform_matrix']) + c2w = c2w @ b2c + fov = frame["camera_angle_x"] + ixt = fov_to_ixt(np.array([fov, fov]), np.array([512, 512])) + scene_info['ixts'].append(ixt.astype(np.float32)) + scene_info['c2ws'].append(c2w.astype(np.float32)) + scene_info['w2cs'].append(np.linalg.inv(c2w.astype(np.float32))) + img_path = os.path.join(self.data_root, 'renders', scene, f'{idx:03d}.png') + scene_info['img_paths'].append(img_path) + scene_info['fovx'].append(fov) + scene_info['fovy'].append(fov) + positions.append(c2w[:3,3]) + mask_path = os.path.join(self.data_root, 'renders_mask', scene, f'{idx:03d}.png') + scene_info['mask_paths'].append(mask_path) + + scene_info['ss_latent_path'] = os.path.join(self.data_root, 'ss_latents/ss_enc_conv3d_16l8_fp16', scene + '.npz') + scene_info['slat_path'] = os.path.join(self.data_root, 'latents/dinov2_vitl14_reg_slat_enc_swin8_B_64l8_fp16', scene + '.npz') + + return scene_info + + + def __getitem__(self, index): + scene_name = self.scenes_name[index] + scene_info = self.build_metas(scene_name) + + ss_latent = np.load(scene_info['ss_latent_path'])['mean'] + ss_latent = torch.from_numpy(ss_latent).float() + + bg_color = np.zeros(3).astype(np.float32) + + num_frames = len(scene_info['img_paths']) + # choose a random frame + frame_idx = random.randint(0, num_frames-1) + + cond_img, cond_img_518_masked, visibility_mask, occlusion_mask = self.read_image(scene_info, frame_idx, bg_color) + + ret = {'cond_img': cond_img, 'cond_img_518_masked': cond_img_518_masked, 'ss_latent': ss_latent, 'slat_path': scene_info['slat_path'], 'visibility_mask': visibility_mask, 'occlusion_mask': occlusion_mask} + + return ret + + + def read_image(self, scene, view_idx, bg_color): + img_path = scene['img_paths'][view_idx] + img = Image.open(img_path).convert("RGBA") + img_518 = img.resize((518, 518), Image.Resampling.LANCZOS) + + img_518 = np.array(img_518).astype(np.float32) / 255. + alpha = img_518[..., -1:] + img_518 = (img_518[..., :3] * img_518[..., -1:] + bg_color*(1 - img_518[..., -1:])).astype(np.float32) + + occlusion_mask = generate_random_mask(height=518, width=518) + bg_mask = (alpha<0.1) + visibility_mask = occlusion_mask | bg_mask + visibility_mask = 1 - visibility_mask + + # apply the mask + img_518_masked = img_518 * visibility_mask + + return img_518.astype(np.float32), img_518_masked.astype(np.float32), visibility_mask.squeeze().astype(np.float32), occlusion_mask.squeeze().astype(np.float32) + + def __len__(self): + return len(self.scenes_name) + diff --git a/OVOW/engine/oneposeviagen/Amodal3R/dataLoader/utils.py b/OVOW/engine/oneposeviagen/Amodal3R/dataLoader/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..e57b8f8ff45fe33be180e19647f41fc3e394a754 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Amodal3R/dataLoader/utils.py @@ -0,0 +1,248 @@ +import torch, math +import numpy as np +from sklearn.cluster import KMeans +import re +import cv2 + +def init_volume_grid(bound=0.45, num_pts_each_axis=32): + # Define the range and number of points + start = -bound + stop = bound + num_points = num_pts_each_axis # Adjust the number of points to your preference + + # Create a linear space for each axis + x = np.linspace(start, stop, num_points) + y = np.linspace(start, stop, num_points) + z = np.linspace(start, stop, num_points) + + # Create a 3D grid of points using meshgrid + X, Y, Z = np.meshgrid(x, y, z, indexing='ij') + + # Stack the grid points in a single array of shape (N, 3) + xyz = np.vstack((X.ravel(), Y.ravel(), Z.ravel())).T + + return xyz + +def build_rays_torch(c2ws, ixts, H, W, scale=1.0): + + H, W = int(H*scale), int(W*scale) + ixts[:,:2] *= scale + rays_o = c2ws[:,:3, 3][:,None,None] + X, Y = torch.meshgrid(torch.arange(W), torch.arange(H), indexing='xy') + XYZ = torch.cat((X[:, :, None] + 0.5, Y[:, :, None] + 0.5, torch.ones_like(X[:, :, None])), dim=-1).to(c2ws) + + i2ws = torch.inverse(ixts).permute(0,2,1) @ c2ws[:,:3, :3].permute(0,2,1) + XYZ = torch.stack([(XYZ @ i2w) for i2w in i2ws]) + rays_o = rays_o.repeat(1,H,1,1) + rays_o = rays_o.repeat(1,1,W,1) + rays = torch.cat((rays_o, XYZ), dim=-1) + return rays + +def build_rays(c2ws, ixts, H, W, scale=1.0): + + H, W = int(H*scale), int(W*scale) + ixts[:,:2] *= scale + + rays_o = c2ws[:,:3, 3][:,None,None] + X, Y = np.meshgrid(np.arange(W), np.arange(H)) + XYZ = np.concatenate((X[:, :, None] + 0.5, Y[:, :, None] + 0.5, np.ones_like(X[:, :, None])), axis=-1) + i2ws = np.linalg.inv(ixts).transpose(0,2,1) @ c2ws[:,:3, :3].transpose(0,2,1) + XYZ = np.stack([(XYZ @ i2w) for i2w in i2ws]) + rays_o = rays_o.repeat(H, axis=1) + rays_o = rays_o.repeat(W, axis=2) + rays = np.concatenate((rays_o, XYZ), axis=-1) + return rays.astype(np.float32) + +def build_rays_ortho(c2ws, H, W, scale=1.0): + + c2ws_rot = c2ws[:,:3,:3] + c2ws_t = c2ws[:,:3,3].reshape(-1,1,3) + + rays_d = torch.zeros(1,1,3).to(c2ws) + rays_d[...,-1] = 1.0 + rays_d = rays_d @ c2ws_rot.transpose(1,2) + rays_d = rays_d[:,None].expand(-1,H,W,-1) + + X, Y = np.meshgrid(np.arange(W), np.arange(H)) + X = torch.from_numpy(X[:, :, None] + 0.5).float()/W * 2 - 1.0 + Y = torch.from_numpy(Y[:, :, None] + 0.5).float()/H * 2 - 1.0 + XYZ = torch.cat((X*scale, Y*scale, torch.zeros_like(X)), dim=-1).to(c2ws) + XYZ = XYZ.view(1,-1,3) + rays_o = XYZ @ c2ws_rot.transpose(1,2) + c2ws_t + rays = torch.cat((rays_o.view(rays_d.shape), rays_d), dim=-1) + return rays + +def KMean(xyz, n_clusters): + kmeans = KMeans(n_clusters = n_clusters, n_init=10, random_state=20211202) + kmeans.fit(xyz) + labels = kmeans.labels_ + + clusters = [] + for i in range(n_clusters): + idx = np.where(labels==i)[0] + clusters.append(idx.astype(np.uint8)) + + return clusters + +def fov_to_ixt(fov, reso): + ixt = np.eye(3, dtype=np.float32) + ixt[0][2], ixt[1][2] = reso[0]/2, reso[1]/2 + focal = .5 * reso / np.tan(.5 * fov) + ixt[[0,1],[0,1]] = focal + return ixt + +def intrinsic_to_fov(K, w=None, h=None): + # Extract the focal lengths from the intrinsic matrix + fx = K[0, 0] + fy = K[1, 1] + + w = K[0, 2]*2 if w is None else w + h = K[1, 2]*2 if h is None else h + + # Calculating field of view + fov_x = 2 * np.arctan2(w, 2 * fx) + fov_y = 2 * np.arctan2(h, 2 * fy) + + return fov_x, fov_y + +def fov2focal(fov, pixels): + return pixels / (2 * math.tan(fov / 2)) + +def focal2fov(focal, pixels): + return 2*math.atan(pixels/(2*focal)) + +def pose_sub_selete(poses, N_poses): + # to select N_poses poses that close to the equatorial + # Define the camera's local up-vector and the world's up-vector + camera_up_vector = np.array([0, 1, 0]) + world_up_vector = np.array([1, 0, 0]) + + # Extract the rotation matrices from the transformation matrices + rotations = poses[:, :3, :3] # Shape: [num_poses, 3, 3] + + # Transform the camera's up-vector to world coordinates for all poses + camera_up_world = np.einsum('ijk,k->ij', rotations, camera_up_vector) # Shape: [num_poses, 3] + + # Normalize the transformed up-vectors + camera_up_world_norm = camera_up_world / np.linalg.norm(camera_up_world, axis=1)[:, np.newaxis] + + # Calculate the dot product with the world up-vector to find cosines of angles + cos_angles = np.dot(camera_up_world_norm, world_up_vector) + + # Calculate angles in radians using arccos + angles = np.arccos(np.clip(cos_angles, -1.0, 1.0)) + + # Select the poses with the smallest angles (closest to the equatorial plane) + indices = np.argsort(angles)[:N_poses] + + return indices + +def read_pfm(filename): + file = open(filename, 'rb') + color = None + width = None + height = None + scale = None + endian = None + + header = file.readline().decode('utf-8').rstrip() + if header == 'PF': + color = True + elif header == 'Pf': + color = False + else: + raise Exception('Not a PFM file.') + + dim_match = re.match(r'^(\d+)\s(\d+)\s$', file.readline().decode('utf-8')) + if dim_match: + width, height = map(int, dim_match.groups()) + else: + raise Exception('Malformed PFM header.') + + scale = float(file.readline().rstrip()) + if scale < 0: # little-endian + endian = '<' + scale = -scale + else: + endian = '>' # big-endian + + data = np.fromfile(file, endian + 'f') + shape = (height, width, 3) if color else (height, width) + + data = np.reshape(data, shape) + data = np.flipud(data) + file.close() + return data, scale + + + +def generate_mae_mask(image_shape=(3,512,512), patch_size=16, mask_ratio=0.3): + _, height, width = image_shape + + num_patches_h = height // patch_size + num_patches_w = width // patch_size + total_patches = num_patches_h * num_patches_w + + num_masked_patches = int(total_patches * mask_ratio) + + mask = np.ones(total_patches, dtype=np.float32) + mask[:num_masked_patches] = 0 + + np.random.shuffle(mask) + + mask = mask.reshape(num_patches_h, num_patches_w) + + mask = np.repeat(np.repeat(mask, patch_size, axis=0), patch_size, axis=1) + + return mask + + +def generate_random_mask(width=512, height=512): + """Generates a stable mask with a fewer number of coherent blocks.""" + + img = np.zeros((width, height, 3), np.uint8) + + # Set size scale + size = int((width + height) * 0.03) + if width < 64 or height < 64: + raise Exception("Width and Height of mask must be at least 64!") + + # Draw random lines (reduced count) + for _ in range(np.random.randint(1, 3)): + x1, x2 = np.random.randint(1, width), np.random.randint(1, width) + y1, y2 = np.random.randint(1, height), np.random.randint(1, height) + thickness = np.random.randint(3, size) + cv2.line(img, (x1, y1), (x2, y2), (1, 1, 1), thickness) + + # Draw random circles (reduced count) + for _ in range(np.random.randint(1, 3)): + x1, y1 = np.random.randint(1, width), np.random.randint(1, height) + radius = np.random.randint(3, size) + cv2.circle(img, (x1, y1), radius, (1, 1, 1), -1) + + # Draw random ellipses (reduced count) + for _ in range(np.random.randint(1, 3)): + x1, y1 = np.random.randint(1, width), np.random.randint(1, height) + s1, s2 = np.random.randint(3, size), np.random.randint(3, size) + a1, a2 = np.random.randint(0, 180), np.random.randint(0, 360) + thickness = np.random.randint(3, size) + cv2.ellipse(img, (x1, y1), (s1, s2), a1, 0, a2, (1, 1, 1), thickness) + + # Add coherent block masks (reduced number of blocks) + num_blocks = np.random.randint(3, 7) + block_size_range = (25, 75) # Larger block sizes for stability + for _ in range(num_blocks): + block_height = np.random.randint(*block_size_range) + block_width = np.random.randint(*block_size_range) + + start_x = np.random.randint(0, max(0, width - block_width)) + start_y = np.random.randint(0, max(0, height - block_height)) + + img[start_y:start_y + block_height, start_x:start_x + block_width] = (1, 1, 1) + + # Dilate the block for smoother edges + kernel_size = np.random.randint(5, 9) # Slightly larger kernel for stability + kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (kernel_size, kernel_size)) + img = cv2.dilate(img, kernel, iterations=1) + + return img[:, :, 0:1] \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/blender_script/io_scene_usdz.zip b/OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/blender_script/io_scene_usdz.zip new file mode 100644 index 0000000000000000000000000000000000000000..153a9d97245cfbf98c2c53869987d82f1396922e --- /dev/null +++ b/OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/blender_script/io_scene_usdz.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ec07ab6125fe0a021ed08c64169eceda126330401aba3d494d5203d26ac4b093 +size 34685 diff --git a/OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/blender_script/render.py b/OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/blender_script/render.py new file mode 100644 index 0000000000000000000000000000000000000000..1fbd5867186d6ebd86cff6e1f98f1a2e1d375e3c --- /dev/null +++ b/OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/blender_script/render.py @@ -0,0 +1,528 @@ +import argparse, sys, os, math, re, glob +from typing import * +import bpy +from mathutils import Vector, Matrix +import numpy as np +import json +import glob + + +"""=============== BLENDER ===============""" + +IMPORT_FUNCTIONS: Dict[str, Callable] = { + "obj": bpy.ops.import_scene.obj, + "glb": bpy.ops.import_scene.gltf, + "gltf": bpy.ops.import_scene.gltf, + "usd": bpy.ops.import_scene.usd, + "fbx": bpy.ops.import_scene.fbx, + "stl": bpy.ops.import_mesh.stl, + "usda": bpy.ops.import_scene.usda, + "dae": bpy.ops.wm.collada_import, + "ply": bpy.ops.import_mesh.ply, + "abc": bpy.ops.wm.alembic_import, + "blend": bpy.ops.wm.append, +} + +EXT = { + 'PNG': 'png', + 'JPEG': 'jpg', + 'OPEN_EXR': 'exr', + 'TIFF': 'tiff', + 'BMP': 'bmp', + 'HDR': 'hdr', + 'TARGA': 'tga' +} + +def init_render(engine='CYCLES', resolution=512, geo_mode=False): + bpy.context.scene.render.engine = engine + bpy.context.scene.render.resolution_x = resolution + bpy.context.scene.render.resolution_y = resolution + bpy.context.scene.render.resolution_percentage = 100 + bpy.context.scene.render.image_settings.file_format = 'PNG' + bpy.context.scene.render.image_settings.color_mode = 'RGBA' + bpy.context.scene.render.film_transparent = True + + bpy.context.scene.cycles.device = 'GPU' + bpy.context.scene.cycles.samples = 128 if not geo_mode else 1 + bpy.context.scene.cycles.filter_type = 'BOX' + bpy.context.scene.cycles.filter_width = 1 + bpy.context.scene.cycles.diffuse_bounces = 1 + bpy.context.scene.cycles.glossy_bounces = 1 + bpy.context.scene.cycles.transparent_max_bounces = 3 if not geo_mode else 0 + bpy.context.scene.cycles.transmission_bounces = 3 if not geo_mode else 1 + bpy.context.scene.cycles.use_denoising = True + + bpy.context.preferences.addons['cycles'].preferences.get_devices() + bpy.context.preferences.addons['cycles'].preferences.compute_device_type = 'CUDA' + +def init_nodes(save_depth=False, save_normal=False, save_albedo=False, save_mist=False): + if not any([save_depth, save_normal, save_albedo, save_mist]): + return {}, {} + outputs = {} + spec_nodes = {} + + bpy.context.scene.use_nodes = True + bpy.context.scene.view_layers['View Layer'].use_pass_z = save_depth + bpy.context.scene.view_layers['View Layer'].use_pass_normal = save_normal + bpy.context.scene.view_layers['View Layer'].use_pass_diffuse_color = save_albedo + bpy.context.scene.view_layers['View Layer'].use_pass_mist = save_mist + + nodes = bpy.context.scene.node_tree.nodes + links = bpy.context.scene.node_tree.links + for n in nodes: + nodes.remove(n) + + render_layers = nodes.new('CompositorNodeRLayers') + + if save_depth: + depth_file_output = nodes.new('CompositorNodeOutputFile') + depth_file_output.base_path = '' + depth_file_output.file_slots[0].use_node_format = True + depth_file_output.format.file_format = 'PNG' + depth_file_output.format.color_depth = '16' + depth_file_output.format.color_mode = 'BW' + # Remap to 0-1 + map = nodes.new(type="CompositorNodeMapRange") + map.inputs[1].default_value = 0 # (min value you will be getting) + map.inputs[2].default_value = 10 # (max value you will be getting) + map.inputs[3].default_value = 0 # (min value you will map to) + map.inputs[4].default_value = 1 # (max value you will map to) + + links.new(render_layers.outputs['Depth'], map.inputs[0]) + links.new(map.outputs[0], depth_file_output.inputs[0]) + + outputs['depth'] = depth_file_output + spec_nodes['depth_map'] = map + + if save_normal: + normal_file_output = nodes.new('CompositorNodeOutputFile') + normal_file_output.base_path = '' + normal_file_output.file_slots[0].use_node_format = True + normal_file_output.format.file_format = 'OPEN_EXR' + normal_file_output.format.color_mode = 'RGB' + normal_file_output.format.color_depth = '16' + + links.new(render_layers.outputs['Normal'], normal_file_output.inputs[0]) + + outputs['normal'] = normal_file_output + + if save_albedo: + albedo_file_output = nodes.new('CompositorNodeOutputFile') + albedo_file_output.base_path = '' + albedo_file_output.file_slots[0].use_node_format = True + albedo_file_output.format.file_format = 'PNG' + albedo_file_output.format.color_mode = 'RGBA' + albedo_file_output.format.color_depth = '8' + + alpha_albedo = nodes.new('CompositorNodeSetAlpha') + + links.new(render_layers.outputs['DiffCol'], alpha_albedo.inputs['Image']) + links.new(render_layers.outputs['Alpha'], alpha_albedo.inputs['Alpha']) + links.new(alpha_albedo.outputs['Image'], albedo_file_output.inputs[0]) + + outputs['albedo'] = albedo_file_output + + if save_mist: + bpy.data.worlds['World'].mist_settings.start = 0 + bpy.data.worlds['World'].mist_settings.depth = 10 + + mist_file_output = nodes.new('CompositorNodeOutputFile') + mist_file_output.base_path = '' + mist_file_output.file_slots[0].use_node_format = True + mist_file_output.format.file_format = 'PNG' + mist_file_output.format.color_mode = 'BW' + mist_file_output.format.color_depth = '16' + + links.new(render_layers.outputs['Mist'], mist_file_output.inputs[0]) + + outputs['mist'] = mist_file_output + + return outputs, spec_nodes + +def init_scene() -> None: + """Resets the scene to a clean state. + + Returns: + None + """ + # delete everything + for obj in bpy.data.objects: + bpy.data.objects.remove(obj, do_unlink=True) + + # delete all the materials + for material in bpy.data.materials: + bpy.data.materials.remove(material, do_unlink=True) + + # delete all the textures + for texture in bpy.data.textures: + bpy.data.textures.remove(texture, do_unlink=True) + + # delete all the images + for image in bpy.data.images: + bpy.data.images.remove(image, do_unlink=True) + +def init_camera(): + cam = bpy.data.objects.new('Camera', bpy.data.cameras.new('Camera')) + bpy.context.collection.objects.link(cam) + bpy.context.scene.camera = cam + cam.data.sensor_height = cam.data.sensor_width = 32 + cam_constraint = cam.constraints.new(type='TRACK_TO') + cam_constraint.track_axis = 'TRACK_NEGATIVE_Z' + cam_constraint.up_axis = 'UP_Y' + cam_empty = bpy.data.objects.new("Empty", None) + cam_empty.location = (0, 0, 0) + bpy.context.scene.collection.objects.link(cam_empty) + cam_constraint.target = cam_empty + return cam + +def init_lighting(): + # Clear existing lights + bpy.ops.object.select_all(action="DESELECT") + bpy.ops.object.select_by_type(type="LIGHT") + bpy.ops.object.delete() + + # Create key light + default_light = bpy.data.objects.new("Default_Light", bpy.data.lights.new("Default_Light", type="POINT")) + bpy.context.collection.objects.link(default_light) + default_light.data.energy = 1000 + default_light.location = (4, 1, 6) + default_light.rotation_euler = (0, 0, 0) + + # create top light + top_light = bpy.data.objects.new("Top_Light", bpy.data.lights.new("Top_Light", type="AREA")) + bpy.context.collection.objects.link(top_light) + top_light.data.energy = 10000 + top_light.location = (0, 0, 10) + top_light.scale = (100, 100, 100) + + # create bottom light + bottom_light = bpy.data.objects.new("Bottom_Light", bpy.data.lights.new("Bottom_Light", type="AREA")) + bpy.context.collection.objects.link(bottom_light) + bottom_light.data.energy = 1000 + bottom_light.location = (0, 0, -10) + bottom_light.rotation_euler = (0, 0, 0) + + return { + "default_light": default_light, + "top_light": top_light, + "bottom_light": bottom_light + } + + +def load_object(object_path: str) -> None: + """Loads a model with a supported file extension into the scene. + + Args: + object_path (str): Path to the model file. + + Raises: + ValueError: If the file extension is not supported. + + Returns: + None + """ + file_extension = object_path.split(".")[-1].lower() + if file_extension is None: + raise ValueError(f"Unsupported file type: {object_path}") + + if file_extension == "usdz": + # install usdz io package + dirname = os.path.dirname(os.path.realpath(__file__)) + usdz_package = os.path.join(dirname, "io_scene_usdz.zip") + bpy.ops.preferences.addon_install(filepath=usdz_package) + # enable it + addon_name = "io_scene_usdz" + bpy.ops.preferences.addon_enable(module=addon_name) + # import the usdz + from io_scene_usdz.import_usdz import import_usdz + + import_usdz(context, filepath=object_path, materials=True, animations=True) + return None + + # load from existing import functions + import_function = IMPORT_FUNCTIONS[file_extension] + + print(f"Loading object from {object_path}") + if file_extension == "blend": + import_function(directory=object_path, link=False) + elif file_extension in {"glb", "gltf"}: + import_function(filepath=object_path, merge_vertices=True, import_shading='NORMALS') + else: + import_function(filepath=object_path) + +def delete_invisible_objects() -> None: + """Deletes all invisible objects in the scene. + + Returns: + None + """ + # bpy.ops.object.mode_set(mode="OBJECT") + bpy.ops.object.select_all(action="DESELECT") + for obj in bpy.context.scene.objects: + if obj.hide_viewport or obj.hide_render: + obj.hide_viewport = False + obj.hide_render = False + obj.hide_select = False + obj.select_set(True) + bpy.ops.object.delete() + + # Delete invisible collections + invisible_collections = [col for col in bpy.data.collections if col.hide_viewport] + for col in invisible_collections: + bpy.data.collections.remove(col) + +def split_mesh_normal(): + bpy.ops.object.select_all(action="DESELECT") + objs = [obj for obj in bpy.context.scene.objects if obj.type == "MESH"] + bpy.context.view_layer.objects.active = objs[0] + for obj in objs: + obj.select_set(True) + bpy.ops.object.mode_set(mode="EDIT") + bpy.ops.mesh.select_all(action='SELECT') + bpy.ops.mesh.split_normals() + bpy.ops.object.mode_set(mode='OBJECT') + bpy.ops.object.select_all(action="DESELECT") + +def delete_custom_normals(): + for this_obj in bpy.data.objects: + if this_obj.type == "MESH": + bpy.context.view_layer.objects.active = this_obj + bpy.ops.mesh.customdata_custom_splitnormals_clear() + +def override_material(): + new_mat = bpy.data.materials.new(name="Override0123456789") + new_mat.use_nodes = True + new_mat.node_tree.nodes.clear() + bsdf = new_mat.node_tree.nodes.new('ShaderNodeBsdfDiffuse') + bsdf.inputs[0].default_value = (0.5, 0.5, 0.5, 1) + bsdf.inputs[1].default_value = 1 + output = new_mat.node_tree.nodes.new('ShaderNodeOutputMaterial') + new_mat.node_tree.links.new(bsdf.outputs['BSDF'], output.inputs['Surface']) + bpy.context.scene.view_layers['View Layer'].material_override = new_mat + +def unhide_all_objects() -> None: + """Unhides all objects in the scene. + + Returns: + None + """ + for obj in bpy.context.scene.objects: + obj.hide_set(False) + +def convert_to_meshes() -> None: + """Converts all objects in the scene to meshes. + + Returns: + None + """ + bpy.ops.object.select_all(action="DESELECT") + bpy.context.view_layer.objects.active = [obj for obj in bpy.context.scene.objects if obj.type == "MESH"][0] + for obj in bpy.context.scene.objects: + obj.select_set(True) + bpy.ops.object.convert(target="MESH") + +def triangulate_meshes() -> None: + """Triangulates all meshes in the scene. + + Returns: + None + """ + bpy.ops.object.select_all(action="DESELECT") + objs = [obj for obj in bpy.context.scene.objects if obj.type == "MESH"] + bpy.context.view_layer.objects.active = objs[0] + for obj in objs: + obj.select_set(True) + bpy.ops.object.mode_set(mode="EDIT") + bpy.ops.mesh.reveal() + bpy.ops.mesh.select_all(action="SELECT") + bpy.ops.mesh.quads_convert_to_tris(quad_method="BEAUTY", ngon_method="BEAUTY") + bpy.ops.object.mode_set(mode="OBJECT") + bpy.ops.object.select_all(action="DESELECT") + +def scene_bbox() -> Tuple[Vector, Vector]: + """Returns the bounding box of the scene. + + Taken from Shap-E rendering script + (https://github.com/openai/shap-e/blob/main/shap_e/rendering/blender/blender_script.py#L68-L82) + + Returns: + Tuple[Vector, Vector]: The minimum and maximum coordinates of the bounding box. + """ + bbox_min = (math.inf,) * 3 + bbox_max = (-math.inf,) * 3 + found = False + scene_meshes = [obj for obj in bpy.context.scene.objects.values() if isinstance(obj.data, bpy.types.Mesh)] + for obj in scene_meshes: + found = True + for coord in obj.bound_box: + coord = Vector(coord) + coord = obj.matrix_world @ coord + bbox_min = tuple(min(x, y) for x, y in zip(bbox_min, coord)) + bbox_max = tuple(max(x, y) for x, y in zip(bbox_max, coord)) + if not found: + raise RuntimeError("no objects in scene to compute bounding box for") + return Vector(bbox_min), Vector(bbox_max) + +def normalize_scene() -> Tuple[float, Vector]: + """Normalizes the scene by scaling and translating it to fit in a unit cube centered + at the origin. + + Mostly taken from the Point-E / Shap-E rendering script + (https://github.com/openai/point-e/blob/main/point_e/evals/scripts/blender_script.py#L97-L112), + but fix for multiple root objects: (see bug report here: + https://github.com/openai/shap-e/pull/60). + + Returns: + Tuple[float, Vector]: The scale factor and the offset applied to the scene. + """ + scene_root_objects = [obj for obj in bpy.context.scene.objects.values() if not obj.parent] + if len(scene_root_objects) > 1: + # create an empty object to be used as a parent for all root objects + scene = bpy.data.objects.new("ParentEmpty", None) + bpy.context.scene.collection.objects.link(scene) + + # parent all root objects to the empty object + for obj in scene_root_objects: + obj.parent = scene + else: + scene = scene_root_objects[0] + + bbox_min, bbox_max = scene_bbox() + scale = 1 / max(bbox_max - bbox_min) + scene.scale = scene.scale * scale + + # Apply scale to matrix_world. + bpy.context.view_layer.update() + bbox_min, bbox_max = scene_bbox() + offset = -(bbox_min + bbox_max) / 2 + scene.matrix_world.translation += offset + bpy.ops.object.select_all(action="DESELECT") + + return scale, offset + +def get_transform_matrix(obj: bpy.types.Object) -> list: + pos, rt, _ = obj.matrix_world.decompose() + rt = rt.to_matrix() + matrix = [] + for ii in range(3): + a = [] + for jj in range(3): + a.append(rt[ii][jj]) + a.append(pos[ii]) + matrix.append(a) + matrix.append([0, 0, 0, 1]) + return matrix + +def main(arg): + os.makedirs(arg.output_folder, exist_ok=True) + + # Initialize context + init_render(engine=arg.engine, resolution=arg.resolution, geo_mode=arg.geo_mode) + outputs, spec_nodes = init_nodes( + save_depth=arg.save_depth, + save_normal=arg.save_normal, + save_albedo=arg.save_albedo, + save_mist=arg.save_mist + ) + if arg.object.endswith(".blend"): + delete_invisible_objects() + else: + init_scene() + load_object(arg.object) + if arg.split_normal: + split_mesh_normal() + # delete_custom_normals() + print('[INFO] Scene initialized.') + + # normalize scene + scale, offset = normalize_scene() + print('[INFO] Scene normalized.') + + # Initialize camera and lighting + cam = init_camera() + init_lighting() + print('[INFO] Camera and lighting initialized.') + + # Override material + if arg.geo_mode: + override_material() + + # Create a list of views + to_export = { + "aabb": [[-0.5, -0.5, -0.5], [0.5, 0.5, 0.5]], + "scale": scale, + "offset": [offset.x, offset.y, offset.z], + "frames": [] + } + views = json.loads(arg.views) + for i, view in enumerate(views): + cam.location = ( + view['radius'] * np.cos(view['yaw']) * np.cos(view['pitch']), + view['radius'] * np.sin(view['yaw']) * np.cos(view['pitch']), + view['radius'] * np.sin(view['pitch']) + ) + cam.data.lens = 16 / np.tan(view['fov'] / 2) + + if arg.save_depth: + spec_nodes['depth_map'].inputs[1].default_value = view['radius'] - 0.5 * np.sqrt(3) + spec_nodes['depth_map'].inputs[2].default_value = view['radius'] + 0.5 * np.sqrt(3) + + bpy.context.scene.render.filepath = os.path.join(arg.output_folder, f'{i:03d}.png') + for name, output in outputs.items(): + output.file_slots[0].path = os.path.join(arg.output_folder, f'{i:03d}_{name}') + + # Render the scene + bpy.ops.render.render(write_still=True) + bpy.context.view_layer.update() + for name, output in outputs.items(): + ext = EXT[output.format.file_format] + path = glob.glob(f'{output.file_slots[0].path}*.{ext}')[0] + os.rename(path, f'{output.file_slots[0].path}.{ext}') + + # Save camera parameters + metadata = { + "file_path": f'{i:03d}.png', + "camera_angle_x": view['fov'], + "transform_matrix": get_transform_matrix(cam) + } + if arg.save_depth: + metadata['depth'] = { + 'min': view['radius'] - 0.5 * np.sqrt(3), + 'max': view['radius'] + 0.5 * np.sqrt(3) + } + to_export["frames"].append(metadata) + + # Save the camera parameters + with open(os.path.join(arg.output_folder, 'transforms.json'), 'w') as f: + json.dump(to_export, f, indent=4) + + if arg.save_mesh: + # triangulate meshes + unhide_all_objects() + convert_to_meshes() + triangulate_meshes() + print('[INFO] Meshes triangulated.') + + # export ply mesh + bpy.ops.export_mesh.ply(filepath=os.path.join(arg.output_folder, 'mesh.ply')) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description='Renders given obj file by rotation a camera around it.') + parser.add_argument('--views', type=str, help='JSON string of views. Contains a list of {yaw, pitch, radius, fov} object.') + parser.add_argument('--object', type=str, help='Path to the 3D model file to be rendered.') + parser.add_argument('--output_folder', type=str, default='/tmp', help='The path the output will be dumped to.') + parser.add_argument('--resolution', type=int, default=512, help='Resolution of the images.') + parser.add_argument('--engine', type=str, default='CYCLES', help='Blender internal engine for rendering. E.g. CYCLES, BLENDER_EEVEE, ...') + parser.add_argument('--geo_mode', action='store_true', help='Geometry mode for rendering.') + parser.add_argument('--save_depth', action='store_true', help='Save the depth maps.') + parser.add_argument('--save_normal', action='store_true', help='Save the normal maps.') + parser.add_argument('--save_albedo', action='store_true', help='Save the albedo maps.') + parser.add_argument('--save_mist', action='store_true', help='Save the mist distance maps.') + parser.add_argument('--split_normal', action='store_true', help='Split the normals of the mesh.') + parser.add_argument('--save_mesh', action='store_true', help='Save the mesh as a .ply file.') + argv = sys.argv[sys.argv.index("--") + 1:] + args = parser.parse_args(argv) + + main(args) + \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/build_metadata.py b/OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/build_metadata.py new file mode 100644 index 0000000000000000000000000000000000000000..0c1f6396a9d11ca99be8eb8ffae22e64472f4ec8 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/build_metadata.py @@ -0,0 +1,270 @@ +import os +import shutil +import sys +import time +import importlib +import argparse +import numpy as np +import pandas as pd +from tqdm import tqdm +from easydict import EasyDict as edict +from concurrent.futures import ThreadPoolExecutor +import utils3d + +def get_first_directory(path): + with os.scandir(path) as it: + for entry in it: + if entry.is_dir(): + return entry.name + return None + +def need_process(key): + return key in opt.field or opt.field == ['all'] + +if __name__ == '__main__': + dataset_utils = importlib.import_module(f'datasets.{sys.argv[1]}') + + parser = argparse.ArgumentParser() + parser.add_argument('--output_dir', type=str, required=True, + help='Directory to save the metadata') + parser.add_argument('--field', type=str, default='all', + help='Fields to process, separated by commas') + parser.add_argument('--from_file', action='store_true', + help='Build metadata from file instead of from records of processings.' + + 'Useful when some processing fail to generate records but file already exists.') + dataset_utils.add_args(parser) + opt = parser.parse_args(sys.argv[2:]) + opt = edict(vars(opt)) + + os.makedirs(opt.output_dir, exist_ok=True) + os.makedirs(os.path.join(opt.output_dir, 'merged_records'), exist_ok=True) + + opt.field = opt.field.split(',') + + timestamp = str(int(time.time())) + + # get file list + if os.path.exists(os.path.join(opt.output_dir, 'metadata.csv')): + print('Loading previous metadata...') + metadata = pd.read_csv(os.path.join(opt.output_dir, 'metadata.csv')) + else: + metadata = dataset_utils.get_metadata(**opt) + metadata.set_index('sha256', inplace=True) + + # merge downloaded + df_files = [f for f in os.listdir(opt.output_dir) if f.startswith('downloaded_') and f.endswith('.csv')] + df_parts = [] + for f in df_files: + try: + df_parts.append(pd.read_csv(os.path.join(opt.output_dir, f))) + except: + pass + if len(df_parts) > 0: + df = pd.concat(df_parts) + df.set_index('sha256', inplace=True) + if 'local_path' in metadata.columns: + metadata.update(df, overwrite=True) + else: + metadata = metadata.join(df, on='sha256', how='left') + for f in df_files: + shutil.move(os.path.join(opt.output_dir, f), os.path.join(opt.output_dir, 'merged_records', f'{timestamp}_{f}')) + + # detect models + image_models = [] + if os.path.exists(os.path.join(opt.output_dir, 'features')): + image_models = os.listdir(os.path.join(opt.output_dir, 'features')) + latent_models = [] + if os.path.exists(os.path.join(opt.output_dir, 'latents')): + latent_models = os.listdir(os.path.join(opt.output_dir, 'latents')) + ss_latent_models = [] + if os.path.exists(os.path.join(opt.output_dir, 'ss_latents')): + ss_latent_models = os.listdir(os.path.join(opt.output_dir, 'ss_latents')) + print(f'Image models: {image_models}') + print(f'Latent models: {latent_models}') + print(f'Sparse Structure latent models: {ss_latent_models}') + + if 'rendered' not in metadata.columns: + metadata['rendered'] = [False] * len(metadata) + if 'voxelized' not in metadata.columns: + metadata['voxelized'] = [False] * len(metadata) + if 'num_voxels' not in metadata.columns: + metadata['num_voxels'] = [0] * len(metadata) + if 'cond_rendered' not in metadata.columns: + metadata['cond_rendered'] = [False] * len(metadata) + for model in image_models: + if f'feature_{model}' not in metadata.columns: + metadata[f'feature_{model}'] = [False] * len(metadata) + for model in latent_models: + if f'latent_{model}' not in metadata.columns: + metadata[f'latent_{model}'] = [False] * len(metadata) + for model in ss_latent_models: + if f'ss_latent_{model}' not in metadata.columns: + metadata[f'ss_latent_{model}'] = [False] * len(metadata) + + # merge rendered + df_files = [f for f in os.listdir(opt.output_dir) if f.startswith('rendered_') and f.endswith('.csv')] + df_parts = [] + for f in df_files: + try: + df_parts.append(pd.read_csv(os.path.join(opt.output_dir, f))) + except: + pass + if len(df_parts) > 0: + df = pd.concat(df_parts) + df.set_index('sha256', inplace=True) + metadata.update(df, overwrite=True) + for f in df_files: + shutil.move(os.path.join(opt.output_dir, f), os.path.join(opt.output_dir, 'merged_records', f'{timestamp}_{f}')) + + # merge voxelized + df_files = [f for f in os.listdir(opt.output_dir) if f.startswith('voxelized_') and f.endswith('.csv')] + df_parts = [] + for f in df_files: + try: + df_parts.append(pd.read_csv(os.path.join(opt.output_dir, f))) + except: + pass + if len(df_parts) > 0: + df = pd.concat(df_parts) + df.set_index('sha256', inplace=True) + metadata.update(df, overwrite=True) + for f in df_files: + shutil.move(os.path.join(opt.output_dir, f), os.path.join(opt.output_dir, 'merged_records', f'{timestamp}_{f}')) + + # merge cond_rendered + df_files = [f for f in os.listdir(opt.output_dir) if f.startswith('cond_rendered_') and f.endswith('.csv')] + df_parts = [] + for f in df_files: + try: + df_parts.append(pd.read_csv(os.path.join(opt.output_dir, f))) + except: + pass + if len(df_parts) > 0: + df = pd.concat(df_parts) + df.set_index('sha256', inplace=True) + metadata.update(df, overwrite=True) + for f in df_files: + shutil.move(os.path.join(opt.output_dir, f), os.path.join(opt.output_dir, 'merged_records', f'{timestamp}_{f}')) + + # merge features + for model in image_models: + df_files = [f for f in os.listdir(opt.output_dir) if f.startswith(f'feature_{model}_') and f.endswith('.csv')] + df_parts = [] + for f in df_files: + try: + df_parts.append(pd.read_csv(os.path.join(opt.output_dir, f))) + except: + pass + if len(df_parts) > 0: + df = pd.concat(df_parts) + df.set_index('sha256', inplace=True) + metadata.update(df, overwrite=True) + for f in df_files: + shutil.move(os.path.join(opt.output_dir, f), os.path.join(opt.output_dir, 'merged_records', f'{timestamp}_{f}')) + + # merge latents + for model in latent_models: + df_files = [f for f in os.listdir(opt.output_dir) if f.startswith(f'latent_{model}_') and f.endswith('.csv')] + df_parts = [] + for f in df_files: + try: + df_parts.append(pd.read_csv(os.path.join(opt.output_dir, f))) + except: + pass + if len(df_parts) > 0: + df = pd.concat(df_parts) + df.set_index('sha256', inplace=True) + metadata.update(df, overwrite=True) + for f in df_files: + shutil.move(os.path.join(opt.output_dir, f), os.path.join(opt.output_dir, 'merged_records', f'{timestamp}_{f}')) + + # merge sparse structure latents + for model in ss_latent_models: + df_files = [f for f in os.listdir(opt.output_dir) if f.startswith(f'ss_latent_{model}_') and f.endswith('.csv')] + df_parts = [] + for f in df_files: + try: + df_parts.append(pd.read_csv(os.path.join(opt.output_dir, f))) + except: + pass + if len(df_parts) > 0: + df = pd.concat(df_parts) + df.set_index('sha256', inplace=True) + metadata.update(df, overwrite=True) + for f in df_files: + shutil.move(os.path.join(opt.output_dir, f), os.path.join(opt.output_dir, 'merged_records', f'{timestamp}_{f}')) + + # build metadata from files + if opt.from_file: + with ThreadPoolExecutor(max_workers=os.cpu_count()) as executor, \ + tqdm(total=len(metadata), desc="Building metadata") as pbar: + def worker(sha256): + try: + if need_process('rendered') and metadata.loc[sha256, 'rendered'] == False and \ + os.path.exists(os.path.join(opt.output_dir, 'renders', sha256, 'transforms.json')): + metadata.loc[sha256, 'rendered'] = True + if need_process('voxelized') and metadata.loc[sha256, 'rendered'] == True and metadata.loc[sha256, 'voxelized'] == False and \ + os.path.exists(os.path.join(opt.output_dir, 'voxels', f'{sha256}.ply')): + try: + pts = utils3d.io.read_ply(os.path.join(opt.output_dir, 'voxels', f'{sha256}.ply'))[0] + metadata.loc[sha256, 'voxelized'] = True + metadata.loc[sha256, 'num_voxels'] = len(pts) + except Exception as e: + pass + if need_process('cond_rendered') and metadata.loc[sha256, 'cond_rendered'] == False and \ + os.path.exists(os.path.join(opt.output_dir, 'renders_cond', sha256, 'transforms.json')): + metadata.loc[sha256, 'cond_rendered'] = True + for model in image_models: + if need_process(f'feature_{model}') and \ + metadata.loc[sha256, f'feature_{model}'] == False and \ + metadata.loc[sha256, 'rendered'] == True and \ + metadata.loc[sha256, 'voxelized'] == True and \ + os.path.exists(os.path.join(opt.output_dir, 'features', model, f'{sha256}.npz')): + metadata.loc[sha256, f'feature_{model}'] = True + for model in latent_models: + if need_process(f'latent_{model}') and \ + metadata.loc[sha256, f'latent_{model}'] == False and \ + metadata.loc[sha256, 'rendered'] == True and \ + metadata.loc[sha256, 'voxelized'] == True and \ + os.path.exists(os.path.join(opt.output_dir, 'latents', model, f'{sha256}.npz')): + metadata.loc[sha256, f'latent_{model}'] = True + for model in ss_latent_models: + if need_process(f'ss_latent_{model}') and \ + metadata.loc[sha256, f'ss_latent_{model}'] == False and \ + metadata.loc[sha256, 'voxelized'] == True and \ + os.path.exists(os.path.join(opt.output_dir, 'ss_latents', model, f'{sha256}.npz')): + metadata.loc[sha256, f'ss_latent_{model}'] = True + pbar.update() + except Exception as e: + print(f'Error processing {sha256}: {e}') + pbar.update() + + executor.map(worker, metadata.index) + executor.shutdown(wait=True) + + # statistics + metadata.to_csv(os.path.join(opt.output_dir, 'metadata.csv')) + num_downloaded = metadata['local_path'].count() if 'local_path' in metadata.columns else 0 + with open(os.path.join(opt.output_dir, 'statistics.txt'), 'w') as f: + f.write('Statistics:\n') + f.write(f' - Number of assets: {len(metadata)}\n') + f.write(f' - Number of assets downloaded: {num_downloaded}\n') + f.write(f' - Number of assets rendered: {metadata["rendered"].sum()}\n') + f.write(f' - Number of assets voxelized: {metadata["voxelized"].sum()}\n') + if len(image_models) != 0: + f.write(f' - Number of assets with image features extracted:\n') + for model in image_models: + f.write(f' - {model}: {metadata[f"feature_{model}"].sum()}\n') + if len(latent_models) != 0: + f.write(f' - Number of assets with latents extracted:\n') + for model in latent_models: + f.write(f' - {model}: {metadata[f"latent_{model}"].sum()}\n') + if len(ss_latent_models) != 0: + f.write(f' - Number of assets with sparse structure latents extracted:\n') + for model in ss_latent_models: + f.write(f' - {model}: {metadata[f"ss_latent_{model}"].sum()}\n') + f.write(f' - Number of assets with captions: {metadata["captions"].count()}\n') + f.write(f' - Number of assets with image conditions: {metadata["cond_rendered"].sum()}\n') + + with open(os.path.join(opt.output_dir, 'statistics.txt'), 'r') as f: + print(f.read()) \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/datasets/3D-FUTURE.py b/OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/datasets/3D-FUTURE.py new file mode 100644 index 0000000000000000000000000000000000000000..a5ccc632de8e5a1d4f4a3b2b3024b8a3361e12c4 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/datasets/3D-FUTURE.py @@ -0,0 +1,97 @@ +import os +import re +import argparse +import zipfile +from concurrent.futures import ThreadPoolExecutor +from tqdm import tqdm +import pandas as pd +from utils import get_file_hash + + +def add_args(parser: argparse.ArgumentParser): + pass + + +def get_metadata(**kwargs): + metadata = pd.read_csv("hf://datasets/JeffreyXiang/TRELLIS-500K/3D-FUTURE.csv") + return metadata + + +def download(metadata, output_dir, **kwargs): + os.makedirs(output_dir, exist_ok=True) + + if not os.path.exists(os.path.join(output_dir, 'raw', '3D-FUTURE-model.zip')): + print("\033[93m") + print("3D-FUTURE have to be downloaded manually") + print(f"Please download the 3D-FUTURE-model.zip file and place it in the {output_dir}/raw directory") + print("Visit https://tianchi.aliyun.com/specials/promotion/alibaba-3d-future for more information") + print("\033[0m") + raise FileNotFoundError("3D-FUTURE-model.zip not found") + + downloaded = {} + metadata = metadata.set_index("file_identifier") + with zipfile.ZipFile(os.path.join(output_dir, 'raw', '3D-FUTURE-model.zip')) as zip_ref: + all_names = zip_ref.namelist() + instances = [instance[:-1] for instance in all_names if re.match(r"^3D-FUTURE-model/[^/]+/$", instance)] + instances = list(filter(lambda x: x in metadata.index, instances)) + + with ThreadPoolExecutor(max_workers=os.cpu_count()) as executor, \ + tqdm(total=len(instances), desc="Extracting") as pbar: + def worker(instance: str) -> str: + try: + instance_files = list(filter(lambda x: x.startswith(f"{instance}/") and not x.endswith("/"), all_names)) + zip_ref.extractall(os.path.join(output_dir, 'raw'), members=instance_files) + sha256 = get_file_hash(os.path.join(output_dir, 'raw', f"{instance}/image.jpg")) + pbar.update() + return sha256 + except Exception as e: + pbar.update() + print(f"Error extracting for {instance}: {e}") + return None + + sha256s = executor.map(worker, instances) + executor.shutdown(wait=True) + + for k, sha256 in zip(instances, sha256s): + if sha256 is not None: + if sha256 == metadata.loc[k, "sha256"]: + downloaded[sha256] = os.path.join("raw", f"{k}/raw_model.obj") + else: + print(f"Error downloading {k}: sha256s do not match") + + return pd.DataFrame(downloaded.items(), columns=['sha256', 'local_path']) + + +def foreach_instance(metadata, output_dir, func, max_workers=None, desc='Processing objects') -> pd.DataFrame: + import os + from concurrent.futures import ThreadPoolExecutor + from tqdm import tqdm + + # load metadata + metadata = metadata.to_dict('records') + + # processing objects + records = [] + max_workers = max_workers or os.cpu_count() + try: + with ThreadPoolExecutor(max_workers=max_workers) as executor, \ + tqdm(total=len(metadata), desc=desc) as pbar: + def worker(metadatum): + try: + local_path = metadatum['local_path'] + sha256 = metadatum['sha256'] + file = os.path.join(output_dir, local_path) + record = func(file, sha256) + if record is not None: + records.append(record) + pbar.update() + except Exception as e: + print(f"Error processing object {sha256}: {e}") + pbar.update() + + executor.map(worker, metadata) + executor.shutdown(wait=True) + except: + print("Error happened during processing.") + + return pd.DataFrame.from_records(records) diff --git a/OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/datasets/ABO.py b/OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/datasets/ABO.py new file mode 100644 index 0000000000000000000000000000000000000000..b0aba22c2c4980b024091058a458811ab93805dd --- /dev/null +++ b/OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/datasets/ABO.py @@ -0,0 +1,96 @@ +import os +import re +import argparse +import tarfile +from concurrent.futures import ThreadPoolExecutor +from tqdm import tqdm +import pandas as pd +from utils import get_file_hash + + +def add_args(parser: argparse.ArgumentParser): + pass + + +def get_metadata(**kwargs): + metadata = pd.read_csv("hf://datasets/JeffreyXiang/TRELLIS-500K/ABO.csv") + return metadata + + +def download(metadata, output_dir, **kwargs): + os.makedirs(os.path.join(output_dir, 'raw'), exist_ok=True) + + if not os.path.exists(os.path.join(output_dir, 'raw', 'abo-3dmodels.tar')): + try: + os.makedirs(os.path.join(output_dir, 'raw'), exist_ok=True) + os.system(f"wget -O {output_dir}/raw/abo-3dmodels.tar https://amazon-berkeley-objects.s3.amazonaws.com/archives/abo-3dmodels.tar") + except: + print("\033[93m") + print("Error downloading ABO dataset. Please check your internet connection and try again.") + print("Or, you can manually download the abo-3dmodels.tar file and place it in the {output_dir}/raw directory") + print("Visit https://amazon-berkeley-objects.s3.amazonaws.com/index.html for more information") + print("\033[0m") + raise FileNotFoundError("Error downloading ABO dataset") + + downloaded = {} + metadata = metadata.set_index("file_identifier") + with tarfile.open(os.path.join(output_dir, 'raw', 'abo-3dmodels.tar')) as tar: + with ThreadPoolExecutor(max_workers=1) as executor, \ + tqdm(total=len(metadata), desc="Extracting") as pbar: + def worker(instance: str) -> str: + try: + tar.extract(f"3dmodels/original/{instance}", path=os.path.join(output_dir, 'raw')) + sha256 = get_file_hash(os.path.join(output_dir, 'raw/3dmodels/original', instance)) + pbar.update() + return sha256 + except Exception as e: + pbar.update() + print(f"Error extracting for {instance}: {e}") + return None + + sha256s = executor.map(worker, metadata.index) + executor.shutdown(wait=True) + + for k, sha256 in zip(metadata.index, sha256s): + if sha256 is not None: + if sha256 == metadata.loc[k, "sha256"]: + downloaded[sha256] = os.path.join('raw/3dmodels/original', k) + else: + print(f"Error downloading {k}: sha256s do not match") + + return pd.DataFrame(downloaded.items(), columns=['sha256', 'local_path']) + + +def foreach_instance(metadata, output_dir, func, max_workers=None, desc='Processing objects') -> pd.DataFrame: + import os + from concurrent.futures import ThreadPoolExecutor + from tqdm import tqdm + + # load metadata + metadata = metadata.to_dict('records') + + # processing objects + records = [] + max_workers = max_workers or os.cpu_count() + try: + with ThreadPoolExecutor(max_workers=max_workers) as executor, \ + tqdm(total=len(metadata), desc=desc) as pbar: + def worker(metadatum): + try: + local_path = metadatum['local_path'] + sha256 = metadatum['sha256'] + file = os.path.join(output_dir, local_path) + record = func(file, sha256) + if record is not None: + records.append(record) + pbar.update() + except Exception as e: + print(f"Error processing object {sha256}: {e}") + pbar.update() + + executor.map(worker, metadata) + executor.shutdown(wait=True) + except: + print("Error happened during processing.") + + return pd.DataFrame.from_records(records) diff --git a/OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/datasets/HSSD.py b/OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/datasets/HSSD.py new file mode 100644 index 0000000000000000000000000000000000000000..465e6a140010d0b33ba6435e8129825599dda5db --- /dev/null +++ b/OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/datasets/HSSD.py @@ -0,0 +1,103 @@ +import os +import re +import argparse +import tarfile +from concurrent.futures import ThreadPoolExecutor +from tqdm import tqdm +import pandas as pd +import huggingface_hub +from utils import get_file_hash + + +def add_args(parser: argparse.ArgumentParser): + pass + + +def get_metadata(**kwargs): + metadata = pd.read_csv("hf://datasets/JeffreyXiang/TRELLIS-500K/HSSD.csv") + return metadata + + +def download(metadata, output_dir, **kwargs): + os.makedirs(os.path.join(output_dir, 'raw'), exist_ok=True) + + # check login + try: + huggingface_hub.whoami() + except: + print("\033[93m") + print("Haven't logged in to the Hugging Face Hub.") + print("Visit https://huggingface.co/settings/tokens to get a token.") + print("\033[0m") + huggingface_hub.login() + + try: + huggingface_hub.hf_hub_download(repo_id="hssd/hssd-models", filename="README.md", repo_type="dataset") + except: + print("\033[93m") + print("Error downloading HSSD dataset.") + print("Check if you have access to the HSSD dataset.") + print("Visit https://huggingface.co/datasets/hssd/hssd-models for more information") + print("\033[0m") + + downloaded = {} + metadata = metadata.set_index("file_identifier") + with ThreadPoolExecutor(max_workers=os.cpu_count()) as executor, \ + tqdm(total=len(metadata), desc="Downloading") as pbar: + def worker(instance: str) -> str: + try: + huggingface_hub.hf_hub_download(repo_id="hssd/hssd-models", filename=instance, repo_type="dataset", local_dir=os.path.join(output_dir, 'raw')) + sha256 = get_file_hash(os.path.join(output_dir, 'raw', instance)) + pbar.update() + return sha256 + except Exception as e: + pbar.update() + print(f"Error extracting for {instance}: {e}") + return None + + sha256s = executor.map(worker, metadata.index) + executor.shutdown(wait=True) + + for k, sha256 in zip(metadata.index, sha256s): + if sha256 is not None: + if sha256 == metadata.loc[k, "sha256"]: + downloaded[sha256] = os.path.join('raw', k) + else: + print(f"Error downloading {k}: sha256s do not match") + + return pd.DataFrame(downloaded.items(), columns=['sha256', 'local_path']) + + +def foreach_instance(metadata, output_dir, func, max_workers=None, desc='Processing objects') -> pd.DataFrame: + import os + from concurrent.futures import ThreadPoolExecutor + from tqdm import tqdm + + # load metadata + metadata = metadata.to_dict('records') + + # processing objects + records = [] + max_workers = max_workers or os.cpu_count() + try: + with ThreadPoolExecutor(max_workers=max_workers) as executor, \ + tqdm(total=len(metadata), desc=desc) as pbar: + def worker(metadatum): + try: + local_path = metadatum['local_path'] + sha256 = metadatum['sha256'] + file = os.path.join(output_dir, local_path) + record = func(file, sha256) + if record is not None: + records.append(record) + pbar.update() + except Exception as e: + print(f"Error processing object {sha256}: {e}") + pbar.update() + + executor.map(worker, metadata) + executor.shutdown(wait=True) + except: + print("Error happened during processing.") + + return pd.DataFrame.from_records(records) diff --git a/OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/datasets/ObjaverseXL.py b/OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/datasets/ObjaverseXL.py new file mode 100644 index 0000000000000000000000000000000000000000..b2f5c76c07701b198a20af32fc87c81614ae7f79 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/datasets/ObjaverseXL.py @@ -0,0 +1,92 @@ +import os +import argparse +from concurrent.futures import ThreadPoolExecutor +from tqdm import tqdm +import pandas as pd +import objaverse.xl as oxl +from utils import get_file_hash + + +def add_args(parser: argparse.ArgumentParser): + parser.add_argument('--source', type=str, default='sketchfab', + help='Data source to download annotations from (github, sketchfab)') + + +def get_metadata(source, **kwargs): + if source == 'sketchfab': + metadata = pd.read_csv("hf://datasets/JeffreyXiang/TRELLIS-500K/ObjaverseXL_sketchfab.csv") + elif source == 'github': + metadata = pd.read_csv("hf://datasets/JeffreyXiang/TRELLIS-500K/ObjaverseXL_github.csv") + else: + raise ValueError(f"Invalid source: {source}") + return metadata + + +def download(metadata, output_dir, **kwargs): + os.makedirs(os.path.join(output_dir, 'raw'), exist_ok=True) + + # download annotations + annotations = oxl.get_annotations() + annotations = annotations[annotations['sha256'].isin(metadata['sha256'].values)] + + # download and render objects + file_paths = oxl.download_objects( + annotations, + download_dir=os.path.join(output_dir, "raw"), + save_repo_format="zip", + ) + + downloaded = {} + metadata = metadata.set_index("file_identifier") + for k, v in file_paths.items(): + sha256 = metadata.loc[k, "sha256"] + downloaded[sha256] = os.path.relpath(v, output_dir) + + return pd.DataFrame(downloaded.items(), columns=['sha256', 'local_path']) + + +def foreach_instance(metadata, output_dir, func, max_workers=None, desc='Processing objects') -> pd.DataFrame: + import os + from concurrent.futures import ThreadPoolExecutor + from tqdm import tqdm + import tempfile + import zipfile + + # load metadata + metadata = metadata.to_dict('records') + + # processing objects + records = [] + max_workers = max_workers or os.cpu_count() + try: + with ThreadPoolExecutor(max_workers=max_workers) as executor, \ + tqdm(total=len(metadata), desc=desc) as pbar: + def worker(metadatum): + try: + local_path = metadatum['local_path'] + sha256 = metadatum['sha256'] + if local_path.startswith('raw/github/repos/'): + path_parts = local_path.split('/') + file_name = os.path.join(*path_parts[5:]) + zip_file = os.path.join(output_dir, *path_parts[:5]) + with tempfile.TemporaryDirectory() as tmp_dir: + with zipfile.ZipFile(zip_file, 'r') as zip_ref: + zip_ref.extractall(tmp_dir) + file = os.path.join(tmp_dir, file_name) + record = func(file, sha256) + else: + file = os.path.join(output_dir, local_path) + record = func(file, sha256) + if record is not None: + records.append(record) + pbar.update() + except Exception as e: + print(f"Error processing object {sha256}: {e}") + pbar.update() + + executor.map(worker, metadata) + executor.shutdown(wait=True) + except: + print("Error happened during processing.") + + return pd.DataFrame.from_records(records) diff --git a/OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/datasets/Toys4k.py b/OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/datasets/Toys4k.py new file mode 100644 index 0000000000000000000000000000000000000000..378afdaa87b1b2a5962a33e7e55efa9540f28436 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/datasets/Toys4k.py @@ -0,0 +1,92 @@ +import os +import re +import argparse +import zipfile +from concurrent.futures import ThreadPoolExecutor +from tqdm import tqdm +import pandas as pd +from utils import get_file_hash + + +def add_args(parser: argparse.ArgumentParser): + pass + + +def get_metadata(**kwargs): + metadata = pd.read_csv("hf://datasets/JeffreyXiang/TRELLIS-500K/Toys4k.csv") + return metadata + + +def download(metadata, output_dir, **kwargs): + os.makedirs(output_dir, exist_ok=True) + + if not os.path.exists(os.path.join(output_dir, 'raw', 'toys4k_blend_files.zip')): + print("\033[93m") + print("Toys4k have to be downloaded manually") + print(f"Please download the toys4k_blend_files.zip file and place it in the {output_dir}/raw directory") + print("Visit https://github.com/rehg-lab/lowshot-shapebias/tree/main/toys4k for more information") + print("\033[0m") + raise FileNotFoundError("toys4k_blend_files.zip not found") + + downloaded = {} + metadata = metadata.set_index("file_identifier") + with zipfile.ZipFile(os.path.join(output_dir, 'raw', 'toys4k_blend_files.zip')) as zip_ref: + with ThreadPoolExecutor(max_workers=os.cpu_count()) as executor, \ + tqdm(total=len(metadata), desc="Extracting") as pbar: + def worker(instance: str) -> str: + try: + zip_ref.extract(os.path.join('toys4k_blend_files', instance), os.path.join(output_dir, 'raw')) + sha256 = get_file_hash(os.path.join(output_dir, 'raw/toys4k_blend_files', instance)) + pbar.update() + return sha256 + except Exception as e: + pbar.update() + print(f"Error extracting for {instance}: {e}") + return None + + sha256s = executor.map(worker, metadata.index) + executor.shutdown(wait=True) + + for k, sha256 in zip(metadata.index, sha256s): + if sha256 is not None: + if sha256 == metadata.loc[k, "sha256"]: + downloaded[sha256] = os.path.join("raw/toys4k_blend_files", k) + else: + print(f"Error downloading {k}: sha256s do not match") + + return pd.DataFrame(downloaded.items(), columns=['sha256', 'local_path']) + + +def foreach_instance(metadata, output_dir, func, max_workers=None, desc='Processing objects') -> pd.DataFrame: + import os + from concurrent.futures import ThreadPoolExecutor + from tqdm import tqdm + + # load metadata + metadata = metadata.to_dict('records') + + # processing objects + records = [] + max_workers = max_workers or os.cpu_count() + try: + with ThreadPoolExecutor(max_workers=max_workers) as executor, \ + tqdm(total=len(metadata), desc=desc) as pbar: + def worker(metadatum): + try: + local_path = metadatum['local_path'] + sha256 = metadatum['sha256'] + file = os.path.join(output_dir, local_path) + record = func(file, sha256) + if record is not None: + records.append(record) + pbar.update() + except Exception as e: + print(f"Error processing object {sha256}: {e}") + pbar.update() + + executor.map(worker, metadata) + executor.shutdown(wait=True) + except: + print("Error happened during processing.") + + return pd.DataFrame.from_records(records) diff --git a/OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/download.py b/OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/download.py new file mode 100644 index 0000000000000000000000000000000000000000..36e684ff5e61105d8c69c101291dc8fa4415af3d --- /dev/null +++ b/OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/download.py @@ -0,0 +1,52 @@ +import os +import copy +import sys +import importlib +import argparse +import pandas as pd +from easydict import EasyDict as edict + +if __name__ == '__main__': + dataset_utils = importlib.import_module(f'datasets.{sys.argv[1]}') + + parser = argparse.ArgumentParser() + parser.add_argument('--output_dir', type=str, required=True, + help='Directory to save the metadata') + parser.add_argument('--filter_low_aesthetic_score', type=float, default=None, + help='Filter objects with aesthetic score lower than this value') + parser.add_argument('--instances', type=str, default=None, + help='Instances to process') + dataset_utils.add_args(parser) + parser.add_argument('--rank', type=int, default=0) + parser.add_argument('--world_size', type=int, default=1) + opt = parser.parse_args(sys.argv[2:]) + opt = edict(vars(opt)) + + os.makedirs(opt.output_dir, exist_ok=True) + + # get file list + if not os.path.exists(os.path.join(opt.output_dir, 'metadata.csv')): + raise ValueError('metadata.csv not found') + metadata = pd.read_csv(os.path.join(opt.output_dir, 'metadata.csv')) + if opt.instances is None: + if opt.filter_low_aesthetic_score is not None: + metadata = metadata[metadata['aesthetic_score'] >= opt.filter_low_aesthetic_score] + if 'local_path' in metadata.columns: + metadata = metadata[metadata['local_path'].isna()] + else: + if os.path.exists(opt.instances): + with open(opt.instances, 'r') as f: + instances = f.read().splitlines() + else: + instances = opt.instances.split(',') + metadata = metadata[metadata['sha256'].isin(instances)] + + start = len(metadata) * opt.rank // opt.world_size + end = len(metadata) * (opt.rank + 1) // opt.world_size + metadata = metadata[start:end] + + print(f'Processing {len(metadata)} objects...') + + # process objects + downloaded = dataset_utils.download(metadata, **opt) + downloaded.to_csv(os.path.join(opt.output_dir, f'downloaded_{opt.rank}.csv'), index=False) diff --git a/OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/encode_latent.py b/OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/encode_latent.py new file mode 100644 index 0000000000000000000000000000000000000000..a5b078f833b2c1c0868956e4b37db36cfd22b31b --- /dev/null +++ b/OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/encode_latent.py @@ -0,0 +1,127 @@ +import os +import sys +sys.path.append(os.path.join(os.path.dirname(__file__), '..')) +import copy +import json +import argparse +import torch +import numpy as np +import pandas as pd +from tqdm import tqdm +from easydict import EasyDict as edict +from concurrent.futures import ThreadPoolExecutor +from queue import Queue + +import trellis.models as models +import trellis.modules.sparse as sp + + +torch.set_grad_enabled(False) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('--output_dir', type=str, required=True, + help='Directory to save the metadata') + parser.add_argument('--filter_low_aesthetic_score', type=float, default=None, + help='Filter objects with aesthetic score lower than this value') + parser.add_argument('--feat_model', type=str, default='dinov2_vitl14_reg', + help='Feature model') + parser.add_argument('--enc_pretrained', type=str, default='microsoft/TRELLIS-image-large/ckpts/slat_enc_swin8_B_64l8_fp16', + help='Pretrained encoder model') + parser.add_argument('--model_root', type=str, default='results', + help='Root directory of models') + parser.add_argument('--enc_model', type=str, default=None, + help='Encoder model. if specified, use this model instead of pretrained model') + parser.add_argument('--ckpt', type=str, default=None, + help='Checkpoint to load') + parser.add_argument('--instances', type=str, default=None, + help='Instances to process') + parser.add_argument('--rank', type=int, default=0) + parser.add_argument('--world_size', type=int, default=1) + opt = parser.parse_args() + opt = edict(vars(opt)) + + if opt.enc_model is None: + latent_name = f'{opt.feat_model}_{opt.enc_pretrained.split("/")[-1]}' + encoder = models.from_pretrained(opt.enc_pretrained).eval().cuda() + else: + latent_name = f'{opt.feat_model}_{opt.enc_model}_{opt.ckpt}' + cfg = edict(json.load(open(os.path.join(opt.model_root, opt.enc_model, 'config.json'), 'r'))) + encoder = getattr(models, cfg.models.encoder.name)(**cfg.models.encoder.args).cuda() + ckpt_path = os.path.join(opt.model_root, opt.enc_model, 'ckpts', f'encoder_{opt.ckpt}.pt') + encoder.load_state_dict(torch.load(ckpt_path), strict=False) + encoder.eval() + print(f'Loaded model from {ckpt_path}') + + os.makedirs(os.path.join(opt.output_dir, 'latents', latent_name), exist_ok=True) + + # get file list + if os.path.exists(os.path.join(opt.output_dir, 'metadata.csv')): + metadata = pd.read_csv(os.path.join(opt.output_dir, 'metadata.csv')) + else: + raise ValueError('metadata.csv not found') + if opt.instances is not None: + with open(opt.instances, 'r') as f: + sha256s = [line.strip() for line in f] + metadata = metadata[metadata['sha256'].isin(sha256s)] + else: + if opt.filter_low_aesthetic_score is not None: + metadata = metadata[metadata['aesthetic_score'] >= opt.filter_low_aesthetic_score] + metadata = metadata[metadata[f'feature_{opt.feat_model}'] == True] + if f'latent_{latent_name}' in metadata.columns: + metadata = metadata[metadata[f'latent_{latent_name}'] == False] + + start = len(metadata) * opt.rank // opt.world_size + end = len(metadata) * (opt.rank + 1) // opt.world_size + metadata = metadata[start:end] + records = [] + + # filter out objects that are already processed + sha256s = list(metadata['sha256'].values) + for sha256 in copy.copy(sha256s): + if os.path.exists(os.path.join(opt.output_dir, 'latents', latent_name, f'{sha256}.npz')): + records.append({'sha256': sha256, f'latent_{latent_name}': True}) + sha256s.remove(sha256) + + # encode latents + load_queue = Queue(maxsize=4) + try: + with ThreadPoolExecutor(max_workers=32) as loader_executor, \ + ThreadPoolExecutor(max_workers=32) as saver_executor: + def loader(sha256): + try: + feats = np.load(os.path.join(opt.output_dir, 'features', opt.feat_model, f'{sha256}.npz')) + load_queue.put((sha256, feats)) + except Exception as e: + print(f"Error loading features for {sha256}: {e}") + loader_executor.map(loader, sha256s) + + def saver(sha256, pack): + save_path = os.path.join(opt.output_dir, 'latents', latent_name, f'{sha256}.npz') + np.savez_compressed(save_path, **pack) + records.append({'sha256': sha256, f'latent_{latent_name}': True}) + + for _ in tqdm(range(len(sha256s)), desc="Extracting latents"): + sha256, feats = load_queue.get() + feats = sp.SparseTensor( + feats = torch.from_numpy(feats['patchtokens']).float(), + coords = torch.cat([ + torch.zeros(feats['patchtokens'].shape[0], 1).int(), + torch.from_numpy(feats['indices']).int(), + ], dim=1), + ).cuda() + latent = encoder(feats, sample_posterior=False) + assert torch.isfinite(latent.feats).all(), "Non-finite latent" + pack = { + 'feats': latent.feats.cpu().numpy().astype(np.float32), + 'coords': latent.coords[:, 1:].cpu().numpy().astype(np.uint8), + } + saver_executor.submit(saver, sha256, pack) + + saver_executor.shutdown(wait=True) + except: + print("Error happened during processing.") + + records = pd.DataFrame.from_records(records) + records.to_csv(os.path.join(opt.output_dir, f'latent_{latent_name}_{opt.rank}.csv'), index=False) diff --git a/OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/encode_ss_latent.py b/OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/encode_ss_latent.py new file mode 100644 index 0000000000000000000000000000000000000000..a59549ee58d68aa0cc393cf0319bcbe32efb62f3 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/encode_ss_latent.py @@ -0,0 +1,128 @@ +import os +import sys +sys.path.append(os.path.join(os.path.dirname(__file__), '..')) +import copy +import json +import argparse +import torch +import numpy as np +import pandas as pd +import utils3d +from tqdm import tqdm +from easydict import EasyDict as edict +from concurrent.futures import ThreadPoolExecutor +from queue import Queue + +import trellis.models as models + + +torch.set_grad_enabled(False) + + +def get_voxels(instance): + position = utils3d.io.read_ply(os.path.join(opt.output_dir, 'voxels', f'{instance}.ply'))[0] + coords = ((torch.tensor(position) + 0.5) * opt.resolution).int().contiguous() + ss = torch.zeros(1, opt.resolution, opt.resolution, opt.resolution, dtype=torch.long) + ss[:, coords[:, 0], coords[:, 1], coords[:, 2]] = 1 + return ss + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('--output_dir', type=str, required=True, + help='Directory to save the metadata') + parser.add_argument('--filter_low_aesthetic_score', type=float, default=None, + help='Filter objects with aesthetic score lower than this value') + parser.add_argument('--enc_pretrained', type=str, default='microsoft/TRELLIS-image-large/ckpts/ss_enc_conv3d_16l8_fp16', + help='Pretrained encoder model') + parser.add_argument('--model_root', type=str, default='results', + help='Root directory of models') + parser.add_argument('--enc_model', type=str, default=None, + help='Encoder model. if specified, use this model instead of pretrained model') + parser.add_argument('--ckpt', type=str, default=None, + help='Checkpoint to load') + parser.add_argument('--resolution', type=int, default=64, + help='Resolution') + parser.add_argument('--instances', type=str, default=None, + help='Instances to process') + parser.add_argument('--rank', type=int, default=0) + parser.add_argument('--world_size', type=int, default=1) + opt = parser.parse_args() + opt = edict(vars(opt)) + + if opt.enc_model is None: + latent_name = f'{opt.enc_pretrained.split("/")[-1]}' + encoder = models.from_pretrained(opt.enc_pretrained).eval().cuda() + else: + latent_name = f'{opt.enc_model}_{opt.ckpt}' + cfg = edict(json.load(open(os.path.join(opt.model_root, opt.enc_model, 'config.json'), 'r'))) + encoder = getattr(models, cfg.models.encoder.name)(**cfg.models.encoder.args).cuda() + ckpt_path = os.path.join(opt.model_root, opt.enc_model, 'ckpts', f'encoder_{opt.ckpt}.pt') + encoder.load_state_dict(torch.load(ckpt_path), strict=False) + encoder.eval() + print(f'Loaded model from {ckpt_path}') + + os.makedirs(os.path.join(opt.output_dir, 'ss_latents', latent_name), exist_ok=True) + + # get file list + if os.path.exists(os.path.join(opt.output_dir, 'metadata.csv')): + metadata = pd.read_csv(os.path.join(opt.output_dir, 'metadata.csv')) + else: + raise ValueError('metadata.csv not found') + if opt.instances is not None: + with open(opt.instances, 'r') as f: + instances = f.read().splitlines() + metadata = metadata[metadata['sha256'].isin(instances)] + else: + if opt.filter_low_aesthetic_score is not None: + metadata = metadata[metadata['aesthetic_score'] >= opt.filter_low_aesthetic_score] + metadata = metadata[metadata['voxelized'] == True] + if f'ss_latent_{latent_name}' in metadata.columns: + metadata = metadata[metadata[f'ss_latent_{latent_name}'] == False] + + start = len(metadata) * opt.rank // opt.world_size + end = len(metadata) * (opt.rank + 1) // opt.world_size + metadata = metadata[start:end] + records = [] + + # filter out objects that are already processed + sha256s = list(metadata['sha256'].values) + for sha256 in copy.copy(sha256s): + if os.path.exists(os.path.join(opt.output_dir, 'ss_latents', latent_name, f'{sha256}.npz')): + records.append({'sha256': sha256, f'ss_latent_{latent_name}': True}) + sha256s.remove(sha256) + + # encode latents + load_queue = Queue(maxsize=4) + try: + with ThreadPoolExecutor(max_workers=32) as loader_executor, \ + ThreadPoolExecutor(max_workers=32) as saver_executor: + def loader(sha256): + try: + ss = get_voxels(sha256)[None].float() + load_queue.put((sha256, ss)) + except Exception as e: + print(f"Error loading features for {sha256}: {e}") + loader_executor.map(loader, sha256s) + + def saver(sha256, pack): + save_path = os.path.join(opt.output_dir, 'ss_latents', latent_name, f'{sha256}.npz') + np.savez_compressed(save_path, **pack) + records.append({'sha256': sha256, f'ss_latent_{latent_name}': True}) + + for _ in tqdm(range(len(sha256s)), desc="Extracting latents"): + sha256, ss = load_queue.get() + ss = ss.cuda().float() + latent = encoder(ss, sample_posterior=False) + assert torch.isfinite(latent).all(), "Non-finite latent" + pack = { + 'mean': latent[0].cpu().numpy(), + } + saver_executor.submit(saver, sha256, pack) + + saver_executor.shutdown(wait=True) + except: + print("Error happened during processing.") + + records = pd.DataFrame.from_records(records) + records.to_csv(os.path.join(opt.output_dir, f'ss_latent_{latent_name}_{opt.rank}.csv'), index=False) diff --git a/OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/extract_feature.py b/OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/extract_feature.py new file mode 100644 index 0000000000000000000000000000000000000000..1ded2fe03b3e4355da00af429c9439a68069308a --- /dev/null +++ b/OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/extract_feature.py @@ -0,0 +1,179 @@ +import os +import copy +import sys +import json +import importlib +import argparse +import torch +import torch.nn.functional as F +import numpy as np +import pandas as pd +import utils3d +from tqdm import tqdm +from easydict import EasyDict as edict +from concurrent.futures import ThreadPoolExecutor +from queue import Queue +from torchvision import transforms +from PIL import Image + + +torch.set_grad_enabled(False) + + +def get_data(frames, sha256): + with ThreadPoolExecutor(max_workers=16) as executor: + def worker(view): + image_path = os.path.join(opt.output_dir, 'renders', sha256, view['file_path']) + try: + image = Image.open(image_path) + except: + print(f"Error loading image {image_path}") + return None + image = image.resize((518, 518), Image.Resampling.LANCZOS) + image = np.array(image).astype(np.float32) / 255 + image = image[:, :, :3] * image[:, :, 3:] + image = torch.from_numpy(image).permute(2, 0, 1).float() + + c2w = torch.tensor(view['transform_matrix']) + c2w[:3, 1:3] *= -1 + extrinsics = torch.inverse(c2w) + fov = view['camera_angle_x'] + intrinsics = utils3d.torch.intrinsics_from_fov_xy(torch.tensor(fov), torch.tensor(fov)) + + return { + 'image': image, + 'extrinsics': extrinsics, + 'intrinsics': intrinsics + } + + datas = executor.map(worker, frames) + for data in datas: + if data is not None: + yield data + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('--output_dir', type=str, required=True, + help='Directory to save the metadata') + parser.add_argument('--filter_low_aesthetic_score', type=float, default=None, + help='Filter objects with aesthetic score lower than this value') + parser.add_argument('--model', type=str, default='dinov2_vitl14_reg', + help='Feature extraction model') + parser.add_argument('--instances', type=str, default=None, + help='Instances to process') + parser.add_argument('--batch_size', type=int, default=16) + parser.add_argument('--rank', type=int, default=0) + parser.add_argument('--world_size', type=int, default=1) + opt = parser.parse_args() + opt = edict(vars(opt)) + + feature_name = opt.model + os.makedirs(os.path.join(opt.output_dir, 'features', feature_name), exist_ok=True) + + # load model + dinov2_model = torch.hub.load('facebookresearch/dinov2', opt.model) + dinov2_model.eval().cuda() + transform = transforms.Compose([ + transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), + ]) + n_patch = 518 // 14 + + # get file list + if os.path.exists(os.path.join(opt.output_dir, 'metadata.csv')): + metadata = pd.read_csv(os.path.join(opt.output_dir, 'metadata.csv')) + else: + raise ValueError('metadata.csv not found') + if opt.instances is not None: + with open(opt.instances, 'r') as f: + instances = f.read().splitlines() + metadata = metadata[metadata['sha256'].isin(instances)] + else: + if opt.filter_low_aesthetic_score is not None: + metadata = metadata[metadata['aesthetic_score'] >= opt.filter_low_aesthetic_score] + if f'feature_{feature_name}' in metadata.columns: + metadata = metadata[metadata[f'feature_{feature_name}'] == False] + metadata = metadata[metadata['voxelized'] == True] + metadata = metadata[metadata['rendered'] == True] + + start = len(metadata) * opt.rank // opt.world_size + end = len(metadata) * (opt.rank + 1) // opt.world_size + metadata = metadata[start:end] + records = [] + + # filter out objects that are already processed + sha256s = list(metadata['sha256'].values) + for sha256 in copy.copy(sha256s): + if os.path.exists(os.path.join(opt.output_dir, 'features', feature_name, f'{sha256}.npz')): + records.append({'sha256': sha256, f'feature_{feature_name}' : True}) + sha256s.remove(sha256) + + # extract features + load_queue = Queue(maxsize=4) + try: + with ThreadPoolExecutor(max_workers=8) as loader_executor, \ + ThreadPoolExecutor(max_workers=8) as saver_executor: + def loader(sha256): + try: + with open(os.path.join(opt.output_dir, 'renders', sha256, 'transforms.json'), 'r') as f: + metadata = json.load(f) + frames = metadata['frames'] + data = [] + for datum in get_data(frames, sha256): + datum['image'] = transform(datum['image']) + data.append(datum) + positions = utils3d.io.read_ply(os.path.join(opt.output_dir, 'voxels', f'{sha256}.ply'))[0] + load_queue.put((sha256, data, positions)) + except Exception as e: + print(f"Error loading data for {sha256}: {e}") + + loader_executor.map(loader, sha256s) + + def saver(sha256, pack, patchtokens, uv): + pack['patchtokens'] = F.grid_sample( + patchtokens, + uv.unsqueeze(1), + mode='bilinear', + align_corners=False, + ).squeeze(2).permute(0, 2, 1).cpu().numpy() + pack['patchtokens'] = np.mean(pack['patchtokens'], axis=0).astype(np.float16) + save_path = os.path.join(opt.output_dir, 'features', feature_name, f'{sha256}.npz') + np.savez_compressed(save_path, **pack) + records.append({'sha256': sha256, f'feature_{feature_name}' : True}) + + for _ in tqdm(range(len(sha256s)), desc="Extracting features"): + sha256, data, positions = load_queue.get() + positions = torch.from_numpy(positions).float().cuda() + indices = ((positions + 0.5) * 64).long() + assert torch.all(indices >= 0) and torch.all(indices < 64), "Some vertices are out of bounds" + n_views = len(data) + N = positions.shape[0] + pack = { + 'indices': indices.cpu().numpy().astype(np.uint8), + } + patchtokens_lst = [] + uv_lst = [] + for i in range(0, n_views, opt.batch_size): + batch_data = data[i:i+opt.batch_size] + bs = len(batch_data) + batch_images = torch.stack([d['image'] for d in batch_data]).cuda() + batch_extrinsics = torch.stack([d['extrinsics'] for d in batch_data]).cuda() + batch_intrinsics = torch.stack([d['intrinsics'] for d in batch_data]).cuda() + features = dinov2_model(batch_images, is_training=True) + uv = utils3d.torch.project_cv(positions, batch_extrinsics, batch_intrinsics)[0] * 2 - 1 + patchtokens = features['x_prenorm'][:, dinov2_model.num_register_tokens + 1:].permute(0, 2, 1).reshape(bs, 1024, n_patch, n_patch) + patchtokens_lst.append(patchtokens) + uv_lst.append(uv) + patchtokens = torch.cat(patchtokens_lst, dim=0) + uv = torch.cat(uv_lst, dim=0) + + # save features + saver_executor.submit(saver, sha256, pack, patchtokens, uv) + + saver_executor.shutdown(wait=True) + except: + print("Error happened during processing.") + + records = pd.DataFrame.from_records(records) + records.to_csv(os.path.join(opt.output_dir, f'feature_{feature_name}_{opt.rank}.csv'), index=False) + \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/render.py b/OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/render.py new file mode 100644 index 0000000000000000000000000000000000000000..636f3b308fa9a33e1304b6b64370221167885118 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/render.py @@ -0,0 +1,121 @@ +import os +import json +import copy +import sys +import importlib +import argparse +import pandas as pd +from easydict import EasyDict as edict +from functools import partial +from subprocess import DEVNULL, call +import numpy as np +from utils import sphere_hammersley_sequence + + +BLENDER_LINK = 'https://download.blender.org/release/Blender3.0/blender-3.0.1-linux-x64.tar.xz' +BLENDER_INSTALLATION_PATH = '/tmp' +BLENDER_PATH = f'{BLENDER_INSTALLATION_PATH}/blender-3.0.1-linux-x64/blender' + +def _install_blender(): + if not os.path.exists(BLENDER_PATH): + os.system('sudo apt-get update') + os.system('sudo apt-get install -y libxrender1 libxi6 libxkbcommon-x11-0 libsm6') + os.system(f'wget {BLENDER_LINK} -P {BLENDER_INSTALLATION_PATH}') + os.system(f'tar -xvf {BLENDER_INSTALLATION_PATH}/blender-3.0.1-linux-x64.tar.xz -C {BLENDER_INSTALLATION_PATH}') + + +def _render(file_path, sha256, output_dir, num_views): + output_folder = os.path.join(output_dir, 'renders', sha256) + + # Build camera {yaw, pitch, radius, fov} + yaws = [] + pitchs = [] + offset = (np.random.rand(), np.random.rand()) + for i in range(num_views): + y, p = sphere_hammersley_sequence(i, num_views, offset) + yaws.append(y) + pitchs.append(p) + radius = [2] * num_views + fov = [40 / 180 * np.pi] * num_views + views = [{'yaw': y, 'pitch': p, 'radius': r, 'fov': f} for y, p, r, f in zip(yaws, pitchs, radius, fov)] + + args = [ + BLENDER_PATH, '-b', '-P', os.path.join(os.path.dirname(__file__), 'blender_script', 'render.py'), + '--', + '--views', json.dumps(views), + '--object', os.path.expanduser(file_path), + '--resolution', '512', + '--output_folder', output_folder, + '--engine', 'CYCLES', + '--save_mesh', + ] + if file_path.endswith('.blend'): + args.insert(1, file_path) + + call(args, stdout=DEVNULL, stderr=DEVNULL) + + if os.path.exists(os.path.join(output_folder, 'transforms.json')): + return {'sha256': sha256, 'rendered': True} + + +if __name__ == '__main__': + dataset_utils = importlib.import_module(f'datasets.{sys.argv[1]}') + + parser = argparse.ArgumentParser() + parser.add_argument('--output_dir', type=str, required=True, + help='Directory to save the metadata') + parser.add_argument('--filter_low_aesthetic_score', type=float, default=None, + help='Filter objects with aesthetic score lower than this value') + parser.add_argument('--instances', type=str, default=None, + help='Instances to process') + parser.add_argument('--num_views', type=int, default=150, + help='Number of views to render') + dataset_utils.add_args(parser) + parser.add_argument('--rank', type=int, default=0) + parser.add_argument('--world_size', type=int, default=1) + parser.add_argument('--max_workers', type=int, default=8) + opt = parser.parse_args(sys.argv[2:]) + opt = edict(vars(opt)) + + os.makedirs(os.path.join(opt.output_dir, 'renders'), exist_ok=True) + + # install blender + print('Checking blender...', flush=True) + _install_blender() + + # get file list + if not os.path.exists(os.path.join(opt.output_dir, 'metadata.csv')): + raise ValueError('metadata.csv not found') + metadata = pd.read_csv(os.path.join(opt.output_dir, 'metadata.csv')) + if opt.instances is None: + metadata = metadata[metadata['local_path'].notna()] + if opt.filter_low_aesthetic_score is not None: + metadata = metadata[metadata['aesthetic_score'] >= opt.filter_low_aesthetic_score] + if 'rendered' in metadata.columns: + metadata = metadata[metadata['rendered'] == False] + else: + if os.path.exists(opt.instances): + with open(opt.instances, 'r') as f: + instances = f.read().splitlines() + else: + instances = opt.instances.split(',') + metadata = metadata[metadata['sha256'].isin(instances)] + + start = len(metadata) * opt.rank // opt.world_size + end = len(metadata) * (opt.rank + 1) // opt.world_size + metadata = metadata[start:end] + records = [] + + # filter out objects that are already processed + for sha256 in copy.copy(metadata['sha256'].values): + if os.path.exists(os.path.join(opt.output_dir, 'renders', sha256, 'transforms.json')): + records.append({'sha256': sha256, 'rendered': True}) + metadata = metadata[metadata['sha256'] != sha256] + + print(f'Processing {len(metadata)} objects...') + + # process objects + func = partial(_render, output_dir=opt.output_dir, num_views=opt.num_views) + rendered = dataset_utils.foreach_instance(metadata, opt.output_dir, func, max_workers=opt.max_workers, desc='Rendering objects') + rendered = pd.concat([rendered, pd.DataFrame.from_records(records)]) + rendered.to_csv(os.path.join(opt.output_dir, f'rendered_{opt.rank}.csv'), index=False) diff --git a/OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/render_cond.py b/OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/render_cond.py new file mode 100644 index 0000000000000000000000000000000000000000..b2a40e6d9974a9e7256571d9ed636f4a5758b5c7 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/render_cond.py @@ -0,0 +1,125 @@ +import os +import json +import copy +import sys +import importlib +import argparse +import pandas as pd +from easydict import EasyDict as edict +from functools import partial +from subprocess import DEVNULL, call +import numpy as np +from utils import sphere_hammersley_sequence + + +BLENDER_LINK = 'https://download.blender.org/release/Blender3.0/blender-3.0.1-linux-x64.tar.xz' +BLENDER_INSTALLATION_PATH = '/tmp' +BLENDER_PATH = f'{BLENDER_INSTALLATION_PATH}/blender-3.0.1-linux-x64/blender' + +def _install_blender(): + if not os.path.exists(BLENDER_PATH): + os.system('sudo apt-get update') + os.system('sudo apt-get install -y libxrender1 libxi6 libxkbcommon-x11-0 libsm6') + os.system(f'wget {BLENDER_LINK} -P {BLENDER_INSTALLATION_PATH}') + os.system(f'tar -xvf {BLENDER_INSTALLATION_PATH}/blender-3.0.1-linux-x64.tar.xz -C {BLENDER_INSTALLATION_PATH}') + + +def _render_cond(file_path, sha256, output_dir, num_views): + output_folder = os.path.join(output_dir, 'renders_cond', sha256) + + # Build camera {yaw, pitch, radius, fov} + yaws = [] + pitchs = [] + offset = (np.random.rand(), np.random.rand()) + for i in range(num_views): + y, p = sphere_hammersley_sequence(i, num_views, offset) + yaws.append(y) + pitchs.append(p) + fov_min, fov_max = 10, 70 + radius_min = np.sqrt(3) / 2 / np.sin(fov_max / 360 * np.pi) + radius_max = np.sqrt(3) / 2 / np.sin(fov_min / 360 * np.pi) + k_min = 1 / radius_max**2 + k_max = 1 / radius_min**2 + ks = np.random.uniform(k_min, k_max, (1000000,)) + radius = [1 / np.sqrt(k) for k in ks] + fov = [2 * np.arcsin(np.sqrt(3) / 2 / r) for r in radius] + views = [{'yaw': y, 'pitch': p, 'radius': r, 'fov': f} for y, p, r, f in zip(yaws, pitchs, radius, fov)] + + args = [ + BLENDER_PATH, '-b', '-P', os.path.join(os.path.dirname(__file__), 'blender_script', 'render.py'), + '--', + '--views', json.dumps(views), + '--object', os.path.expanduser(file_path), + '--output_folder', os.path.expanduser(output_folder), + '--resolution', '1024', + ] + if file_path.endswith('.blend'): + args.insert(1, file_path) + + call(args, stdout=DEVNULL) + + if os.path.exists(os.path.join(output_folder, 'transforms.json')): + return {'sha256': sha256, 'cond_rendered': True} + + +if __name__ == '__main__': + dataset_utils = importlib.import_module(f'datasets.{sys.argv[1]}') + + parser = argparse.ArgumentParser() + parser.add_argument('--output_dir', type=str, required=True, + help='Directory to save the metadata') + parser.add_argument('--filter_low_aesthetic_score', type=float, default=None, + help='Filter objects with aesthetic score lower than this value') + parser.add_argument('--instances', type=str, default=None, + help='Instances to process') + parser.add_argument('--num_views', type=int, default=24, + help='Number of views to render') + dataset_utils.add_args(parser) + parser.add_argument('--rank', type=int, default=0) + parser.add_argument('--world_size', type=int, default=1) + parser.add_argument('--max_workers', type=int, default=8) + opt = parser.parse_args(sys.argv[2:]) + opt = edict(vars(opt)) + + os.makedirs(os.path.join(opt.output_dir, 'renders_cond'), exist_ok=True) + + # install blender + print('Checking blender...', flush=True) + _install_blender() + + # get file list + if not os.path.exists(os.path.join(opt.output_dir, 'metadata.csv')): + raise ValueError('metadata.csv not found') + metadata = pd.read_csv(os.path.join(opt.output_dir, 'metadata.csv')) + if opt.instances is None: + metadata = metadata[metadata['local_path'].notna()] + if opt.filter_low_aesthetic_score is not None: + metadata = metadata[metadata['aesthetic_score'] >= opt.filter_low_aesthetic_score] + if 'cond_rendered' in metadata.columns: + metadata = metadata[metadata['cond_rendered'] == False] + else: + if os.path.exists(opt.instances): + with open(opt.instances, 'r') as f: + instances = f.read().splitlines() + else: + instances = opt.instances.split(',') + metadata = metadata[metadata['sha256'].isin(instances)] + + start = len(metadata) * opt.rank // opt.world_size + end = len(metadata) * (opt.rank + 1) // opt.world_size + metadata = metadata[start:end] + records = [] + + # filter out objects that are already processed + for sha256 in copy.copy(metadata['sha256'].values): + if os.path.exists(os.path.join(opt.output_dir, 'renders_cond', sha256, 'transforms.json')): + records.append({'sha256': sha256, 'cond_rendered': True}) + metadata = metadata[metadata['sha256'] != sha256] + + print(f'Processing {len(metadata)} objects...') + + # process objects + func = partial(_render_cond, output_dir=opt.output_dir, num_views=opt.num_views) + cond_rendered = dataset_utils.foreach_instance(metadata, opt.output_dir, func, max_workers=opt.max_workers, desc='Rendering objects') + cond_rendered = pd.concat([cond_rendered, pd.DataFrame.from_records(records)]) + cond_rendered.to_csv(os.path.join(opt.output_dir, f'cond_rendered_{opt.rank}.csv'), index=False) diff --git a/OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/setup.sh b/OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..e387ea4fe1f7d6b68ee7f5ccf07043f80bd624f4 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/setup.sh @@ -0,0 +1 @@ +pip install pillow imageio imageio-ffmpeg tqdm easydict opencv-python-headless pandas open3d objaverse huggingface_hub diff --git a/OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/stat_latent.py b/OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/stat_latent.py new file mode 100644 index 0000000000000000000000000000000000000000..7f27a062bb8be898ef6c705a3f3d9488f94299fe --- /dev/null +++ b/OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/stat_latent.py @@ -0,0 +1,66 @@ +import os +import json +import argparse +import numpy as np +import pandas as pd +from tqdm import tqdm +from easydict import EasyDict as edict +from concurrent.futures import ThreadPoolExecutor + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('--output_dir', type=str, required=True, + help='Directory to save the metadata') + parser.add_argument('--filter_low_aesthetic_score', type=float, default=None, + help='Filter objects with aesthetic score lower than this value') + parser.add_argument('--model', type=str, default='dinov2_vitl14_reg_slat_enc_swin8_B_64l8_fp16', + help='Latent model to use') + parser.add_argument('--num_samples', type=int, default=50000, + help='Number of samples to use for calculating stats') + opt = parser.parse_args() + opt = edict(vars(opt)) + + # get file list + if os.path.exists(os.path.join(opt.output_dir, 'metadata.csv')): + metadata = pd.read_csv(os.path.join(opt.output_dir, 'metadata.csv')) + else: + raise ValueError('metadata.csv not found') + if opt.filter_low_aesthetic_score is not None: + metadata = metadata[metadata['aesthetic_score'] >= opt.filter_low_aesthetic_score] + metadata = metadata[metadata[f'latent_{opt.model}'] == True] + sha256s = metadata['sha256'].values + sha256s = np.random.choice(sha256s, min(opt.num_samples, len(sha256s)), replace=False) + + # stats + means = [] + mean2s = [] + with ThreadPoolExecutor(max_workers=16) as executor, \ + tqdm(total=len(sha256s), desc="Extracting features") as pbar: + def worker(sha256): + try: + feats = np.load(os.path.join(opt.output_dir, 'latents', opt.model, f'{sha256}.npz')) + feats = feats['feats'] + means.append(feats.mean(axis=0)) + mean2s.append((feats ** 2).mean(axis=0)) + pbar.update() + except Exception as e: + print(f"Error extracting features for {sha256}: {e}") + pbar.update() + + executor.map(worker, sha256s) + executor.shutdown(wait=True) + + mean = np.array(means).mean(axis=0) + mean2 = np.array(mean2s).mean(axis=0) + std = np.sqrt(mean2 - mean ** 2) + + print('mean:', mean) + print('std:', std) + + with open(os.path.join(opt.output_dir, 'latents', opt.model, 'stats.json'), 'w') as f: + json.dump({ + 'mean': mean.tolist(), + 'std': std.tolist(), + }, f, indent=4) + \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/utils.py b/OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..69830845d40697bd2c4e7c68e64e54b4d4091a81 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/utils.py @@ -0,0 +1,43 @@ +from typing import * +import hashlib +import numpy as np + + +def get_file_hash(file: str) -> str: + sha256 = hashlib.sha256() + # Read the file from the path + with open(file, "rb") as f: + # Update the hash with the file content + for byte_block in iter(lambda: f.read(4096), b""): + sha256.update(byte_block) + return sha256.hexdigest() + +# ===============LOW DISCREPANCY SEQUENCES================ + +PRIMES = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53] + +def radical_inverse(base, n): + val = 0 + inv_base = 1.0 / base + inv_base_n = inv_base + while n > 0: + digit = n % base + val += digit * inv_base_n + n //= base + inv_base_n *= inv_base + return val + +def halton_sequence(dim, n): + return [radical_inverse(PRIMES[dim], n) for dim in range(dim)] + +def hammersley_sequence(dim, n, num_samples): + return [n / num_samples] + halton_sequence(dim - 1, n) + +def sphere_hammersley_sequence(n, num_samples, offset=(0, 0)): + u, v = hammersley_sequence(2, n, num_samples) + u += offset[0] / num_samples + v += offset[1] + u = 2 * u if u < 0.25 else 2 / 3 * u + 1 / 3 + theta = np.arccos(1 - 2 * u) - np.pi / 2 + phi = v * 2 * np.pi + return [phi, theta] diff --git a/OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/voxelize.py b/OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/voxelize.py new file mode 100644 index 0000000000000000000000000000000000000000..390575ab9e26e73b467151dadc8252eae3c96424 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/voxelize.py @@ -0,0 +1,86 @@ +import os +import copy +import sys +import importlib +import argparse +import pandas as pd +from easydict import EasyDict as edict +from functools import partial +import numpy as np +import open3d as o3d +import utils3d + + +def _voxelize(file, sha256, output_dir): + mesh = o3d.io.read_triangle_mesh(os.path.join(output_dir, 'renders', sha256, 'mesh.ply')) + # clamp vertices to the range [-0.5, 0.5] + vertices = np.clip(np.asarray(mesh.vertices), -0.5 + 1e-6, 0.5 - 1e-6) + mesh.vertices = o3d.utility.Vector3dVector(vertices) + voxel_grid = o3d.geometry.VoxelGrid.create_from_triangle_mesh_within_bounds(mesh, voxel_size=1/64, min_bound=(-0.5, -0.5, -0.5), max_bound=(0.5, 0.5, 0.5)) + vertices = np.array([voxel.grid_index for voxel in voxel_grid.get_voxels()]) + assert np.all(vertices >= 0) and np.all(vertices < 64), "Some vertices are out of bounds" + vertices = (vertices + 0.5) / 64 - 0.5 + utils3d.io.write_ply(os.path.join(output_dir, 'voxels', f'{sha256}.ply'), vertices) + return {'sha256': sha256, 'voxelized': True, 'num_voxels': len(vertices)} + + +if __name__ == '__main__': + dataset_utils = importlib.import_module(f'datasets.{sys.argv[1]}') + + parser = argparse.ArgumentParser() + parser.add_argument('--output_dir', type=str, required=True, + help='Directory to save the metadata') + parser.add_argument('--filter_low_aesthetic_score', type=float, default=None, + help='Filter objects with aesthetic score lower than this value') + parser.add_argument('--instances', type=str, default=None, + help='Instances to process') + parser.add_argument('--num_views', type=int, default=150, + help='Number of views to render') + dataset_utils.add_args(parser) + parser.add_argument('--rank', type=int, default=0) + parser.add_argument('--world_size', type=int, default=1) + parser.add_argument('--max_workers', type=int, default=None) + opt = parser.parse_args(sys.argv[2:]) + opt = edict(vars(opt)) + + os.makedirs(os.path.join(opt.output_dir, 'voxels'), exist_ok=True) + + # get file list + if not os.path.exists(os.path.join(opt.output_dir, 'metadata.csv')): + raise ValueError('metadata.csv not found') + metadata = pd.read_csv(os.path.join(opt.output_dir, 'metadata.csv')) + if opt.instances is None: + if opt.filter_low_aesthetic_score is not None: + metadata = metadata[metadata['aesthetic_score'] >= opt.filter_low_aesthetic_score] + if 'rendered' not in metadata.columns: + raise ValueError('metadata.csv does not have "rendered" column, please run "build_metadata.py" first') + metadata = metadata[metadata['rendered'] == True] + if 'voxelized' in metadata.columns: + metadata = metadata[metadata['voxelized'] == False] + else: + if os.path.exists(opt.instances): + with open(opt.instances, 'r') as f: + instances = f.read().splitlines() + else: + instances = opt.instances.split(',') + metadata = metadata[metadata['sha256'].isin(instances)] + + start = len(metadata) * opt.rank // opt.world_size + end = len(metadata) * (opt.rank + 1) // opt.world_size + metadata = metadata[start:end] + records = [] + + # filter out objects that are already processed + for sha256 in copy.copy(metadata['sha256'].values): + if os.path.exists(os.path.join(opt.output_dir, 'voxels', f'{sha256}.ply')): + pts = utils3d.io.read_ply(os.path.join(opt.output_dir, 'voxels', f'{sha256}.ply'))[0] + records.append({'sha256': sha256, 'voxelized': True, 'num_voxels': len(pts)}) + metadata = metadata[metadata['sha256'] != sha256] + + print(f'Processing {len(metadata)} objects...') + + # process objects + func = partial(_voxelize, output_dir=opt.output_dir) + voxelized = dataset_utils.foreach_instance(metadata, opt.output_dir, func, max_workers=opt.max_workers, desc='Voxelizing') + voxelized = pd.concat([voxelized, pd.DataFrame.from_records(records)]) + voxelized.to_csv(os.path.join(opt.output_dir, f'voxelized_{opt.rank}.csv'), index=False) diff --git a/OVOW/engine/oneposeviagen/Amodal3R/dit/diffusion_slat.py b/OVOW/engine/oneposeviagen/Amodal3R/dit/diffusion_slat.py new file mode 100644 index 0000000000000000000000000000000000000000..53903f098d341ccca0f6c9dc93934fa73e440f9e --- /dev/null +++ b/OVOW/engine/oneposeviagen/Amodal3R/dit/diffusion_slat.py @@ -0,0 +1,181 @@ +import torch.nn as nn +import torch +import numpy as np +from amodal3r.modules.sparse import SparseTensor + +def get_betas(schedule_type, b_start, b_end, time_num): + if schedule_type == 'linear': + betas = np.linspace(b_start, b_end, time_num) + elif schedule_type == 'warm0.1': + + betas = b_end * np.ones(time_num, dtype=np.float64) + warmup_time = int(time_num * 0.1) + betas[:warmup_time] = np.linspace(b_start, b_end, warmup_time, dtype=np.float64) + elif schedule_type == 'warm0.2': + + betas = b_end * np.ones(time_num, dtype=np.float64) + warmup_time = int(time_num * 0.2) + betas[:warmup_time] = np.linspace(b_start, b_end, warmup_time, dtype=np.float64) + elif schedule_type == 'warm0.5': + + betas = b_end * np.ones(time_num, dtype=np.float64) + warmup_time = int(time_num * 0.5) + betas[:warmup_time] = np.linspace(b_start, b_end, warmup_time, dtype=np.float64) + else: + raise NotImplementedError(schedule_type) + return betas + + +class GaussianDiffusion: + def __init__(self,betas, loss_type, model_mean_type, model_var_type): + self.loss_type = loss_type + self.model_mean_type = model_mean_type + self.model_var_type = model_var_type + assert isinstance(betas, np.ndarray) + self.np_betas = betas = betas.astype(np.float64) # computations here in float64 for accuracy + assert (betas > 0).all() and (betas <= 1).all() + timesteps, = betas.shape + self.num_timesteps = int(timesteps) + + # initialize twice the actual length so we can keep running for eval + # betas = np.concatenate([betas, np.full_like(betas[:int(0.2*len(betas))], betas[-1])]) + + alphas = 1. - betas + alphas_cumprod = torch.from_numpy(np.cumprod(alphas, axis=0)).float() + alphas_cumprod_prev = torch.from_numpy(np.append(1., alphas_cumprod[:-1])).float() + + self.betas = torch.from_numpy(betas).float() + self.alphas_cumprod = alphas_cumprod.float() + self.alphas_cumprod_prev = alphas_cumprod_prev.float() + + # calculations for diffusion q(x_t | x_{t-1}) and others + self.sqrt_alphas_cumprod = torch.sqrt(alphas_cumprod).float() + self.sqrt_one_minus_alphas_cumprod = torch.sqrt(1. - alphas_cumprod).float() + self.log_one_minus_alphas_cumprod = torch.log(1. - alphas_cumprod).float() + self.sqrt_recip_alphas_cumprod = torch.sqrt(1. / alphas_cumprod).float() + self.sqrt_recipm1_alphas_cumprod = torch.sqrt(1. / alphas_cumprod - 1).float() + + betas = torch.from_numpy(betas).float() + alphas = torch.from_numpy(alphas).float() + # calculations for posterior q(x_{t-1} | x_t, x_0) + posterior_variance = betas * (1. - alphas_cumprod_prev) / (1. - alphas_cumprod) + # above: equal to 1. / (1. / (1. - alpha_cumprod_tm1) + alpha_t / beta_t) + self.posterior_variance = posterior_variance + # below: log calculation clipped because the posterior variance is 0 at the beginning of the diffusion chain + self.posterior_log_variance_clipped = torch.log(torch.max(posterior_variance, 1e-20 * torch.ones_like(posterior_variance))) + self.posterior_mean_coef1 = betas * torch.sqrt(alphas_cumprod_prev) / (1. - alphas_cumprod) + self.posterior_mean_coef2 = (1. - alphas_cumprod_prev) * torch.sqrt(alphas) / (1. - alphas_cumprod) + + self.sigma_min = 1e-5 + + @staticmethod + def _extract(a, t, x_shape): + """ + Extract some coefficients at specified timesteps, + then reshape to [batch_size, 1, 1, 1, 1, ...] for broadcasting purposes. + """ + bs, = t.shape + assert x_shape[0] == bs + out = torch.gather(a, 0, t) + assert out.shape == torch.Size([bs]) + return torch.reshape(out, [bs] + ((len(x_shape) - 1) * [1])) + + def q_mean_variance(self, x_start, t): + mean = self._extract(self.sqrt_alphas_cumprod.to(x_start.device), t, x_start.shape) * x_start + variance = self._extract(1. - self.alphas_cumprod.to(x_start.device), t, x_start.shape) + log_variance = self._extract(self.log_one_minus_alphas_cumprod.to(x_start.device), t, x_start.shape) + return mean, variance, log_variance + + def q_sample(self, x_start, t, noise=None): + """ + Diffuse the data (t == 0 means diffused for 1 step) + """ + if noise is None: + noise = torch.randn(x_start.shape, device=x_start.device) + assert noise.shape == x_start.shape + return ( + self._extract(self.sqrt_alphas_cumprod.to(x_start.device), t, x_start.shape) * x_start + + self._extract(self.sqrt_one_minus_alphas_cumprod.to(x_start.device), t, x_start.shape) * noise + ) + + def q_sample_linear(self, x_start, t, noise=None): + """ + x_t = (1 - t) * x0 + t * noise + """ + if noise is None: + noise = torch.randn_like(x_start) + t_shape = [x_start.shape[0]] + [1] * (len(x_start.shape) - 1) + t = t.view(*t_shape) + return (1 - t) * x_start + t * noise + + def _predict_xstart_from_eps(self, x_t, t, eps): + assert x_t.shape == eps.shape + return ( + self._extract(self.sqrt_recip_alphas_cumprod.to(x_t.device), t, x_t.shape) * x_t - + self._extract(self.sqrt_recipm1_alphas_cumprod.to(x_t.device), t, x_t.shape) * eps + ) + + + + '''losses''' + + def p_losses(self, denoise_fn, data_start, t, noise=None, y=None, multi_t=False): + """ + Training loss calculation + """ + # print(data_start.shape) + if multi_t: + B = len(data_start['feats']) + assert t.shape == torch.Size([B]) + + noise, data_feats_t = [], [] + for idx, feat in enumerate(data_start['feats']): + noise_single = torch.randn(feat.shape, dtype=feat.dtype, device=feat.device) + noise.append(noise_single) + assert noise_single.shape == feat.shape and noise_single.dtype == feat.dtype + data_feat_t = self.q_sample_linear(x_start=feat.unsqueeze(0), t=t[idx:idx+1], noise=noise_single.unsqueeze(0)) + data_feats_t.append(data_feat_t.squeeze(0)) + data_feats_t = torch.cat(data_feats_t, dim=0) + data_coords_t = torch.cat(data_start['coords'], dim=0) + + data_t = SparseTensor( + feats=data_feats_t.half().contiguous(), + coords=data_coords_t.contiguous() + ) + + # predict the noise instead of x_start. seems to be weighted naturally like SNR + eps_recon = denoise_fn(data_t, t, y).feats + target = torch.cat(noise, dim=0) - torch.cat(data_start['feats'], dim=0) + losses = ((eps_recon - target)**2).mean() + + # assert losses.shape == torch.Size([B]) + return losses, {'data_t': data_t, 'eps_recon': eps_recon} + else: + B = 1 + assert t.shape == torch.Size([B]) + + if noise is None: + for idx, feat in enumerate(data_start['feats']): + noise_single = torch.randn(feat.shape, dtype=feat.dtype, device=feat.device) + noises.append(noise_single) + noise = torch.cat(noises, dim=0) + + data_start_sp = SparseTensor( + feats=torch.cat(data_start['feats'], dim=0).contiguous(), + coords=torch.cat(data_start['coords'], dim=0).contiguous() + ) + + assert noise.shape == data_start_sp.feats.shape and noise.dtype == data_start_sp.feats.dtype + + data_t_feats = self.q_sample_linear(x_start=data_start_sp.feats.unsqueeze(0), t=t, noise=noise.unsqueeze(0)) + data_t = SparseTensor( + feats=data_t_feats.squeeze(0).contiguous(), + coords=data_start_sp.coords.contiguous() + ) + + eps_recon = denoise_fn(data_t, t, y).feats + target = noise - torch.cat(data_start['feats'], dim=0) + losses = ((eps_recon - target)**2).mean() + + # assert losses.shape == torch.Size([B]) + return losses, {'data_t': data_t, 'eps_recon': eps_recon} \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/Amodal3R/dit/diffusion_ss.py b/OVOW/engine/oneposeviagen/Amodal3R/dit/diffusion_ss.py new file mode 100644 index 0000000000000000000000000000000000000000..fc90fa7d89117bbbec00355b8c7aa9756c605935 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Amodal3R/dit/diffusion_ss.py @@ -0,0 +1,135 @@ +import torch +import numpy as np + +def get_betas(schedule_type, b_start, b_end, time_num): + if schedule_type == 'linear': + betas = np.linspace(b_start, b_end, time_num) + elif schedule_type == 'warm0.1': + + betas = b_end * np.ones(time_num, dtype=np.float64) + warmup_time = int(time_num * 0.1) + betas[:warmup_time] = np.linspace(b_start, b_end, warmup_time, dtype=np.float64) + elif schedule_type == 'warm0.2': + + betas = b_end * np.ones(time_num, dtype=np.float64) + warmup_time = int(time_num * 0.2) + betas[:warmup_time] = np.linspace(b_start, b_end, warmup_time, dtype=np.float64) + elif schedule_type == 'warm0.5': + + betas = b_end * np.ones(time_num, dtype=np.float64) + warmup_time = int(time_num * 0.5) + betas[:warmup_time] = np.linspace(b_start, b_end, warmup_time, dtype=np.float64) + else: + raise NotImplementedError(schedule_type) + return betas + + +class GaussianDiffusion: + def __init__(self,betas, loss_type, model_mean_type, model_var_type): + self.loss_type = loss_type + self.model_mean_type = model_mean_type + self.model_var_type = model_var_type + assert isinstance(betas, np.ndarray) + self.np_betas = betas = betas.astype(np.float64) # computations here in float64 for accuracy + assert (betas > 0).all() and (betas <= 1).all() + timesteps, = betas.shape + self.num_timesteps = int(timesteps) + + # initialize twice the actual length so we can keep running for eval + # betas = np.concatenate([betas, np.full_like(betas[:int(0.2*len(betas))], betas[-1])]) + + alphas = 1. - betas + alphas_cumprod = torch.from_numpy(np.cumprod(alphas, axis=0)).float() + alphas_cumprod_prev = torch.from_numpy(np.append(1., alphas_cumprod[:-1])).float() + + self.betas = torch.from_numpy(betas).float() + self.alphas_cumprod = alphas_cumprod.float() + self.alphas_cumprod_prev = alphas_cumprod_prev.float() + + # calculations for diffusion q(x_t | x_{t-1}) and others + self.sqrt_alphas_cumprod = torch.sqrt(alphas_cumprod).float() + self.sqrt_one_minus_alphas_cumprod = torch.sqrt(1. - alphas_cumprod).float() + self.log_one_minus_alphas_cumprod = torch.log(1. - alphas_cumprod).float() + self.sqrt_recip_alphas_cumprod = torch.sqrt(1. / alphas_cumprod).float() + self.sqrt_recipm1_alphas_cumprod = torch.sqrt(1. / alphas_cumprod - 1).float() + + betas = torch.from_numpy(betas).float() + alphas = torch.from_numpy(alphas).float() + # calculations for posterior q(x_{t-1} | x_t, x_0) + posterior_variance = betas * (1. - alphas_cumprod_prev) / (1. - alphas_cumprod) + # above: equal to 1. / (1. / (1. - alpha_cumprod_tm1) + alpha_t / beta_t) + self.posterior_variance = posterior_variance + # below: log calculation clipped because the posterior variance is 0 at the beginning of the diffusion chain + self.posterior_log_variance_clipped = torch.log(torch.max(posterior_variance, 1e-20 * torch.ones_like(posterior_variance))) + self.posterior_mean_coef1 = betas * torch.sqrt(alphas_cumprod_prev) / (1. - alphas_cumprod) + self.posterior_mean_coef2 = (1. - alphas_cumprod_prev) * torch.sqrt(alphas) / (1. - alphas_cumprod) + + @staticmethod + def _extract(a, t, x_shape): + """ + Extract some coefficients at specified timesteps, + then reshape to [batch_size, 1, 1, 1, 1, ...] for broadcasting purposes. + """ + bs, = t.shape + assert x_shape[0] == bs + out = torch.gather(a, 0, t) + assert out.shape == torch.Size([bs]) + return torch.reshape(out, [bs] + ((len(x_shape) - 1) * [1])) + + + def q_mean_variance(self, x_start, t): + mean = self._extract(self.sqrt_alphas_cumprod.to(x_start.device), t, x_start.shape) * x_start + variance = self._extract(1. - self.alphas_cumprod.to(x_start.device), t, x_start.shape) + log_variance = self._extract(self.log_one_minus_alphas_cumprod.to(x_start.device), t, x_start.shape) + return mean, variance, log_variance + + def q_sample(self, x_start, t, noise=None): + """ + Diffuse the data (t == 0 means diffused for 1 step) + """ + if noise is None: + noise = torch.randn(x_start.shape, device=x_start.device) + assert noise.shape == x_start.shape + return ( + self._extract(self.sqrt_alphas_cumprod.to(x_start.device), t, x_start.shape) * x_start + + self._extract(self.sqrt_one_minus_alphas_cumprod.to(x_start.device), t, x_start.shape) * noise + ) + + def q_sample_linear(self, x_start, t, noise=None): + """ + Linearly interpolate x_t = (1 - t) * x_0 + t * ϵ + """ + if noise is None: + noise = torch.randn(x_start.shape, device=x_start.device) + assert noise.shape == x_start.shape + + t = t.view(-1, *([1] * (len(x_start.shape) - 1))) # (B, 1, 1, ...) + + x_t = (1 - t) * x_start + t * noise + return x_t + + + '''losses''' + + def p_losses(self, denoise_fn, data_start, t, noise=None, y=None): + """ + Training loss calculation + """ + B = data_start.shape[0] + assert t.shape == torch.Size([B]) + + if noise is None: + noise = torch.randn(data_start.shape, dtype=data_start.dtype, device=data_start.device) + assert noise.shape == data_start.shape and noise.dtype == data_start.dtype + + data_t = self.q_sample_linear(x_start=data_start, t=t, noise=noise) + + eps_recon = denoise_fn(data_t, t, y) + assert data_t.shape == data_start.shape + # assert eps_recon.shape == torch.Size([B, N, 3]) + assert eps_recon.shape == data_start.shape + target = noise - data_start + losses = ((eps_recon - target)**2).mean(dim=list(range(1, len(data_start.shape)))) + + assert losses.shape == torch.Size([B]) + return losses, {'data_t': data_t, 'eps_recon': eps_recon} \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/Amodal3R/dit/utils.py b/OVOW/engine/oneposeviagen/Amodal3R/dit/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..7e7418c22e4a315216c5185f189d039a33923b3f --- /dev/null +++ b/OVOW/engine/oneposeviagen/Amodal3R/dit/utils.py @@ -0,0 +1,881 @@ +# https://raw.githubusercontent.com/facebookresearch/dino/main/utils.py +# Copyright (c) Facebook, Inc. and its affiliates. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +Misc functions. + +Mostly copy-paste from torchvision references or other public repos like DETR: +https://github.com/facebookresearch/detr/blob/master/util/misc.py +""" +import os +import sys +import time +import math +import random +import datetime +import subprocess +from collections import defaultdict, deque + +import numpy as np +import torch +from torch import nn +import torch.distributed as dist +from PIL import ImageFilter, ImageOps + + +class GaussianBlur(object): + """ + Apply Gaussian Blur to the PIL image. + """ + def __init__(self, p=0.5, radius_min=0.1, radius_max=2.): + self.prob = p + self.radius_min = radius_min + self.radius_max = radius_max + + def __call__(self, img): + do_it = random.random() <= self.prob + if not do_it: + return img + + return img.filter( + ImageFilter.GaussianBlur( + radius=random.uniform(self.radius_min, self.radius_max))) + + +class Solarization(object): + """ + Apply Solarization to the PIL image. + """ + def __init__(self, p): + self.p = p + + def __call__(self, img): + if random.random() < self.p: + return ImageOps.solarize(img) + else: + return img + + +def load_pretrained_weights(model, pretrained_weights, checkpoint_key, + model_name, patch_size): + if os.path.isfile(pretrained_weights): + state_dict = torch.load(pretrained_weights, map_location="cpu") + if checkpoint_key is not None and checkpoint_key in state_dict: + print(f"Take key {checkpoint_key} in provided checkpoint dict") + state_dict = state_dict[checkpoint_key] + # remove `module.` prefix + state_dict = { + k.replace("module.", ""): v + for k, v in state_dict.items() + } + # remove `backbone.` prefix induced by multicrop wrapper + state_dict = { + k.replace("backbone.", ""): v + for k, v in state_dict.items() + } + msg = model.load_state_dict(state_dict, strict=False) + print('Pretrained weights found at {} and loaded with msg: {}'.format( + pretrained_weights, msg)) + else: + print( + "Please use the `--pretrained_weights` argument to indicate the path of the checkpoint to evaluate." + ) + url = None + if model_name == "vit_small" and patch_size == 16: + url = "dino_deitsmall16_pretrain/dino_deitsmall16_pretrain.pth" + elif model_name == "vit_small" and patch_size == 8: + url = "dino_deitsmall8_pretrain/dino_deitsmall8_pretrain.pth" + elif model_name == "vit_base" and patch_size == 16: + url = "dino_vitbase16_pretrain/dino_vitbase16_pretrain.pth" + elif model_name == "vit_base" and patch_size == 8: + url = "dino_vitbase8_pretrain/dino_vitbase8_pretrain.pth" + elif model_name == "xcit_small_12_p16": + url = "dino_xcit_small_12_p16_pretrain/dino_xcit_small_12_p16_pretrain.pth" + elif model_name == "xcit_small_12_p8": + url = "dino_xcit_small_12_p8_pretrain/dino_xcit_small_12_p8_pretrain.pth" + elif model_name == "xcit_medium_24_p16": + url = "dino_xcit_medium_24_p16_pretrain/dino_xcit_medium_24_p16_pretrain.pth" + elif model_name == "xcit_medium_24_p8": + url = "dino_xcit_medium_24_p8_pretrain/dino_xcit_medium_24_p8_pretrain.pth" + elif model_name == "resnet50": + url = "dino_resnet50_pretrain/dino_resnet50_pretrain.pth" + if url is not None: + print( + "Since no pretrained weights have been provided, we load the reference pretrained DINO weights." + ) + state_dict = torch.hub.load_state_dict_from_url( + url="https://dl.fbaipublicfiles.com/dino/" + url) + model.load_state_dict(state_dict, strict=True) + else: + print( + "There is no reference weights available for this model => We use random weights." + ) + + +def load_pretrained_linear_weights(linear_classifier, model_name, patch_size): + url = None + if model_name == "vit_small" and patch_size == 16: + url = "dino_deitsmall16_pretrain/dino_deitsmall16_linearweights.pth" + elif model_name == "vit_small" and patch_size == 8: + url = "dino_deitsmall8_pretrain/dino_deitsmall8_linearweights.pth" + elif model_name == "vit_base" and patch_size == 16: + url = "dino_vitbase16_pretrain/dino_vitbase16_linearweights.pth" + elif model_name == "vit_base" and patch_size == 8: + url = "dino_vitbase8_pretrain/dino_vitbase8_linearweights.pth" + elif model_name == "resnet50": + url = "dino_resnet50_pretrain/dino_resnet50_linearweights.pth" + if url is not None: + print("We load the reference pretrained linear weights.") + state_dict = torch.hub.load_state_dict_from_url( + url="https://dl.fbaipublicfiles.com/dino/" + url)["state_dict"] + linear_classifier.load_state_dict(state_dict, strict=True) + else: + print("We use random linear weights.") + + +def clip_gradients(model, clip): + norms = [] + for name, p in model.named_parameters(): + if p.grad is not None: + param_norm = p.grad.data.norm(2) + norms.append(param_norm.item()) + clip_coef = clip / (param_norm + 1e-6) + if clip_coef < 1: + p.grad.data.mul_(clip_coef) + return norms + + +def cancel_gradients_last_layer(epoch, model, freeze_last_layer): + if epoch >= freeze_last_layer: + return + for n, p in model.named_parameters(): + if "last_layer" in n: + p.grad = None + + +def restart_from_checkpoint(ckp_path, run_variables=None, **kwargs): + """ + Re-start from checkpoint + """ + if not os.path.isfile(ckp_path): + return + print("Found checkpoint at {}".format(ckp_path)) + + # open checkpoint file + checkpoint = torch.load(ckp_path, map_location="cpu") + + # key is what to look for in the checkpoint file + # value is the object to load + # example: {'state_dict': model} + for key, value in kwargs.items(): + if key in checkpoint and value is not None: + try: + msg = value.load_state_dict(checkpoint[key], strict=False) + print("=> loaded '{}' from checkpoint '{}' with msg {}".format( + key, ckp_path, msg)) + except TypeError: + try: + msg = value.load_state_dict(checkpoint[key]) + print("=> loaded '{}' from checkpoint: '{}'".format( + key, ckp_path)) + except ValueError: + print( + "=> failed to load '{}' from checkpoint: '{}'".format( + key, ckp_path)) + else: + print("=> key '{}' not found in checkpoint: '{}'".format( + key, ckp_path)) + + # re load variable important for the run + if run_variables is not None: + for var_name in run_variables: + if var_name in checkpoint: + run_variables[var_name] = checkpoint[var_name] + + +def cosine_scheduler(base_value, + final_value, + epochs, + niter_per_ep, + warmup_epochs=0, + start_warmup_value=0): + warmup_schedule = np.array([]) + warmup_iters = warmup_epochs * niter_per_ep + if warmup_epochs > 0: + warmup_schedule = np.linspace(start_warmup_value, base_value, + warmup_iters) + + iters = np.arange(epochs * niter_per_ep - warmup_iters) + schedule = final_value + 0.5 * (base_value - final_value) * ( + 1 + np.cos(np.pi * iters / len(iters))) + + schedule = np.concatenate((warmup_schedule, schedule)) + assert len(schedule) == epochs * niter_per_ep + return schedule + + +def bool_flag(s): + """ + Parse boolean arguments from the command line. + """ + FALSY_STRINGS = {"off", "false", "0"} + TRUTHY_STRINGS = {"on", "true", "1"} + if s.lower() in FALSY_STRINGS: + return False + elif s.lower() in TRUTHY_STRINGS: + return True + else: + raise argparse.ArgumentTypeError("invalid value for a boolean flag") + + +def fix_random_seeds(seed=31): + """ + Fix random seeds. + """ + torch.manual_seed(seed) + torch.cuda.manual_seed_all(seed) + np.random.seed(seed) + + +class SmoothedValue(object): + """Track a series of values and provide access to smoothed values over a + window or the global series average. + """ + def __init__(self, window_size=20, fmt=None): + if fmt is None: + fmt = "{median:.6f} ({global_avg:.6f})" + self.deque = deque(maxlen=window_size) + self.total = 0.0 + self.count = 0 + self.fmt = fmt + + def update(self, value, n=1): + self.deque.append(value) + self.count += n + self.total += value * n + + def synchronize_between_processes(self): + """ + Warning: does not synchronize the deque! + """ + if not is_dist_avail_and_initialized(): + return + t = torch.tensor([self.count, self.total], + dtype=torch.float64, + device='cuda') + dist.barrier() + dist.all_reduce(t) + t = t.tolist() + self.count = int(t[0]) + self.total = t[1] + + @property + def median(self): + d = torch.tensor(list(self.deque)) + return d.median().item() + + @property + def avg(self): + d = torch.tensor(list(self.deque), dtype=torch.float32) + return d.mean().item() + + @property + def global_avg(self): + return self.total / self.count + + @property + def max(self): + return max(self.deque) + + @property + def value(self): + return self.deque[-1] + + def __str__(self): + return self.fmt.format(median=self.median, + avg=self.avg, + global_avg=self.global_avg, + max=self.max, + value=self.value) + + +def reduce_dict(input_dict, average=True): + """ + Args: + input_dict (dict): all the values will be reduced + average (bool): whether to do average or sum + Reduce the values in the dictionary from all processes so that all processes + have the averaged results. Returns a dict with the same fields as + input_dict, after reduction. + """ + world_size = get_world_size() + if world_size < 2: + return input_dict + with torch.no_grad(): + names = [] + values = [] + # sort the keys so that they are consistent across processes + for k in sorted(input_dict.keys()): + names.append(k) + values.append(input_dict[k]) + values = torch.stack(values, dim=0) + dist.all_reduce(values) + if average: + values /= world_size + reduced_dict = {k: v for k, v in zip(names, values)} + return reduced_dict + + +class MetricLogger(object): + def __init__(self, delimiter="\t"): + self.meters = defaultdict(SmoothedValue) + self.delimiter = delimiter + + def update(self, **kwargs): + for k, v in kwargs.items(): + if isinstance(v, torch.Tensor): + v = v.item() + assert isinstance(v, (float, int)) + self.meters[k].update(v) + + def __getattr__(self, attr): + if attr in self.meters: + return self.meters[attr] + if attr in self.__dict__: + return self.__dict__[attr] + raise AttributeError("'{}' object has no attribute '{}'".format( + type(self).__name__, attr)) + + def __str__(self): + loss_str = [] + for name, meter in self.meters.items(): + loss_str.append("{}: {}".format(name, str(meter))) + return self.delimiter.join(loss_str) + + def synchronize_between_processes(self): + for meter in self.meters.values(): + meter.synchronize_between_processes() + + def add_meter(self, name, meter): + self.meters[name] = meter + + def log_every(self, iterable, print_freq, header=None): + i = 0 + if not header: + header = '' + start_time = time.time() + end = time.time() + iter_time = SmoothedValue(fmt='{avg:.6f}') + data_time = SmoothedValue(fmt='{avg:.6f}') + space_fmt = ':' + str(len(str(len(iterable)))) + 'd' + if torch.cuda.is_available(): + log_msg = self.delimiter.join([ + header, '[{0' + space_fmt + '}/{1}]', 'eta: {eta}', '{meters}', + 'time: {time}', 'data: {data}', 'max mem: {memory:.0f}' + ]) + else: + log_msg = self.delimiter.join([ + header, '[{0' + space_fmt + '}/{1}]', 'eta: {eta}', '{meters}', + 'time: {time}', 'data: {data}' + ]) + MB = 1024.0 * 1024.0 + for obj in iterable: + data_time.update(time.time() - end) + yield obj + iter_time.update(time.time() - end) + if i % print_freq == 0 or i == len(iterable) - 1: + eta_seconds = iter_time.global_avg * (len(iterable) - i) + eta_string = str(datetime.timedelta(seconds=int(eta_seconds))) + if torch.cuda.is_available(): + print( + log_msg.format( + i, + len(iterable), + eta=eta_string, + meters=str(self), + time=str(iter_time), + data=str(data_time), + memory=torch.cuda.max_memory_allocated() / MB)) + else: + print( + log_msg.format(i, + len(iterable), + eta=eta_string, + meters=str(self), + time=str(iter_time), + data=str(data_time))) + i += 1 + end = time.time() + total_time = time.time() - start_time + total_time_str = str(datetime.timedelta(seconds=int(total_time))) + print('{} Total time: {} ({:.6f} s / it)'.format( + header, total_time_str, total_time / len(iterable))) + + +def get_sha(): + cwd = os.path.dirname(os.path.abspath(__file__)) + + def _run(command): + return subprocess.check_output(command, + cwd=cwd).decode('ascii').strip() + + sha = 'N/A' + diff = "clean" + branch = 'N/A' + try: + sha = _run(['git', 'rev-parse', 'HEAD']) + subprocess.check_output(['git', 'diff'], cwd=cwd) + diff = _run(['git', 'diff-index', 'HEAD']) + diff = "has uncommited changes" if diff else "clean" + branch = _run(['git', 'rev-parse', '--abbrev-ref', 'HEAD']) + except Exception: + pass + message = f"sha: {sha}, status: {diff}, branch: {branch}" + return message + + +def is_dist_avail_and_initialized(): + if not dist.is_available(): + return False + if not dist.is_initialized(): + return False + return True + + +def get_world_size(): + if not is_dist_avail_and_initialized(): + return 1 + return dist.get_world_size() + + +def get_rank(): + if not is_dist_avail_and_initialized(): + return 0 + return dist.get_rank() + + +def is_main_process(): + return get_rank() == 0 + + +def save_on_master(*args, **kwargs): + if is_main_process(): + torch.save(*args, **kwargs) + + +def setup_for_distributed(is_master): + """ + This function disables printing when not in master process + """ + import builtins as __builtin__ + builtin_print = __builtin__.print + + def print(*args, **kwargs): + force = kwargs.pop('force', False) + if is_master or force: + builtin_print(*args, **kwargs) + + __builtin__.print = print + + +def init_distributed_mode(args): + # launched with torch.distributed.launch + if 'RANK' in os.environ and 'WORLD_SIZE' in os.environ: + args.rank = int(os.environ["RANK"]) + args.world_size = int(os.environ['WORLD_SIZE']) + args.gpu = int(os.environ['LOCAL_RANK']) + # launched with submitit on a slurm cluster + elif 'SLURM_PROCID' in os.environ: + args.rank = int(os.environ['SLURM_PROCID']) + args.gpu = args.rank % torch.cuda.device_count() + # launched naively with `python main_dino.py` + # we manually add MASTER_ADDR and MASTER_PORT to env variables + elif torch.cuda.is_available(): + print('Will run the code on one GPU.') + args.rank, args.gpu, args.world_size = 0, 0, 1 + os.environ['MASTER_ADDR'] = '127.0.0.1' + os.environ['MASTER_PORT'] = '29500' + else: + print('Does not support training without GPU.') + sys.exit(1) + + dist.init_process_group( + backend="nccl", + init_method=args.dist_url, + world_size=args.world_size, + rank=args.rank, + ) + + torch.cuda.set_device(args.gpu) + print('| distributed init (rank {}): {}'.format(args.rank, args.dist_url), + flush=True) + dist.barrier() + setup_for_distributed(args.rank == 0) + + +def accuracy(output, target, topk=(1, )): + """Computes the accuracy over the k top predictions for the specified values of k""" + maxk = max(topk) + batch_size = target.size(0) + _, pred = output.topk(maxk, 1, True, True) + pred = pred.t() + correct = pred.eq(target.reshape(1, -1).expand_as(pred)) + return [ + correct[:k].reshape(-1).float().sum(0) * 100. / batch_size + for k in topk + ] + + +def _no_grad_trunc_normal_(tensor, mean, std, a, b): + # Cut & paste from PyTorch official master until it's in a few official releases - RW + # Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf + def norm_cdf(x): + # Computes standard normal cumulative distribution function + return (1. + math.erf(x / math.sqrt(2.))) / 2. + + if (mean < a - 2 * std) or (mean > b + 2 * std): + warnings.warn( + "mean is more than 2 std from [a, b] in nn.init.trunc_normal_. " + "The distribution of values may be incorrect.", + stacklevel=2) + + with torch.no_grad(): + # Values are generated by using a truncated uniform distribution and + # then using the inverse CDF for the normal distribution. + # Get upper and lower cdf values + l = norm_cdf((a - mean) / std) + u = norm_cdf((b - mean) / std) + + # Uniformly fill tensor with values from [l, u], then translate to + # [2l-1, 2u-1]. + tensor.uniform_(2 * l - 1, 2 * u - 1) + + # Use inverse cdf transform for normal distribution to get truncated + # standard normal + tensor.erfinv_() + + # Transform to proper mean, std + tensor.mul_(std * math.sqrt(2.)) + tensor.add_(mean) + + # Clamp to ensure it's in the proper range + tensor.clamp_(min=a, max=b) + return tensor + + +def trunc_normal_(tensor, mean=0., std=1., a=-2., b=2.): + # type: (Tensor, float, float, float, float) -> Tensor + return _no_grad_trunc_normal_(tensor, mean, std, a, b) + + +class LARS(torch.optim.Optimizer): + """ + Almost copy-paste from https://github.com/facebookresearch/barlowtwins/blob/main/main.py + """ + def __init__(self, + params, + lr=0, + weight_decay=0, + momentum=0.9, + eta=0.001, + weight_decay_filter=None, + lars_adaptation_filter=None): + defaults = dict(lr=lr, + weight_decay=weight_decay, + momentum=momentum, + eta=eta, + weight_decay_filter=weight_decay_filter, + lars_adaptation_filter=lars_adaptation_filter) + super().__init__(params, defaults) + + @torch.no_grad() + def step(self): + for g in self.param_groups: + for p in g['params']: + dp = p.grad + + if dp is None: + continue + + if p.ndim != 1: + dp = dp.add(p, alpha=g['weight_decay']) + + if p.ndim != 1: + param_norm = torch.norm(p) + update_norm = torch.norm(dp) + one = torch.ones_like(param_norm) + q = torch.where( + param_norm > 0., + torch.where(update_norm > 0, + (g['eta'] * param_norm / update_norm), + one), one) + dp = dp.mul(q) + + param_state = self.state[p] + if 'mu' not in param_state: + param_state['mu'] = torch.zeros_like(p) + mu = param_state['mu'] + mu.mul_(g['momentum']).add_(dp) + + p.add_(mu, alpha=-g['lr']) + + +class MultiCropWrapper(nn.Module): + """ + Perform forward pass separately on each resolution input. + The inputs corresponding to a single resolution are clubbed and single + forward is run on the same resolution inputs. Hence we do several + forward passes = number of different resolutions used. We then + concatenate all the output features and run the head forward on these + concatenated features. + """ + def __init__(self, backbone, head): + super(MultiCropWrapper, self).__init__() + # disable layers dedicated to ImageNet labels classification + backbone.fc, backbone.head = nn.Identity(), nn.Identity() + self.backbone = backbone + self.head = head + + def forward(self, x): + # convert to list + if not isinstance(x, list): + x = [x] + idx_crops = torch.cumsum( + torch.unique_consecutive( + torch.tensor([inp.shape[-1] for inp in x]), + return_counts=True, + )[1], 0) + start_idx, output = 0, torch.empty(0).to(x[0].device) + for end_idx in idx_crops: + _out = self.backbone(torch.cat(x[start_idx:end_idx])) + # The output is a tuple with XCiT model. See: + # https://github.com/facebookresearch/xcit/blob/master/xcit.py#L404-L405 + if isinstance(_out, tuple): + _out = _out[0] + # accumulate outputs + output = torch.cat((output, _out)) + start_idx = end_idx + # Run the head forward on the concatenated features. + return self.head(output) + + +def get_params_groups(model): + regularized = [] + not_regularized = [] + for name, param in model.named_parameters(): + if not param.requires_grad: + continue + # we do not regularize biases nor Norm parameters + if name.endswith(".bias") or len(param.shape) == 1: + not_regularized.append(param) + else: + regularized.append(param) + return [{ + 'params': regularized + }, { + 'params': not_regularized, + 'weight_decay': 0. + }] + + +def has_batchnorms(model): + bn_types = (nn.BatchNorm1d, nn.BatchNorm2d, nn.BatchNorm3d, + nn.SyncBatchNorm) + for name, module in model.named_modules(): + if isinstance(module, bn_types): + return True + return False + + +class PCA(): + """ + Class to compute and apply PCA. + """ + def __init__(self, dim=256, whit=0.5): + self.dim = dim + self.whit = whit + self.mean = None + + def train_pca(self, cov): + """ + Takes a covariance matrix (np.ndarray) as input. + """ + d, v = np.linalg.eigh(cov) + eps = d.max() * 1e-5 + n_0 = (d < eps).sum() + if n_0 > 0: + d[d < eps] = eps + + # total energy + totenergy = d.sum() + + # sort eigenvectors with eigenvalues order + idx = np.argsort(d)[::-1][:self.dim] + d = d[idx] + v = v[:, idx] + + print("keeping %.2f %% of the energy" % (d.sum() / totenergy * 100.0)) + + # for the whitening + d = np.diag(1. / d**self.whit) + + # principal components + self.dvt = np.dot(d, v.T) + + def apply(self, x): + # input is from numpy + if isinstance(x, np.ndarray): + if self.mean is not None: + x -= self.mean + return np.dot(self.dvt, x.T).T + + # input is from torch and is on GPU + if x.is_cuda: + if self.mean is not None: + x -= torch.cuda.FloatTensor(self.mean) + return torch.mm(torch.cuda.FloatTensor(self.dvt), + x.transpose(0, 1)).transpose(0, 1) + + # input if from torch, on CPU + if self.mean is not None: + x -= torch.FloatTensor(self.mean) + return torch.mm(torch.FloatTensor(self.dvt), + x.transpose(0, 1)).transpose(0, 1) + + +def compute_ap(ranks, nres): + """ + Computes average precision for given ranked indexes. + Arguments + --------- + ranks : zerro-based ranks of positive images + nres : number of positive images + Returns + ------- + ap : average precision + """ + + # number of images ranked by the system + nimgranks = len(ranks) + + # accumulate trapezoids in PR-plot + ap = 0 + + recall_step = 1. / nres + + for j in np.arange(nimgranks): + rank = ranks[j] + + if rank == 0: + precision_0 = 1. + else: + precision_0 = float(j) / rank + + precision_1 = float(j + 1) / (rank + 1) + + ap += (precision_0 + precision_1) * recall_step / 2. + + return ap + + +def compute_map(ranks, gnd, kappas=[]): + """ + Computes the mAP for a given set of returned results. + Usage: + map = compute_map (ranks, gnd) + computes mean average precsion (map) only + map, aps, pr, prs = compute_map (ranks, gnd, kappas) + computes mean average precision (map), average precision (aps) for each query + computes mean precision at kappas (pr), precision at kappas (prs) for each query + Notes: + 1) ranks starts from 0, ranks.shape = db_size X #queries + 2) The junk results (e.g., the query itself) should be declared in the gnd stuct array + 3) If there are no positive images for some query, that query is excluded from the evaluation + """ + + map = 0. + nq = len(gnd) # number of queries + aps = np.zeros(nq) + pr = np.zeros(len(kappas)) + prs = np.zeros((nq, len(kappas))) + nempty = 0 + + for i in np.arange(nq): + qgnd = np.array(gnd[i]['ok']) + + # no positive images, skip from the average + if qgnd.shape[0] == 0: + aps[i] = float('nan') + prs[i, :] = float('nan') + nempty += 1 + continue + + try: + qgndj = np.array(gnd[i]['junk']) + except: + qgndj = np.empty(0) + + # sorted positions of positive and junk images (0 based) + pos = np.arange(ranks.shape[0])[np.in1d(ranks[:, i], qgnd)] + junk = np.arange(ranks.shape[0])[np.in1d(ranks[:, i], qgndj)] + + k = 0 + ij = 0 + if len(junk): + # decrease positions of positives based on the number of + # junk images appearing before them + ip = 0 + while (ip < len(pos)): + while (ij < len(junk) and pos[ip] > junk[ij]): + k += 1 + ij += 1 + pos[ip] = pos[ip] - k + ip += 1 + + # compute ap + ap = compute_ap(pos, len(qgnd)) + map = map + ap + aps[i] = ap + + # compute precision @ k + pos += 1 # get it to 1-based + for j in np.arange(len(kappas)): + kq = min(max(pos), kappas[j]) + prs[i, j] = (pos <= kq).sum() / kq + pr = pr + prs[i, :] + + map = map / (nq - nempty) + pr = pr / (nq - nempty) + + return map, aps, pr, prs + + +def multi_scale(samples, model): + v = None + for s in [1, 1 / 2**(1 / 2), 1 / 2]: # we use 3 different scales + if s == 1: + inp = samples.clone() + else: + inp = nn.functional.interpolate(samples, + scale_factor=s, + mode='bilinear', + align_corners=False) + feats = model(inp).clone() + if v is None: + v = feats + else: + v += feats + v /= 3 + v /= v.norm() + return v \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/benchmark.py b/OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/benchmark.py new file mode 100644 index 0000000000000000000000000000000000000000..30351e0251cfed4db82d286af1b53654f8cdce8b --- /dev/null +++ b/OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/benchmark.py @@ -0,0 +1,45 @@ +import time +import torch +import vox2seq + + +if __name__ == "__main__": + stats = { + 'z_order_cuda': [], + 'z_order_pytorch': [], + 'hilbert_cuda': [], + 'hilbert_pytorch': [], + } + RES = [16, 32, 64, 128, 256] + for res in RES: + coords = torch.meshgrid(torch.arange(res), torch.arange(res), torch.arange(res)) + coords = torch.stack(coords, dim=-1).reshape(-1, 3).int().cuda() + + start = time.time() + for _ in range(100): + code_z_cuda = vox2seq.encode(coords, mode='z_order').cuda() + torch.cuda.synchronize() + stats['z_order_cuda'].append((time.time() - start) / 100) + + start = time.time() + for _ in range(100): + code_z_pytorch = vox2seq.pytorch.encode(coords, mode='z_order').cuda() + torch.cuda.synchronize() + stats['z_order_pytorch'].append((time.time() - start) / 100) + + start = time.time() + for _ in range(100): + code_h_cuda = vox2seq.encode(coords, mode='hilbert').cuda() + torch.cuda.synchronize() + stats['hilbert_cuda'].append((time.time() - start) / 100) + + start = time.time() + for _ in range(100): + code_h_pytorch = vox2seq.pytorch.encode(coords, mode='hilbert').cuda() + torch.cuda.synchronize() + stats['hilbert_pytorch'].append((time.time() - start) / 100) + + print(f"{'Resolution':<12}{'Z-Order (CUDA)':<24}{'Z-Order (PyTorch)':<24}{'Hilbert (CUDA)':<24}{'Hilbert (PyTorch)':<24}") + for res, z_order_cuda, z_order_pytorch, hilbert_cuda, hilbert_pytorch in zip(RES, stats['z_order_cuda'], stats['z_order_pytorch'], stats['hilbert_cuda'], stats['hilbert_pytorch']): + print(f"{res:<12}{z_order_cuda:<24.6f}{z_order_pytorch:<24.6f}{hilbert_cuda:<24.6f}{hilbert_pytorch:<24.6f}") + diff --git a/OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/setup.py b/OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..500d97b7c2c69e2ced48a9286b1b030976f2fb47 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/setup.py @@ -0,0 +1,34 @@ +# +# Copyright (C) 2023, Inria +# GRAPHDECO research group, https://team.inria.fr/graphdeco +# All rights reserved. +# +# This software is free for non-commercial, research and evaluation use +# under the terms of the LICENSE.md file. +# +# For inquiries contact george.drettakis@inria.fr +# + +from setuptools import setup +from torch.utils.cpp_extension import CUDAExtension, BuildExtension +import os +os.path.dirname(os.path.abspath(__file__)) + +setup( + name="vox2seq", + packages=['vox2seq', 'vox2seq.pytorch'], + ext_modules=[ + CUDAExtension( + name="vox2seq._C", + sources=[ + "src/api.cu", + "src/z_order.cu", + "src/hilbert.cu", + "src/ext.cpp", + ], + ) + ], + cmdclass={ + 'build_ext': BuildExtension + } +) diff --git a/OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/src/api.cu b/OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/src/api.cu new file mode 100644 index 0000000000000000000000000000000000000000..072e930f90278f2f407b45750220d7d98c37b91e --- /dev/null +++ b/OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/src/api.cu @@ -0,0 +1,92 @@ +#include +#include "api.h" +#include "z_order.h" +#include "hilbert.h" + + +torch::Tensor +z_order_encode( + const torch::Tensor& x, + const torch::Tensor& y, + const torch::Tensor& z +) { + // Allocate output tensor + torch::Tensor codes = torch::empty_like(x); + + // Call CUDA kernel + z_order_encode_cuda<<<(x.size(0) + BLOCK_SIZE - 1) / BLOCK_SIZE, BLOCK_SIZE>>>( + x.size(0), + reinterpret_cast(x.contiguous().data_ptr()), + reinterpret_cast(y.contiguous().data_ptr()), + reinterpret_cast(z.contiguous().data_ptr()), + reinterpret_cast(codes.data_ptr()) + ); + + return codes; +} + + +std::tuple +z_order_decode( + const torch::Tensor& codes +) { + // Allocate output tensors + torch::Tensor x = torch::empty_like(codes); + torch::Tensor y = torch::empty_like(codes); + torch::Tensor z = torch::empty_like(codes); + + // Call CUDA kernel + z_order_decode_cuda<<<(codes.size(0) + BLOCK_SIZE - 1) / BLOCK_SIZE, BLOCK_SIZE>>>( + codes.size(0), + reinterpret_cast(codes.contiguous().data_ptr()), + reinterpret_cast(x.data_ptr()), + reinterpret_cast(y.data_ptr()), + reinterpret_cast(z.data_ptr()) + ); + + return std::make_tuple(x, y, z); +} + + +torch::Tensor +hilbert_encode( + const torch::Tensor& x, + const torch::Tensor& y, + const torch::Tensor& z +) { + // Allocate output tensor + torch::Tensor codes = torch::empty_like(x); + + // Call CUDA kernel + hilbert_encode_cuda<<<(x.size(0) + BLOCK_SIZE - 1) / BLOCK_SIZE, BLOCK_SIZE>>>( + x.size(0), + reinterpret_cast(x.contiguous().data_ptr()), + reinterpret_cast(y.contiguous().data_ptr()), + reinterpret_cast(z.contiguous().data_ptr()), + reinterpret_cast(codes.data_ptr()) + ); + + return codes; +} + + +std::tuple +hilbert_decode( + const torch::Tensor& codes +) { + // Allocate output tensors + torch::Tensor x = torch::empty_like(codes); + torch::Tensor y = torch::empty_like(codes); + torch::Tensor z = torch::empty_like(codes); + + // Call CUDA kernel + hilbert_decode_cuda<<<(codes.size(0) + BLOCK_SIZE - 1) / BLOCK_SIZE, BLOCK_SIZE>>>( + codes.size(0), + reinterpret_cast(codes.contiguous().data_ptr()), + reinterpret_cast(x.data_ptr()), + reinterpret_cast(y.data_ptr()), + reinterpret_cast(z.data_ptr()) + ); + + return std::make_tuple(x, y, z); +} diff --git a/OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/src/api.h b/OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/src/api.h new file mode 100644 index 0000000000000000000000000000000000000000..26a68348d56585d0e9e1dfb4900a0d23587df9a6 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/src/api.h @@ -0,0 +1,76 @@ +/* + * Serialize a voxel grid + * + * Copyright (C) 2024, Jianfeng XIANG + * All rights reserved. + * + * Licensed under The MIT License [see LICENSE for details] + * + * Written by Jianfeng XIANG + */ + +#pragma once +#include + + +#define BLOCK_SIZE 256 + + +/** + * Z-order encode 3D points + * + * @param x [N] tensor containing the x coordinates + * @param y [N] tensor containing the y coordinates + * @param z [N] tensor containing the z coordinates + * + * @return [N] tensor containing the z-order encoded values + */ +torch::Tensor +z_order_encode( + const torch::Tensor& x, + const torch::Tensor& y, + const torch::Tensor& z +); + + +/** + * Z-order decode 3D points + * + * @param codes [N] tensor containing the z-order encoded values + * + * @return 3 tensors [N] containing the x, y, z coordinates + */ +std::tuple +z_order_decode( + const torch::Tensor& codes +); + + +/** + * Hilbert encode 3D points + * + * @param x [N] tensor containing the x coordinates + * @param y [N] tensor containing the y coordinates + * @param z [N] tensor containing the z coordinates + * + * @return [N] tensor containing the Hilbert encoded values + */ +torch::Tensor +hilbert_encode( + const torch::Tensor& x, + const torch::Tensor& y, + const torch::Tensor& z +); + + +/** + * Hilbert decode 3D points + * + * @param codes [N] tensor containing the Hilbert encoded values + * + * @return 3 tensors [N] containing the x, y, z coordinates + */ +std::tuple +hilbert_decode( + const torch::Tensor& codes +); diff --git a/OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/src/ext.cpp b/OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/src/ext.cpp new file mode 100644 index 0000000000000000000000000000000000000000..72e76d3b361eb8f355760f067f71005d4e37902c --- /dev/null +++ b/OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/src/ext.cpp @@ -0,0 +1,10 @@ +#include +#include "api.h" + + +PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { + m.def("z_order_encode", &z_order_encode); + m.def("z_order_decode", &z_order_decode); + m.def("hilbert_encode", &hilbert_encode); + m.def("hilbert_decode", &hilbert_decode); +} \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/src/hilbert.cu b/OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/src/hilbert.cu new file mode 100644 index 0000000000000000000000000000000000000000..b3c5bb19474a528cf6f3102e728fa7550588ca61 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/src/hilbert.cu @@ -0,0 +1,133 @@ +#include +#include +#include + +#include +#include +namespace cg = cooperative_groups; + +#include "hilbert.h" + + +// Expands a 10-bit integer into 30 bits by inserting 2 zeros after each bit. +static __device__ uint32_t expandBits(uint32_t v) +{ + v = (v * 0x00010001u) & 0xFF0000FFu; + v = (v * 0x00000101u) & 0x0F00F00Fu; + v = (v * 0x00000011u) & 0xC30C30C3u; + v = (v * 0x00000005u) & 0x49249249u; + return v; +} + + +// Removes 2 zeros after each bit in a 30-bit integer. +static __device__ uint32_t extractBits(uint32_t v) +{ + v = v & 0x49249249; + v = (v ^ (v >> 2)) & 0x030C30C3u; + v = (v ^ (v >> 4)) & 0x0300F00Fu; + v = (v ^ (v >> 8)) & 0x030000FFu; + v = (v ^ (v >> 16)) & 0x000003FFu; + return v; +} + + +__global__ void hilbert_encode_cuda( + size_t N, + const uint32_t* x, + const uint32_t* y, + const uint32_t* z, + uint32_t* codes +) { + size_t thread_id = cg::this_grid().thread_rank(); + if (thread_id >= N) return; + + uint32_t point[3] = {x[thread_id], y[thread_id], z[thread_id]}; + + uint32_t m = 1 << 9, q, p, t; + + // Inverse undo excess work + q = m; + while (q > 1) { + p = q - 1; + for (int i = 0; i < 3; i++) { + if (point[i] & q) { + point[0] ^= p; // invert + } else { + t = (point[0] ^ point[i]) & p; + point[0] ^= t; + point[i] ^= t; + } + } + q >>= 1; + } + + // Gray encode + for (int i = 1; i < 3; i++) { + point[i] ^= point[i - 1]; + } + t = 0; + q = m; + while (q > 1) { + if (point[2] & q) { + t ^= q - 1; + } + q >>= 1; + } + for (int i = 0; i < 3; i++) { + point[i] ^= t; + } + + // Convert to 3D Hilbert code + uint32_t xx = expandBits(point[0]); + uint32_t yy = expandBits(point[1]); + uint32_t zz = expandBits(point[2]); + + codes[thread_id] = xx * 4 + yy * 2 + zz; +} + + +__global__ void hilbert_decode_cuda( + size_t N, + const uint32_t* codes, + uint32_t* x, + uint32_t* y, + uint32_t* z +) { + size_t thread_id = cg::this_grid().thread_rank(); + if (thread_id >= N) return; + + uint32_t point[3]; + point[0] = extractBits(codes[thread_id] >> 2); + point[1] = extractBits(codes[thread_id] >> 1); + point[2] = extractBits(codes[thread_id]); + + uint32_t m = 2 << 9, q, p, t; + + // Gray decode by H ^ (H/2) + t = point[2] >> 1; + for (int i = 2; i > 0; i--) { + point[i] ^= point[i - 1]; + } + point[0] ^= t; + + // Undo excess work + q = 2; + while (q != m) { + p = q - 1; + for (int i = 2; i >= 0; i--) { + if (point[i] & q) { + point[0] ^= p; + } else { + t = (point[0] ^ point[i]) & p; + point[0] ^= t; + point[i] ^= t; + } + } + q <<= 1; + } + + x[thread_id] = point[0]; + y[thread_id] = point[1]; + z[thread_id] = point[2]; +} diff --git a/OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/src/hilbert.h b/OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/src/hilbert.h new file mode 100644 index 0000000000000000000000000000000000000000..4896bf6006f43e5e527d8bde691ce7a54b38c4d7 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/src/hilbert.h @@ -0,0 +1,35 @@ +#pragma once + +/** + * Hilbert encode 3D points + * + * @param x [N] tensor containing the x coordinates + * @param y [N] tensor containing the y coordinates + * @param z [N] tensor containing the z coordinates + * + * @return [N] tensor containing the z-order encoded values + */ +__global__ void hilbert_encode_cuda( + size_t N, + const uint32_t* x, + const uint32_t* y, + const uint32_t* z, + uint32_t* codes +); + + +/** + * Hilbert decode 3D points + * + * @param codes [N] tensor containing the z-order encoded values + * @param x [N] tensor containing the x coordinates + * @param y [N] tensor containing the y coordinates + * @param z [N] tensor containing the z coordinates + */ +__global__ void hilbert_decode_cuda( + size_t N, + const uint32_t* codes, + uint32_t* x, + uint32_t* y, + uint32_t* z +); diff --git a/OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/src/z_order.cu b/OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/src/z_order.cu new file mode 100644 index 0000000000000000000000000000000000000000..ba6f5a91e55588d1ca4bea7cb45e6936330a694b --- /dev/null +++ b/OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/src/z_order.cu @@ -0,0 +1,66 @@ +#include +#include +#include + +#include +#include +namespace cg = cooperative_groups; + +#include "z_order.h" + + +// Expands a 10-bit integer into 30 bits by inserting 2 zeros after each bit. +static __device__ uint32_t expandBits(uint32_t v) +{ + v = (v * 0x00010001u) & 0xFF0000FFu; + v = (v * 0x00000101u) & 0x0F00F00Fu; + v = (v * 0x00000011u) & 0xC30C30C3u; + v = (v * 0x00000005u) & 0x49249249u; + return v; +} + + +// Removes 2 zeros after each bit in a 30-bit integer. +static __device__ uint32_t extractBits(uint32_t v) +{ + v = v & 0x49249249; + v = (v ^ (v >> 2)) & 0x030C30C3u; + v = (v ^ (v >> 4)) & 0x0300F00Fu; + v = (v ^ (v >> 8)) & 0x030000FFu; + v = (v ^ (v >> 16)) & 0x000003FFu; + return v; +} + + +__global__ void z_order_encode_cuda( + size_t N, + const uint32_t* x, + const uint32_t* y, + const uint32_t* z, + uint32_t* codes +) { + size_t thread_id = cg::this_grid().thread_rank(); + if (thread_id >= N) return; + + uint32_t xx = expandBits(x[thread_id]); + uint32_t yy = expandBits(y[thread_id]); + uint32_t zz = expandBits(z[thread_id]); + + codes[thread_id] = xx * 4 + yy * 2 + zz; +} + + +__global__ void z_order_decode_cuda( + size_t N, + const uint32_t* codes, + uint32_t* x, + uint32_t* y, + uint32_t* z +) { + size_t thread_id = cg::this_grid().thread_rank(); + if (thread_id >= N) return; + + x[thread_id] = extractBits(codes[thread_id] >> 2); + y[thread_id] = extractBits(codes[thread_id] >> 1); + z[thread_id] = extractBits(codes[thread_id]); +} diff --git a/OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/src/z_order.h b/OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/src/z_order.h new file mode 100644 index 0000000000000000000000000000000000000000..a4aa857d064e375c8f2eb023abd9ac4af5a2d8f5 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/src/z_order.h @@ -0,0 +1,35 @@ +#pragma once + +/** + * Z-order encode 3D points + * + * @param x [N] tensor containing the x coordinates + * @param y [N] tensor containing the y coordinates + * @param z [N] tensor containing the z coordinates + * + * @return [N] tensor containing the z-order encoded values + */ +__global__ void z_order_encode_cuda( + size_t N, + const uint32_t* x, + const uint32_t* y, + const uint32_t* z, + uint32_t* codes +); + + +/** + * Z-order decode 3D points + * + * @param codes [N] tensor containing the z-order encoded values + * @param x [N] tensor containing the x coordinates + * @param y [N] tensor containing the y coordinates + * @param z [N] tensor containing the z coordinates + */ +__global__ void z_order_decode_cuda( + size_t N, + const uint32_t* codes, + uint32_t* x, + uint32_t* y, + uint32_t* z +); diff --git a/OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/vox2seq/__init__.py b/OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/vox2seq/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ba13bb5f46b2ba90c7882f23b7d97c3b6fe960ac --- /dev/null +++ b/OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/vox2seq/__init__.py @@ -0,0 +1,50 @@ + +from typing import * +import torch +from . import _C +from . import pytorch + + +@torch.no_grad() +def encode(coords: torch.Tensor, permute: List[int] = [0, 1, 2], mode: Literal['z_order', 'hilbert'] = 'z_order') -> torch.Tensor: + """ + Encodes 3D coordinates into a 30-bit code. + + Args: + coords: a tensor of shape [N, 3] containing the 3D coordinates. + permute: the permutation of the coordinates. + mode: the encoding mode to use. + """ + assert coords.shape[-1] == 3 and coords.ndim == 2, "Input coordinates must be of shape [N, 3]" + x = coords[:, permute[0]].int() + y = coords[:, permute[1]].int() + z = coords[:, permute[2]].int() + if mode == 'z_order': + return _C.z_order_encode(x, y, z) + elif mode == 'hilbert': + return _C.hilbert_encode(x, y, z) + else: + raise ValueError(f"Unknown encoding mode: {mode}") + + +@torch.no_grad() +def decode(code: torch.Tensor, permute: List[int] = [0, 1, 2], mode: Literal['z_order', 'hilbert'] = 'z_order') -> torch.Tensor: + """ + Decodes a 30-bit code into 3D coordinates. + + Args: + code: a tensor of shape [N] containing the 30-bit code. + permute: the permutation of the coordinates. + mode: the decoding mode to use. + """ + assert code.ndim == 1, "Input code must be of shape [N]" + if mode == 'z_order': + coords = _C.z_order_decode(code) + elif mode == 'hilbert': + coords = _C.hilbert_decode(code) + else: + raise ValueError(f"Unknown decoding mode: {mode}") + x = coords[permute.index(0)] + y = coords[permute.index(1)] + z = coords[permute.index(2)] + return torch.stack([x, y, z], dim=-1) diff --git a/OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/vox2seq/pytorch/__init__.py b/OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/vox2seq/pytorch/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..25c74c42feb802b24eee9a1bc8744040468c927d --- /dev/null +++ b/OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/vox2seq/pytorch/__init__.py @@ -0,0 +1,48 @@ +import torch +from typing import * + +from .default import ( + encode, + decode, + z_order_encode, + z_order_decode, + hilbert_encode, + hilbert_decode, +) + + +@torch.no_grad() +def encode(coords: torch.Tensor, permute: List[int] = [0, 1, 2], mode: Literal['z_order', 'hilbert'] = 'z_order') -> torch.Tensor: + """ + Encodes 3D coordinates into a 30-bit code. + + Args: + coords: a tensor of shape [N, 3] containing the 3D coordinates. + permute: the permutation of the coordinates. + mode: the encoding mode to use. + """ + if mode == 'z_order': + return z_order_encode(coords[:, permute], depth=10).int() + elif mode == 'hilbert': + return hilbert_encode(coords[:, permute], depth=10).int() + else: + raise ValueError(f"Unknown encoding mode: {mode}") + + +@torch.no_grad() +def decode(code: torch.Tensor, permute: List[int] = [0, 1, 2], mode: Literal['z_order', 'hilbert'] = 'z_order') -> torch.Tensor: + """ + Decodes a 30-bit code into 3D coordinates. + + Args: + code: a tensor of shape [N] containing the 30-bit code. + permute: the permutation of the coordinates. + mode: the decoding mode to use. + """ + if mode == 'z_order': + return z_order_decode(code, depth=10)[:, permute].float() + elif mode == 'hilbert': + return hilbert_decode(code, depth=10)[:, permute].float() + else: + raise ValueError(f"Unknown decoding mode: {mode}") + \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/vox2seq/pytorch/default.py b/OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/vox2seq/pytorch/default.py new file mode 100644 index 0000000000000000000000000000000000000000..906f9bfbe80fcf71977ca774b6491ff63a1ee43b --- /dev/null +++ b/OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/vox2seq/pytorch/default.py @@ -0,0 +1,59 @@ +import torch +from .z_order import xyz2key as z_order_encode_ +from .z_order import key2xyz as z_order_decode_ +from .hilbert import encode as hilbert_encode_ +from .hilbert import decode as hilbert_decode_ + + +@torch.inference_mode() +def encode(grid_coord, batch=None, depth=16, order="z"): + assert order in {"z", "z-trans", "hilbert", "hilbert-trans"} + if order == "z": + code = z_order_encode(grid_coord, depth=depth) + elif order == "z-trans": + code = z_order_encode(grid_coord[:, [1, 0, 2]], depth=depth) + elif order == "hilbert": + code = hilbert_encode(grid_coord, depth=depth) + elif order == "hilbert-trans": + code = hilbert_encode(grid_coord[:, [1, 0, 2]], depth=depth) + else: + raise NotImplementedError + if batch is not None: + batch = batch.long() + code = batch << depth * 3 | code + return code + + +@torch.inference_mode() +def decode(code, depth=16, order="z"): + assert order in {"z", "hilbert"} + batch = code >> depth * 3 + code = code & ((1 << depth * 3) - 1) + if order == "z": + grid_coord = z_order_decode(code, depth=depth) + elif order == "hilbert": + grid_coord = hilbert_decode(code, depth=depth) + else: + raise NotImplementedError + return grid_coord, batch + + +def z_order_encode(grid_coord: torch.Tensor, depth: int = 16): + x, y, z = grid_coord[:, 0].long(), grid_coord[:, 1].long(), grid_coord[:, 2].long() + # we block the support to batch, maintain batched code in Point class + code = z_order_encode_(x, y, z, b=None, depth=depth) + return code + + +def z_order_decode(code: torch.Tensor, depth): + x, y, z, _ = z_order_decode_(code, depth=depth) + grid_coord = torch.stack([x, y, z], dim=-1) # (N, 3) + return grid_coord + + +def hilbert_encode(grid_coord: torch.Tensor, depth: int = 16): + return hilbert_encode_(grid_coord, num_dims=3, num_bits=depth) + + +def hilbert_decode(code: torch.Tensor, depth: int = 16): + return hilbert_decode_(code, num_dims=3, num_bits=depth) \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/vox2seq/pytorch/hilbert.py b/OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/vox2seq/pytorch/hilbert.py new file mode 100644 index 0000000000000000000000000000000000000000..c3fb6565ff855c50553d6215eb74407f88b43a01 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/vox2seq/pytorch/hilbert.py @@ -0,0 +1,303 @@ +""" +Hilbert Order +Modified from https://github.com/PrincetonLIPS/numpy-hilbert-curve + +Author: Xiaoyang Wu (xiaoyang.wu.cs@gmail.com), Kaixin Xu +Please cite our work if the code is helpful to you. +""" + +import torch + + +def right_shift(binary, k=1, axis=-1): + """Right shift an array of binary values. + + Parameters: + ----------- + binary: An ndarray of binary values. + + k: The number of bits to shift. Default 1. + + axis: The axis along which to shift. Default -1. + + Returns: + -------- + Returns an ndarray with zero prepended and the ends truncated, along + whatever axis was specified.""" + + # If we're shifting the whole thing, just return zeros. + if binary.shape[axis] <= k: + return torch.zeros_like(binary) + + # Determine the padding pattern. + # padding = [(0,0)] * len(binary.shape) + # padding[axis] = (k,0) + + # Determine the slicing pattern to eliminate just the last one. + slicing = [slice(None)] * len(binary.shape) + slicing[axis] = slice(None, -k) + shifted = torch.nn.functional.pad( + binary[tuple(slicing)], (k, 0), mode="constant", value=0 + ) + + return shifted + + +def binary2gray(binary, axis=-1): + """Convert an array of binary values into Gray codes. + + This uses the classic X ^ (X >> 1) trick to compute the Gray code. + + Parameters: + ----------- + binary: An ndarray of binary values. + + axis: The axis along which to compute the gray code. Default=-1. + + Returns: + -------- + Returns an ndarray of Gray codes. + """ + shifted = right_shift(binary, axis=axis) + + # Do the X ^ (X >> 1) trick. + gray = torch.logical_xor(binary, shifted) + + return gray + + +def gray2binary(gray, axis=-1): + """Convert an array of Gray codes back into binary values. + + Parameters: + ----------- + gray: An ndarray of gray codes. + + axis: The axis along which to perform Gray decoding. Default=-1. + + Returns: + -------- + Returns an ndarray of binary values. + """ + + # Loop the log2(bits) number of times necessary, with shift and xor. + shift = 2 ** (torch.Tensor([gray.shape[axis]]).log2().ceil().int() - 1) + while shift > 0: + gray = torch.logical_xor(gray, right_shift(gray, shift)) + shift = torch.div(shift, 2, rounding_mode="floor") + return gray + + +def encode(locs, num_dims, num_bits): + """Decode an array of locations in a hypercube into a Hilbert integer. + + This is a vectorized-ish version of the Hilbert curve implementation by John + Skilling as described in: + + Skilling, J. (2004, April). Programming the Hilbert curve. In AIP Conference + Proceedings (Vol. 707, No. 1, pp. 381-387). American Institute of Physics. + + Params: + ------- + locs - An ndarray of locations in a hypercube of num_dims dimensions, in + which each dimension runs from 0 to 2**num_bits-1. The shape can + be arbitrary, as long as the last dimension of the same has size + num_dims. + + num_dims - The dimensionality of the hypercube. Integer. + + num_bits - The number of bits for each dimension. Integer. + + Returns: + -------- + The output is an ndarray of uint64 integers with the same shape as the + input, excluding the last dimension, which needs to be num_dims. + """ + + # Keep around the original shape for later. + orig_shape = locs.shape + bitpack_mask = 1 << torch.arange(0, 8).to(locs.device) + bitpack_mask_rev = bitpack_mask.flip(-1) + + if orig_shape[-1] != num_dims: + raise ValueError( + """ + The shape of locs was surprising in that the last dimension was of size + %d, but num_dims=%d. These need to be equal. + """ + % (orig_shape[-1], num_dims) + ) + + if num_dims * num_bits > 63: + raise ValueError( + """ + num_dims=%d and num_bits=%d for %d bits total, which can't be encoded + into a int64. Are you sure you need that many points on your Hilbert + curve? + """ + % (num_dims, num_bits, num_dims * num_bits) + ) + + # Treat the location integers as 64-bit unsigned and then split them up into + # a sequence of uint8s. Preserve the association by dimension. + locs_uint8 = locs.long().view(torch.uint8).reshape((-1, num_dims, 8)).flip(-1) + + # Now turn these into bits and truncate to num_bits. + gray = ( + locs_uint8.unsqueeze(-1) + .bitwise_and(bitpack_mask_rev) + .ne(0) + .byte() + .flatten(-2, -1)[..., -num_bits:] + ) + + # Run the decoding process the other way. + # Iterate forwards through the bits. + for bit in range(0, num_bits): + # Iterate forwards through the dimensions. + for dim in range(0, num_dims): + # Identify which ones have this bit active. + mask = gray[:, dim, bit] + + # Where this bit is on, invert the 0 dimension for lower bits. + gray[:, 0, bit + 1 :] = torch.logical_xor( + gray[:, 0, bit + 1 :], mask[:, None] + ) + + # Where the bit is off, exchange the lower bits with the 0 dimension. + to_flip = torch.logical_and( + torch.logical_not(mask[:, None]).repeat(1, gray.shape[2] - bit - 1), + torch.logical_xor(gray[:, 0, bit + 1 :], gray[:, dim, bit + 1 :]), + ) + gray[:, dim, bit + 1 :] = torch.logical_xor( + gray[:, dim, bit + 1 :], to_flip + ) + gray[:, 0, bit + 1 :] = torch.logical_xor(gray[:, 0, bit + 1 :], to_flip) + + # Now flatten out. + gray = gray.swapaxes(1, 2).reshape((-1, num_bits * num_dims)) + + # Convert Gray back to binary. + hh_bin = gray2binary(gray) + + # Pad back out to 64 bits. + extra_dims = 64 - num_bits * num_dims + padded = torch.nn.functional.pad(hh_bin, (extra_dims, 0), "constant", 0) + + # Convert binary values into uint8s. + hh_uint8 = ( + (padded.flip(-1).reshape((-1, 8, 8)) * bitpack_mask) + .sum(2) + .squeeze() + .type(torch.uint8) + ) + + # Convert uint8s into uint64s. + hh_uint64 = hh_uint8.view(torch.int64).squeeze() + + return hh_uint64 + + +def decode(hilberts, num_dims, num_bits): + """Decode an array of Hilbert integers into locations in a hypercube. + + This is a vectorized-ish version of the Hilbert curve implementation by John + Skilling as described in: + + Skilling, J. (2004, April). Programming the Hilbert curve. In AIP Conference + Proceedings (Vol. 707, No. 1, pp. 381-387). American Institute of Physics. + + Params: + ------- + hilberts - An ndarray of Hilbert integers. Must be an integer dtype and + cannot have fewer bits than num_dims * num_bits. + + num_dims - The dimensionality of the hypercube. Integer. + + num_bits - The number of bits for each dimension. Integer. + + Returns: + -------- + The output is an ndarray of unsigned integers with the same shape as hilberts + but with an additional dimension of size num_dims. + """ + + if num_dims * num_bits > 64: + raise ValueError( + """ + num_dims=%d and num_bits=%d for %d bits total, which can't be encoded + into a uint64. Are you sure you need that many points on your Hilbert + curve? + """ + % (num_dims, num_bits) + ) + + # Handle the case where we got handed a naked integer. + hilberts = torch.atleast_1d(hilberts) + + # Keep around the shape for later. + orig_shape = hilberts.shape + bitpack_mask = 2 ** torch.arange(0, 8).to(hilberts.device) + bitpack_mask_rev = bitpack_mask.flip(-1) + + # Treat each of the hilberts as a s equence of eight uint8. + # This treats all of the inputs as uint64 and makes things uniform. + hh_uint8 = ( + hilberts.ravel().type(torch.int64).view(torch.uint8).reshape((-1, 8)).flip(-1) + ) + + # Turn these lists of uints into lists of bits and then truncate to the size + # we actually need for using Skilling's procedure. + hh_bits = ( + hh_uint8.unsqueeze(-1) + .bitwise_and(bitpack_mask_rev) + .ne(0) + .byte() + .flatten(-2, -1)[:, -num_dims * num_bits :] + ) + + # Take the sequence of bits and Gray-code it. + gray = binary2gray(hh_bits) + + # There has got to be a better way to do this. + # I could index them differently, but the eventual packbits likes it this way. + gray = gray.reshape((-1, num_bits, num_dims)).swapaxes(1, 2) + + # Iterate backwards through the bits. + for bit in range(num_bits - 1, -1, -1): + # Iterate backwards through the dimensions. + for dim in range(num_dims - 1, -1, -1): + # Identify which ones have this bit active. + mask = gray[:, dim, bit] + + # Where this bit is on, invert the 0 dimension for lower bits. + gray[:, 0, bit + 1 :] = torch.logical_xor( + gray[:, 0, bit + 1 :], mask[:, None] + ) + + # Where the bit is off, exchange the lower bits with the 0 dimension. + to_flip = torch.logical_and( + torch.logical_not(mask[:, None]), + torch.logical_xor(gray[:, 0, bit + 1 :], gray[:, dim, bit + 1 :]), + ) + gray[:, dim, bit + 1 :] = torch.logical_xor( + gray[:, dim, bit + 1 :], to_flip + ) + gray[:, 0, bit + 1 :] = torch.logical_xor(gray[:, 0, bit + 1 :], to_flip) + + # Pad back out to 64 bits. + extra_dims = 64 - num_bits + padded = torch.nn.functional.pad(gray, (extra_dims, 0), "constant", 0) + + # Now chop these up into blocks of 8. + locs_chopped = padded.flip(-1).reshape((-1, num_dims, 8, 8)) + + # Take those blocks and turn them unto uint8s. + # from IPython import embed; embed() + locs_uint8 = (locs_chopped * bitpack_mask).sum(3).squeeze().type(torch.uint8) + + # Finally, treat these as uint64s. + flat_locs = locs_uint8.view(torch.int64) + + # Return them in the expected shape. + return flat_locs.reshape((*orig_shape, num_dims)) \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/vox2seq/pytorch/z_order.py b/OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/vox2seq/pytorch/z_order.py new file mode 100644 index 0000000000000000000000000000000000000000..b33963de44ddfcbecdf2e403ea70166f2d0e4eb0 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/vox2seq/pytorch/z_order.py @@ -0,0 +1,126 @@ +# -------------------------------------------------------- +# Octree-based Sparse Convolutional Neural Networks +# Copyright (c) 2022 Peng-Shuai Wang +# Licensed under The MIT License [see LICENSE for details] +# Written by Peng-Shuai Wang +# -------------------------------------------------------- + +import torch +from typing import Optional, Union + + +class KeyLUT: + def __init__(self): + r256 = torch.arange(256, dtype=torch.int64) + r512 = torch.arange(512, dtype=torch.int64) + zero = torch.zeros(256, dtype=torch.int64) + device = torch.device("cpu") + + self._encode = { + device: ( + self.xyz2key(r256, zero, zero, 8), + self.xyz2key(zero, r256, zero, 8), + self.xyz2key(zero, zero, r256, 8), + ) + } + self._decode = {device: self.key2xyz(r512, 9)} + + def encode_lut(self, device=torch.device("cpu")): + if device not in self._encode: + cpu = torch.device("cpu") + self._encode[device] = tuple(e.to(device) for e in self._encode[cpu]) + return self._encode[device] + + def decode_lut(self, device=torch.device("cpu")): + if device not in self._decode: + cpu = torch.device("cpu") + self._decode[device] = tuple(e.to(device) for e in self._decode[cpu]) + return self._decode[device] + + def xyz2key(self, x, y, z, depth): + key = torch.zeros_like(x) + for i in range(depth): + mask = 1 << i + key = ( + key + | ((x & mask) << (2 * i + 2)) + | ((y & mask) << (2 * i + 1)) + | ((z & mask) << (2 * i + 0)) + ) + return key + + def key2xyz(self, key, depth): + x = torch.zeros_like(key) + y = torch.zeros_like(key) + z = torch.zeros_like(key) + for i in range(depth): + x = x | ((key & (1 << (3 * i + 2))) >> (2 * i + 2)) + y = y | ((key & (1 << (3 * i + 1))) >> (2 * i + 1)) + z = z | ((key & (1 << (3 * i + 0))) >> (2 * i + 0)) + return x, y, z + + +_key_lut = KeyLUT() + + +def xyz2key( + x: torch.Tensor, + y: torch.Tensor, + z: torch.Tensor, + b: Optional[Union[torch.Tensor, int]] = None, + depth: int = 16, +): + r"""Encodes :attr:`x`, :attr:`y`, :attr:`z` coordinates to the shuffled keys + based on pre-computed look up tables. The speed of this function is much + faster than the method based on for-loop. + + Args: + x (torch.Tensor): The x coordinate. + y (torch.Tensor): The y coordinate. + z (torch.Tensor): The z coordinate. + b (torch.Tensor or int): The batch index of the coordinates, and should be + smaller than 32768. If :attr:`b` is :obj:`torch.Tensor`, the size of + :attr:`b` must be the same as :attr:`x`, :attr:`y`, and :attr:`z`. + depth (int): The depth of the shuffled key, and must be smaller than 17 (< 17). + """ + + EX, EY, EZ = _key_lut.encode_lut(x.device) + x, y, z = x.long(), y.long(), z.long() + + mask = 255 if depth > 8 else (1 << depth) - 1 + key = EX[x & mask] | EY[y & mask] | EZ[z & mask] + if depth > 8: + mask = (1 << (depth - 8)) - 1 + key16 = EX[(x >> 8) & mask] | EY[(y >> 8) & mask] | EZ[(z >> 8) & mask] + key = key16 << 24 | key + + if b is not None: + b = b.long() + key = b << 48 | key + + return key + + +def key2xyz(key: torch.Tensor, depth: int = 16): + r"""Decodes the shuffled key to :attr:`x`, :attr:`y`, :attr:`z` coordinates + and the batch index based on pre-computed look up tables. + + Args: + key (torch.Tensor): The shuffled key. + depth (int): The depth of the shuffled key, and must be smaller than 17 (< 17). + """ + + DX, DY, DZ = _key_lut.decode_lut(key.device) + x, y, z = torch.zeros_like(key), torch.zeros_like(key), torch.zeros_like(key) + + b = key >> 48 + key = key & ((1 << 48) - 1) + + n = (depth + 2) // 3 + for i in range(n): + k = key >> (i * 9) & 511 + x = x | (DX[k] << (i * 3)) + y = y | (DY[k] << (i * 3)) + z = z | (DZ[k] << (i * 3)) + + return x, y, z, b \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/Amodal3R/inference.py b/OVOW/engine/oneposeviagen/Amodal3R/inference.py new file mode 100644 index 0000000000000000000000000000000000000000..053528cf62a44e59f493d79644dcecf0c6e5cc3a --- /dev/null +++ b/OVOW/engine/oneposeviagen/Amodal3R/inference.py @@ -0,0 +1,107 @@ +import os +os.environ['ATTN_BACKEND'] = 'xformers' # Can be 'flash-attn' or 'xformers', default is 'flash-attn' +# os.environ['SPCONV_ALGO'] = 'native' # Can be 'native' or 'auto', default is 'auto'. + # 'auto' is faster but will do benchmarking at the beginning. + # Recommended to set to 'native' if run only once. + +import numpy as np +import imageio +from PIL import Image +from amodal3r.pipelines import Amodal3RImageTo3DPipeline +from amodal3r.utils import render_utils, postprocessing_utils +import cv2 +import trimesh + + +def extract_glb(gs, mesh, mesh_simplify=0.95, texture_size=1024, export_path="output.glb"): + """ + Extract a GLB file from the 3D model. + + Args: + state (dict): The state of the generated 3D model. + mesh_simplify (float): The mesh simplification factor. + texture_size (int): The texture resolution. + + Returns: + str: The path to the extracted GLB file. + """ + + glb = postprocessing_utils.to_glb(gs, mesh, simplify=mesh_simplify, texture_size=texture_size, verbose=False) + glb.export(export_path) + return export_path + +def save_mesh(mesh_result, filename): + vertices = mesh_result.vertices.cpu().numpy() if hasattr(mesh_result.vertices, 'cpu') else mesh_result.vertices + faces = mesh_result.faces.cpu().numpy() if hasattr(mesh_result.faces, 'cpu') else mesh_result.faces + + mesh = trimesh.Trimesh(vertices=vertices, faces=faces, process=False) + + if mesh_result.vertex_attrs is not None: + attrs = mesh_result.vertex_attrs.cpu().numpy() if hasattr(mesh_result.vertex_attrs, 'cpu') else mesh_result.vertex_attrs + mesh.visual.vertex_colors = attrs + + mesh.export(filename) + +# Load a pipeline from a model folder or a Hugging Face model hub. +pipeline = Amodal3RImageTo3DPipeline.from_pretrained("/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/Amodal3R/Amodal3R") +pipeline.cuda() + + +output_dir = "./output/1/" +os.makedirs(output_dir, exist_ok=True) + +# can be single image or multiple images +images = [ + Image.open(f"/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/code/pose/One23Pose_amodal3r/temp_local/session_bcb9225f/model/rgb_image.png"), +] + +masks = [ + Image.open(f"/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/code/pose/One23Pose_amodal3r/temp_local/session_bcb9225f/model/inverted_mask.png").convert("L"), +] + + +# Run the pipeline +outputs = pipeline.run_multi_image( + images, + masks, + seed=1, + # Optional parameters + sparse_structure_sampler_params={ + "steps": 12, + "cfg_strength": 7.5, + }, + slat_sampler_params={ + "steps": 12, + "cfg_strength": 3, + }, +) + +# save as gif +video_gs = render_utils.render_video(outputs['gaussian'][0], bg_color=(1, 1, 1))['color'] +video_mesh = render_utils.render_video(outputs['mesh'][0], bg_color=(1, 1, 1))['normal'] +video = [np.concatenate([frame_gs, frame_mesh], axis=1) for frame_gs, frame_mesh in zip(video_gs, video_mesh)] +imageio.mimsave(os.path.join(output_dir, "sample_multi.gif"), video, fps=30) + +# save multi-view gs and mesh +# gaussian = outputs['gaussian'][0] +# multi_view_gs,_,_ = render_utils.render_multiview(gaussian, nviews=8, bg_color=(1, 1, 1)) +# multi_view_gs = multi_view_gs['color'] +# for i in range(8): +# output = multi_view_gs[i] +# output = cv2.cvtColor(output, cv2.COLOR_RGB2BGR) +# cv2.imwrite(os.path.join(output_dir, f"{i:03d}_gs.png"), output) + +mesh = outputs['mesh'][0] +# multi_view_mesh,_,_ = render_utils.render_multiview(mesh, nviews=8, bg_color=(1, 1, 1)) +# multi_view_mesh = multi_view_mesh['normal'] +# for i in range(8): +# output = multi_view_mesh[i] +# output = cv2.cvtColor(output, cv2.COLOR_RGB2BGR) +# cv2.imwrite(os.path.join(output_dir, f"{i:03d}_mesh.png"), output) + +# # save mesh +save_mesh(mesh, os.path.join(output_dir, "mesh.ply")) + +# export glb if needed +glb_path = os.path.join(output_dir, "mesh.glb") +extract_glb(outputs['gaussian'][0], outputs['mesh'][0], 0.5, 1024, glb_path) diff --git a/OVOW/engine/oneposeviagen/Amodal3R/lightning/network_slat.py b/OVOW/engine/oneposeviagen/Amodal3R/lightning/network_slat.py new file mode 100644 index 0000000000000000000000000000000000000000..7eface9566eb0a8088b6e5fdf43ae2db08580c9a --- /dev/null +++ b/OVOW/engine/oneposeviagen/Amodal3R/lightning/network_slat.py @@ -0,0 +1,153 @@ +import torch,random +import torch.nn as nn +from torch.nn import functional as F +import numpy as np + +import pytorch_lightning as L +from torchvision import transforms + +from amodal3r.models import SLatFlowModelMaskAsCondWeighted + +from dit.diffusion_slat import GaussianDiffusion, get_betas + +from safetensors.torch import load_file + +class mask_patcher(nn.Module): + def __init__(self): + super(mask_patcher, self).__init__() + + def forward(self, mask, patch_size=14): + """ + Inputs: + mask: tensor, size [B, H, W] (e.g., the original mask might not be 518x518) + patch_size: the size of each patch, default is 14 (since 518/14=37) + Outputs: + patch_ratio: tensor, size [B, 37, 37], where each element represents the ratio of 1's in the corresponding patch of the mask + """ + # 1. Resize the mask if the shape is not (518, 518) + if mask.shape != (518, 518): + mask = F.interpolate(mask.unsqueeze(1).float(), size=(518, 518), mode='nearest') # [B, 1, 518, 518] + else: + mask = mask.unsqueeze(1).float() + + # 2. Use unfold to divide the mask into non-overlapping patches + # Unfold parameters: dimension, window size, stride + patches = mask.unfold(2, patch_size, patch_size).unfold(3, patch_size, patch_size) + # At this point, patches have shape [B, 1, 37, 37, 14, 14] + + # 3. For each patch, compute the ratio of ones in the mask by taking the mean + patch_ratio = patches.mean(dim=(-1, -2)) # Shape becomes [B, 1, 37, 37] + + # 4. Remove the channel dimension + patch_ratio = patch_ratio.squeeze(1) # Final shape is [B, 37, 37] + + return patch_ratio + + +class Network_slat(L.LightningModule): + def __init__(self, cfg, white_bkgd=True): + super(Network_slat, self).__init__() + + self.cfg = cfg + + self.slat_model = SLatFlowModelMaskAsCondWeighted(resolution=64, + in_channels=8, + out_channels=8, + model_channels=1024, + cond_channels=1024, + num_blocks=24, + num_heads=16, + mlp_ratio=4, + patch_size=2, + num_io_res_blocks=2, + io_block_channels=[128], + pe_mode='ape', + qk_rms_norm=True, + use_fp16=False, + use_checkpoint=True, + mask_cond_type='mask_patcher' + ) + + for _, param in self.slat_model.named_parameters(): + param.requires_grad = True + + # diffusion model + betas = get_betas(schedule_type='linear', b_start=0.0001, b_end=0.02, time_num=1000) + self.diffusion = GaussianDiffusion(betas, loss_type='mse', model_mean_type='eps', model_var_type='fixedsmall') + + dinov2_model = torch.hub.load('facebookresearch/dinov2', 'dinov2_vitl14_reg', pretrained=True) + dinov2_model.eval() + for param in dinov2_model.parameters(): + param.requires_grad = False + self.img_encoder = dinov2_model + transform = transforms.Compose([ + transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), + ]) + self.image_cond_model_transform = transform + self.img_encoder_feat_dim = 1024 + + self.std = torch.tensor([2.377650737762451,2.386378288269043,2.124418020248413,2.1748552322387695,2.663944721221924,2.371192216873169,2.6217446327209473,2.684523105621338])[None] + self.mean = torch.tensor([-2.1687545776367188, -0.004347046371549368,-0.13352349400520325,-0.08418072760105133,-0.5271206498146057,0.7238689064979553,-1.1414450407028198,1.2039363384246826])[None] + + self.mask_patcher = mask_patcher() + + self.load_pretrained_slat() + + def load_pretrained_slat(self): + slat_model_weight = load_file("./ckpts/slat_flow_img_dit_L_64l8p2_fp16.safetensors") + self.slat_model.load_state_dict(slat_model_weight, strict=False) + print("load slat model") + + def encode_image(self, inp_imgs): + B, _, _, _ = inp_imgs.shape + inp_imgs = inp_imgs.permute(0, 3, 1, 2) + inp_imgs = torch.stack([self.image_cond_model_transform(inp_imgs[i]) for i in range(B)], dim=0) + encode_imgs = self.img_encoder(inp_imgs, is_training=True)['x_prenorm']#['x_norm_patchtokens'] # [B*N, 37*37, 1024] + encode_imgs = F.layer_norm(encode_imgs, encode_imgs.shape[-1:]) + return encode_imgs + + def logit_normal(self, std, mean, size, device): + # Generate samples from logit-normal distribution + normal_samples = torch.randn(size, device=device) * std + mean + logit_samples = torch.sigmoid(normal_samples) # Apply logit transformation + return logit_samples + + def _denoise(self, x, t, c): + t = t * 1000 + out = self.slat_model(x, t, c) + return out + + def forward(self, batch, if_vis=False): + cond_img = batch['cond_img_518_masked'] + visibility_mask = batch['visibility_mask'] + occlusion_mask = batch['occlusion_mask'] + slat_paths = batch['slat_path'] + B = len(slat_paths) + sp_feats, sp_coords = [], [] + for idx, slat_path in enumerate(slat_paths): + slat_data = np.load(slat_path) + coords = torch.from_numpy(slat_data['coords']).int().to(self.device) + feats = torch.from_numpy(slat_data['feats']).float().to(self.device) + feats = (feats - self.mean.to(self.device)) / self.std.to(self.device) + coords = torch.cat([idx*torch.ones_like(coords[:, 0]).unsqueeze(1), coords], dim=1) + sp_feats.append(feats) + sp_coords.append(coords) + + # extract image features + if random.random() > 0.1: + with torch.no_grad(): + encoded_cond_img = self.encode_image(cond_img) + visibility_mask = self.mask_patcher(1-visibility_mask) + visibility_mask = visibility_mask.view(B, -1).unsqueeze(-1).repeat(1, 1, 1024) + occlusion_mask = self.mask_patcher(occlusion_mask) + occlusion_mask = occlusion_mask.view(B, -1).unsqueeze(-1).repeat(1, 1, 1024) + cond_img = torch.cat([encoded_cond_img, visibility_mask, occlusion_mask], dim=1) + else: + cond_img = torch.zeros((B,1374+37*37+37*37,1024)).to(cond_img.device).to(cond_img.dtype) + + t = self.logit_normal(1.0, 1.0, (B,), device="cuda") # see trellis training details + + loss, _ = self.diffusion.p_losses(denoise_fn=self._denoise, data_start={'feats': sp_feats, 'coords': sp_coords}, t=t, y=cond_img, multi_t=True) + loss = loss.mean() + + return None, loss diff --git a/OVOW/engine/oneposeviagen/Amodal3R/lightning/network_ss.py b/OVOW/engine/oneposeviagen/Amodal3R/lightning/network_ss.py new file mode 100644 index 0000000000000000000000000000000000000000..7159f95eef5fca0c7cc86b839c60e6117610e141 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Amodal3R/lightning/network_ss.py @@ -0,0 +1,133 @@ +import torch,random +import torch.nn as nn +from torch.nn import functional as F + +import pytorch_lightning as L +from torchvision import transforms + +from amodal3r.models import SparseStructureFlowModelMaskAsCondWeighted + +from dit.diffusion_ss import GaussianDiffusion, get_betas +from safetensors.torch import load_file + +class mask_patcher(nn.Module): + def __init__(self): + super(mask_patcher, self).__init__() + + def forward(self, mask, patch_size=14): + """ + Inputs: + mask: tensor, size [B, H, W] (e.g., the original mask might not be 518x518) + patch_size: the size of each patch, default is 14 (since 518/14=37) + Outputs: + patch_ratio: tensor, size [B, 37, 37], where each element represents the ratio of 1's in the corresponding patch of the mask + """ + # 1. Resize the mask if the shape is not (518, 518) + if mask.shape != (518, 518): + mask = F.interpolate(mask.unsqueeze(1).float(), size=(518, 518), mode='nearest') # [B, 1, 518, 518] + else: + mask = mask.unsqueeze(1).float() + + # 2. Use unfold to divide the mask into non-overlapping patches + # Unfold parameters: dimension, window size, stride + patches = mask.unfold(2, patch_size, patch_size).unfold(3, patch_size, patch_size) + # At this point, patches have shape [B, 1, 37, 37, 14, 14] + + # 3. For each patch, compute the ratio of ones in the mask by taking the mean + patch_ratio = patches.mean(dim=(-1, -2)) # Shape becomes [B, 1, 37, 37] + + # 4. Remove the channel dimension + patch_ratio = patch_ratio.squeeze(1) # Final shape is [B, 37, 37] + + return patch_ratio + +class Network_ss(L.LightningModule): + def __init__(self, cfg, white_bkgd=True): + super(Network_ss, self).__init__() + + self.cfg = cfg + + self.ss_model = SparseStructureFlowModelMaskAsCondWeighted(resolution=16, + in_channels=8, + out_channels=8, + model_channels=1024, + cond_channels=1024, + num_blocks=24, + num_heads=16, + mlp_ratio=4, + patch_size=1, + pe_mode='ape', + qk_rms_norm=True, + use_fp16=False, + use_checkpoint=True, + mask_cond_type='mask_patcher') + + # diffusion model + betas = get_betas(schedule_type='linear', b_start=0.0001, b_end=0.02, time_num=1000) + self.diffusion = GaussianDiffusion(betas, loss_type='mse', model_mean_type='eps', model_var_type='fixedsmall') + + dinov2_model = torch.hub.load('facebookresearch/dinov2', 'dinov2_vitl14_reg', pretrained=True) + dinov2_model.eval() + for param in dinov2_model.parameters(): + param.requires_grad = False + self.img_encoder = dinov2_model + transform = transforms.Compose([ + transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), + ]) + self.image_cond_model_transform = transform + self.img_encoder_feat_dim = 1024 + + self.mask_patcher = mask_patcher() + + self.load_pretrained_ss() + + def load_pretrained_ss(self): + ss_model_weight = load_file("./ckpts/ss_flow_img_dit_L_16l8_fp16.safetensors") + self.ss_model.load_state_dict(ss_model_weight, strict=False) + print("load ss model") + + def encode_image(self, inp_imgs): + B, _, _, _ = inp_imgs.shape + inp_imgs = inp_imgs.permute(0, 3, 1, 2) + inp_imgs = torch.stack([self.image_cond_model_transform(inp_imgs[i]) for i in range(B)], dim=0) + encode_imgs = self.img_encoder(inp_imgs, is_training=True)['x_prenorm'] + encode_imgs = F.layer_norm(encode_imgs, encode_imgs.shape[-1:]) + return encode_imgs + + def logit_normal(self, std, mean, size, device): + # Generate samples from logit-normal distribution + normal_samples = torch.randn(size, device=device) * std + mean + logit_samples = torch.sigmoid(normal_samples) # Apply logit transformation + return logit_samples + + def _denoise(self, x, t, c): + t = t * 1000 + out = self.ss_model(x, t, c) + return out + + def forward(self, batch, if_vis=False): + cond_img = batch['cond_img_518_masked'] + visibility_mask = batch['visibility_mask'] + occlusion_mask = batch['occlusion_mask'] + z_s = batch['ss_latent'] + B,_,_,_,_ = z_s.shape + + # extract image features, droprate 10% + random_num = random.random() + if 0.1 < random_num: + with torch.no_grad(): + encoded_cond_img = self.encode_image(cond_img) + patched_visibility_mask = self.mask_patcher(visibility_mask) + visibility_mask_token = patched_visibility_mask.view(B, -1).unsqueeze(-1).repeat(1, 1, 1024) + patched_occlusion_mask = self.mask_patcher(occlusion_mask) + occlusion_mask_token = patched_occlusion_mask.view(B, -1).unsqueeze(-1).repeat(1, 1, 1024) + cond_img = torch.cat([encoded_cond_img, visibility_mask_token, occlusion_mask_token], dim=1) + else: + cond_img = torch.zeros((B,1374+37*37+37*37,1024)).to(cond_img.device).to(cond_img.dtype) + + t = self.logit_normal(1.0, 1.0, (B,), device="cuda") # follow trellis training details + + loss, _ = self.diffusion.p_losses(denoise_fn=self._denoise, data_start=z_s, t=t, y=cond_img) + loss = loss.mean() + + return None, loss diff --git a/OVOW/engine/oneposeviagen/Amodal3R/lightning/system.py b/OVOW/engine/oneposeviagen/Amodal3R/lightning/system.py new file mode 100644 index 0000000000000000000000000000000000000000..2620811022fc69477f94a05c4c865f1104e46b8b --- /dev/null +++ b/OVOW/engine/oneposeviagen/Amodal3R/lightning/system.py @@ -0,0 +1,121 @@ + +import torch +import numpy as np +import pytorch_lightning as L + +import torch.nn as nn +from lightning.utils import vis_images, CosineWarmupScheduler + +from lightning.network_ss import Network_ss +from lightning.network_slat import Network_slat + +import matplotlib.pyplot as plt +import os +import shutil + +class system(L.LightningModule): + def __init__(self, cfg, cfg_path=None): + super().__init__() + + self.cfg = cfg + if cfg.model.type == 'ss': + self.net = Network_ss(cfg) + elif cfg.model.type == 'slat': + self.net = Network_slat(cfg) + + self.validation_step_outputs = [] + + self.vis_dir = cfg.vis_dir + os.makedirs(self.vis_dir, exist_ok=True) + if cfg_path is not None: + shutil.copy(cfg_path, os.path.join(self.vis_dir, 'config.yaml')) + + def training_step(self, batch, batch_idx): + with torch.amp.autocast('cuda'): + output, loss = self.net(batch) + if output is not None: + if 0 == self.trainer.global_step % 1000 and (self.trainer.local_rank == 0): + self.vis_results(output, batch, prex='train') + self.log(f'rec', loss, prog_bar=True) + return loss + + def validation_step(self, batch, batch_idx): + self.net.eval() + output, loss = self.net(batch, if_vis=True) + if output is not None: + if batch_idx == 0 and (self.trainer.local_rank == 0): + self.vis_results(output, batch, prex='val') + self.validation_step_outputs.append({'rec': loss}) + return loss + + def on_validation_epoch_end(self): + keys = self.validation_step_outputs[0] + for key in keys: + prog_bar = True if key in ['psnr','mask','depth', 'rec'] else False + metric_mean = torch.stack([x[key] for x in self.validation_step_outputs]).mean() + self.log(f'val/{key}', metric_mean, prog_bar=prog_bar, sync_dist=True) + + self.validation_step_outputs.clear() # free memory + torch.cuda.empty_cache() + + def vis_results(self, output, batch, prex): + output_vis = vis_images(output, batch) + for key, value in output_vis.items(): + imgs = [np.concatenate([img for img in value],axis=0)] + for idx, img in enumerate(imgs): + img_save_path = os.path.join(self.vis_dir, f'{prex}_{self.global_step}_{key}.png') + plt.imsave(img_save_path, img) + self.net.train() + if hasattr(self.net, 'img_encoder'): + self.net.img_encoder.eval() + + def num_steps(self) -> int: + """Get number of steps""" + # Accessing _data_source is flaky and might break + dataset = self.trainer.fit_loop._data_source.dataloader() + dataset_size = len(dataset) + num_devices = max(1, self.trainer.num_devices) + num_steps = dataset_size * self.trainer.max_epochs * self.cfg.train.limit_train_batches // (self.trainer.accumulate_grad_batches * num_devices) + return int(num_steps) + + def configure_optimizers(self): + decay_params, no_decay_params = [], [] + + # add all bias and LayerNorm params to no_decay_params + for name, module in self.named_modules(): + if isinstance(module, nn.LayerNorm): + no_decay_params.extend([p for p in module.parameters()]) + elif hasattr(module, 'bias') and module.bias is not None: + no_decay_params.append(module.bias) + + # add remaining parameters to decay_params + _no_decay_ids = set(map(id, no_decay_params)) + decay_params = [p for p in self.parameters() if id(p) not in _no_decay_ids] + + # filter out parameters with no grad + decay_params = list(filter(lambda p: p.requires_grad, decay_params)) + no_decay_params = list(filter(lambda p: p.requires_grad, no_decay_params)) + + # Optimizer + opt_groups = [ + {'params': decay_params, 'weight_decay': self.cfg.train.weight_decay}, + {'params': no_decay_params, 'weight_decay': 0.0}, + ] + optimizer = torch.optim.AdamW( + opt_groups, + lr=self.cfg.train.lr, + betas=(self.cfg.train.beta1, self.cfg.train.beta2), + ) + + total_global_batches = self.num_steps() + scheduler = CosineWarmupScheduler( + optimizer=optimizer, + warmup_iters=self.cfg.train.warmup_iters, + max_iters=total_global_batches, + ) + + return {"optimizer": optimizer, + "lr_scheduler": { + 'scheduler': scheduler, + 'interval': 'step' # or 'epoch' for epoch-level updates + }} \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/Amodal3R/lightning/utils.py b/OVOW/engine/oneposeviagen/Amodal3R/lightning/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..03a205442483c33b1de9729a819abe9cfdfdf9a4 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Amodal3R/lightning/utils.py @@ -0,0 +1,129 @@ +import torch, os, json, math +import numpy as np +from torch.optim.lr_scheduler import LRScheduler + +def init_volume_grid(bound=0.45, num_pts_each_axis=32): + # Define the range and number of points + start = -bound + stop = bound + num_points = num_pts_each_axis # Adjust the number of points to your preference + + # Create a linear space for each axis + x = np.linspace(start, stop, num_points) + y = np.linspace(start, stop, num_points) + z = np.linspace(start, stop, num_points) + + # Create a 3D grid of points using meshgrid + X, Y, Z = np.meshgrid(x, y, z, indexing='ij') + + # Stack the grid points in a single array of shape (N, 3) + xyz = np.vstack((X.ravel(), Y.ravel(), Z.ravel())).T + + return xyz + +def getProjectionMatrix(znear, zfar, fovX, fovY): + + tanHalfFovY = torch.tan((fovY / 2)) + tanHalfFovX = torch.tan((fovX / 2)) + + P = torch.zeros(4, 4) + + z_sign = 1.0 + + P[0, 0] = 1 / tanHalfFovX + P[1, 1] = 1 / tanHalfFovY + P[3, 2] = z_sign + P[2, 2] = z_sign * zfar / (zfar - znear) + P[2, 3] = -(zfar * znear) / (zfar - znear) + return P + + +class MiniCam: + def __init__(self, c2w, width, height, fovy, fovx, znear, zfar, device): + # c2w (pose) should be in NeRF convention. + + self.image_width = width + self.image_height = height + self.FoVy = fovy + self.FoVx = fovx + self.znear = znear + self.zfar = zfar + + w2c = torch.inverse(c2w) + + # rectify... + # w2c[1:3, :3] *= -1 + # w2c[:3, 3] *= -1 + + self.world_view_transform = w2c.transpose(0, 1).to(device) + self.projection_matrix = ( + getProjectionMatrix( + znear=self.znear, zfar=self.zfar, fovX=self.FoVx, fovY=self.FoVy + ) + .transpose(0, 1) + .to(device) + ) + self.full_proj_transform = (self.world_view_transform @ self.projection_matrix).float() + self.camera_center = -c2w[:3, 3].to(device) + + +def rotation_matrix_to_quaternion(R): + tr = R[0, 0] + R[1, 1] + R[2, 2] + if tr > 0: + S = torch.sqrt(tr + 1.0) * 2.0 + qw = 0.25 * S + qx = (R[2, 1] - R[1, 2]) / S + qy = (R[0, 2] - R[2, 0]) / S + qz = (R[1, 0] - R[0, 1]) / S + elif (R[0, 0] > R[1, 1]) and (R[0, 0] > R[2, 2]): + S = torch.sqrt(1.0 + R[0, 0] - R[1, 1] - R[2, 2]) * 2.0 + qw = (R[2, 1] - R[1, 2]) / S + qx = 0.25 * S + qy = (R[0, 1] + R[1, 0]) / S + qz = (R[0, 2] + R[2, 0]) / S + elif R[1, 1] > R[2, 2]: + S = torch.sqrt(1.0 + R[1, 1] - R[0, 0] - R[2, 2]) * 2.0 + qw = (R[0, 2] - R[2, 0]) / S + qx = (R[0, 1] + R[1, 0]) / S + qy = 0.25 * S + qz = (R[1, 2] + R[2, 1]) / S + else: + S = torch.sqrt(1.0 + R[2, 2] - R[0, 0] - R[1, 1]) * 2.0 + qw = (R[1, 0] - R[0, 1]) / S + qx = (R[0, 2] + R[2, 0]) / S + qy = (R[1, 2] + R[2, 1]) / S + qz = 0.25 * S + return torch.stack([qw, qx, qy, qz], dim=1) + +def rotate_quaternions(q, R): + # Convert quaternions to rotation matrices + q = torch.cat([q[:, :1], -q[:, 1:]], dim=1) + q = torch.cat([q[:, :3], q[:, 3:] * -1], dim=1) + rotated_R = torch.matmul(torch.matmul(q, R), q.inverse()) + + # Convert the rotated rotation matrices back to quaternions + return rotation_matrix_to_quaternion(rotated_R) + +# this function is borrowed from OpenLRM +class CosineWarmupScheduler(LRScheduler): + def __init__(self, optimizer, warmup_iters: int, max_iters: int, initial_lr: float = 1e-10, last_iter: int = -1): + self.warmup_iters = warmup_iters + self.max_iters = max_iters + self.initial_lr = initial_lr + super().__init__(optimizer, last_iter) + + def get_lr(self): + + if self._step_count <= self.warmup_iters: + return [ + self.initial_lr + (base_lr - self.initial_lr) * self._step_count / self.warmup_iters + for base_lr in self.base_lrs] + else: + cos_iter = self._step_count - self.warmup_iters + cos_max_iter = self.max_iters - self.warmup_iters + cos_theta = cos_iter / cos_max_iter * math.pi + cos_lr = [base_lr * (1 + math.cos(cos_theta)) / 2 for base_lr in self.base_lrs] + return cos_lr + +def vis_images(output, batch): + pass \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/Amodal3R/setup.py b/OVOW/engine/oneposeviagen/Amodal3R/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..c1c27519123047fcd10d4db8042adeae7199923c --- /dev/null +++ b/OVOW/engine/oneposeviagen/Amodal3R/setup.py @@ -0,0 +1,9 @@ +# src/fpose/setup.py +from setuptools import setup, find_packages + +setup( + name='amodal3r', + version='0.1', + package_dir={'amodal3r': 'amodal3r'}, + packages=find_packages(where='amodal3r', include=['amodal3r*']), +) \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/Amodal3R/setup.sh b/OVOW/engine/oneposeviagen/Amodal3R/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..cbf007c4380eebae431a88f6e10489d5e4516df3 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Amodal3R/setup.sh @@ -0,0 +1,260 @@ +# Read Arguments +TEMP=`getopt -o h --long help,new-env,basic,train,xformers,flash-attn,diffoctreerast,vox2seq,spconv,mipgaussian,kaolin,nvdiffrast,demo -n 'setup.sh' -- "$@"` + +eval set -- "$TEMP" + +HELP=false +NEW_ENV=false +BASIC=false +TRAIN=false +XFORMERS=false +FLASHATTN=false +DIFFOCTREERAST=false +VOX2SEQ=false +LINEAR_ASSIGNMENT=false +SPCONV=false +ERROR=false +MIPGAUSSIAN=false +KAOLIN=false +NVDIFFRAST=false +DEMO=false + +if [ "$#" -eq 1 ] ; then + HELP=true +fi + +while true ; do + case "$1" in + -h|--help) HELP=true ; shift ;; + --new-env) NEW_ENV=true ; shift ;; + --basic) BASIC=true ; shift ;; + --train) TRAIN=true ; shift ;; + --xformers) XFORMERS=true ; shift ;; + --flash-attn) FLASHATTN=true ; shift ;; + --diffoctreerast) DIFFOCTREERAST=true ; shift ;; + --vox2seq) VOX2SEQ=true ; shift ;; + --spconv) SPCONV=true ; shift ;; + --mipgaussian) MIPGAUSSIAN=true ; shift ;; + --kaolin) KAOLIN=true ; shift ;; + --nvdiffrast) NVDIFFRAST=true ; shift ;; + --demo) DEMO=true ; shift ;; + --) shift ; break ;; + *) ERROR=true ; break ;; + esac +done + +if [ "$ERROR" = true ] ; then + echo "Error: Invalid argument" + HELP=true +fi + +if [ "$HELP" = true ] ; then + echo "Usage: setup.sh [OPTIONS]" + echo "Options:" + echo " -h, --help Display this help message" + echo " --new-env Create a new conda environment" + echo " --basic Install basic dependencies" + echo " --train Install training dependencies" + echo " --xformers Install xformers" + echo " --flash-attn Install flash-attn" + echo " --diffoctreerast Install diffoctreerast" + echo " --vox2seq Install vox2seq" + echo " --spconv Install spconv" + echo " --mipgaussian Install mip-splatting" + echo " --kaolin Install kaolin" + echo " --nvdiffrast Install nvdiffrast" + echo " --demo Install all dependencies for demo" + return +fi + +if [ "$NEW_ENV" = true ] ; then + conda create -n amodal3r python=3.10 + conda activate amodal3r + conda install pytorch==2.4.0 torchvision==0.19.0 pytorch-cuda=11.8 -c pytorch -c nvidia +fi + +# Get system information +WORKDIR=$(pwd) +PYTORCH_VERSION=$(python -c "import torch; print(torch.__version__)") +PLATFORM=$(python -c "import torch; print(('cuda' if torch.version.cuda else ('hip' if torch.version.hip else 'unknown')) if torch.cuda.is_available() else 'cpu')") +case $PLATFORM in + cuda) + CUDA_VERSION=$(python -c "import torch; print(torch.version.cuda)") + CUDA_MAJOR_VERSION=$(echo $CUDA_VERSION | cut -d'.' -f1) + CUDA_MINOR_VERSION=$(echo $CUDA_VERSION | cut -d'.' -f2) + echo "[SYSTEM] PyTorch Version: $PYTORCH_VERSION, CUDA Version: $CUDA_VERSION" + ;; + hip) + HIP_VERSION=$(python -c "import torch; print(torch.version.hip)") + HIP_MAJOR_VERSION=$(echo $HIP_VERSION | cut -d'.' -f1) + HIP_MINOR_VERSION=$(echo $HIP_VERSION | cut -d'.' -f2) + # Install pytorch 2.4.1 for hip + if [ "$PYTORCH_VERSION" != "2.4.1+rocm6.1" ] ; then + echo "[SYSTEM] Installing PyTorch 2.4.1 for HIP ($PYTORCH_VERSION -> 2.4.1+rocm6.1)" + pip install torch==2.4.1 torchvision==0.19.1 --index-url https://download.pytorch.org/whl/rocm6.1 --user + mkdir -p /tmp/extensions + sudo cp /opt/rocm/share/amd_smi /tmp/extensions/amd_smi -r + cd /tmp/extensions/amd_smi + sudo chmod -R 777 . + pip install . + cd $WORKDIR + PYTORCH_VERSION=$(python -c "import torch; print(torch.__version__)") + fi + echo "[SYSTEM] PyTorch Version: $PYTORCH_VERSION, HIP Version: $HIP_VERSION" + ;; + *) + ;; +esac + +if [ "$BASIC" = true ] ; then + pip install pillow imageio imageio-ffmpeg tqdm easydict opencv-python-headless scipy ninja rembg onnxruntime trimesh open3d xatlas pyvista pymeshfix igraph transformers + pip install git+https://github.com/EasternJournalist/utils3d.git@9a4eb15e4021b67b12c460c7057d642626897ec8 +fi + +if [ "$TRAIN" = true ] ; then + pip install tensorboard pandas lpips + pip uninstall -y pillow + sudo apt install -y libjpeg-dev + pip install pillow-simd +fi + +if [ "$XFORMERS" = true ] ; then + # install xformers + if [ "$PLATFORM" = "cuda" ] ; then + if [ "$CUDA_VERSION" = "11.8" ] ; then + case $PYTORCH_VERSION in + 2.0.1) pip install https://files.pythonhosted.org/packages/52/ca/82aeee5dcc24a3429ff5de65cc58ae9695f90f49fbba71755e7fab69a706/xformers-0.0.22-cp310-cp310-manylinux2014_x86_64.whl ;; + 2.1.0) pip install xformers==0.0.22.post7 --index-url https://download.pytorch.org/whl/cu118 ;; + 2.1.1) pip install xformers==0.0.23 --index-url https://download.pytorch.org/whl/cu118 ;; + 2.1.2) pip install xformers==0.0.23.post1 --index-url https://download.pytorch.org/whl/cu118 ;; + 2.2.0) pip install xformers==0.0.24 --index-url https://download.pytorch.org/whl/cu118 ;; + 2.2.1) pip install xformers==0.0.25 --index-url https://download.pytorch.org/whl/cu118 ;; + 2.2.2) pip install xformers==0.0.25.post1 --index-url https://download.pytorch.org/whl/cu118 ;; + 2.3.0) pip install xformers==0.0.26.post1 --index-url https://download.pytorch.org/whl/cu118 ;; + 2.4.0) pip install xformers==0.0.27.post2 --index-url https://download.pytorch.org/whl/cu118 ;; + 2.4.1) pip install xformers==0.0.28 --index-url https://download.pytorch.org/whl/cu118 ;; + 2.5.0) pip install xformers==0.0.28.post2 --index-url https://download.pytorch.org/whl/cu118 ;; + *) echo "[XFORMERS] Unsupported PyTorch & CUDA version: $PYTORCH_VERSION & $CUDA_VERSION" ;; + esac + elif [ "$CUDA_VERSION" = "12.1" ] ; then + case $PYTORCH_VERSION in + 2.1.0) pip install xformers==0.0.22.post7 --index-url https://download.pytorch.org/whl/cu121 ;; + 2.1.1) pip install xformers==0.0.23 --index-url https://download.pytorch.org/whl/cu121 ;; + 2.1.2) pip install xformers==0.0.23.post1 --index-url https://download.pytorch.org/whl/cu121 ;; + 2.2.0) pip install xformers==0.0.24 --index-url https://download.pytorch.org/whl/cu121 ;; + 2.2.1) pip install xformers==0.0.25 --index-url https://download.pytorch.org/whl/cu121 ;; + 2.2.2) pip install xformers==0.0.25.post1 --index-url https://download.pytorch.org/whl/cu121 ;; + 2.3.0) pip install xformers==0.0.26.post1 --index-url https://download.pytorch.org/whl/cu121 ;; + 2.4.0) pip install xformers==0.0.27.post2 --index-url https://download.pytorch.org/whl/cu121 ;; + 2.4.1) pip install xformers==0.0.28 --index-url https://download.pytorch.org/whl/cu121 ;; + 2.5.0) pip install xformers==0.0.28.post2 --index-url https://download.pytorch.org/whl/cu121 ;; + *) echo "[XFORMERS] Unsupported PyTorch & CUDA version: $PYTORCH_VERSION & $CUDA_VERSION" ;; + esac + elif [ "$CUDA_VERSION" = "12.4" ] ; then + case $PYTORCH_VERSION in + 2.5.0) pip install xformers==0.0.28.post2 --index-url https://download.pytorch.org/whl/cu124 ;; + *) echo "[XFORMERS] Unsupported PyTorch & CUDA version: $PYTORCH_VERSION & $CUDA_VERSION" ;; + esac + else + echo "[XFORMERS] Unsupported CUDA version: $CUDA_MAJOR_VERSION" + fi + elif [ "$PLATFORM" = "hip" ] ; then + case $PYTORCH_VERSION in + 2.4.1\+rocm6.1) pip install xformers==0.0.28 --index-url https://download.pytorch.org/whl/rocm6.1 ;; + *) echo "[XFORMERS] Unsupported PyTorch version: $PYTORCH_VERSION" ;; + esac + else + echo "[XFORMERS] Unsupported platform: $PLATFORM" + fi +fi + +if [ "$FLASHATTN" = true ] ; then + if [ "$PLATFORM" = "cuda" ] ; then + pip install flash-attn + elif [ "$PLATFORM" = "hip" ] ; then + echo "[FLASHATTN] Prebuilt binaries not found. Building from source..." + mkdir -p /tmp/extensions + git clone --recursive https://github.com/ROCm/flash-attention.git /tmp/extensions/flash-attention + cd /tmp/extensions/flash-attention + git checkout tags/v2.6.3-cktile + GPU_ARCHS=gfx942 python setup.py install #MI300 series + cd $WORKDIR + else + echo "[FLASHATTN] Unsupported platform: $PLATFORM" + fi +fi + +if [ "$KAOLIN" = true ] ; then + # install kaolin + if [ "$PLATFORM" = "cuda" ] ; then + case $PYTORCH_VERSION in + 2.0.1) pip install kaolin -f https://nvidia-kaolin.s3.us-east-2.amazonaws.com/torch-2.0.1_cu118.html;; + 2.1.0) pip install kaolin -f https://nvidia-kaolin.s3.us-east-2.amazonaws.com/torch-2.1.0_cu118.html;; + 2.1.1) pip install kaolin -f https://nvidia-kaolin.s3.us-east-2.amazonaws.com/torch-2.1.1_cu118.html;; + 2.2.0) pip install kaolin -f https://nvidia-kaolin.s3.us-east-2.amazonaws.com/torch-2.2.0_cu118.html;; + 2.2.1) pip install kaolin -f https://nvidia-kaolin.s3.us-east-2.amazonaws.com/torch-2.2.1_cu118.html;; + 2.2.2) pip install kaolin -f https://nvidia-kaolin.s3.us-east-2.amazonaws.com/torch-2.2.2_cu118.html;; + 2.4.0) pip install kaolin -f https://nvidia-kaolin.s3.us-east-2.amazonaws.com/torch-2.4.0_cu121.html;; + *) echo "[KAOLIN] Unsupported PyTorch version: $PYTORCH_VERSION" ;; + esac + else + echo "[KAOLIN] Unsupported platform: $PLATFORM" + fi +fi + +if [ "$NVDIFFRAST" = true ] ; then + if [ "$PLATFORM" = "cuda" ] ; then + mkdir -p /tmp/extensions + git clone https://github.com/NVlabs/nvdiffrast.git /tmp/extensions/nvdiffrast + pip install /tmp/extensions/nvdiffrast + else + echo "[NVDIFFRAST] Unsupported platform: $PLATFORM" + fi +fi + +if [ "$DIFFOCTREERAST" = true ] ; then + if [ "$PLATFORM" = "cuda" ] ; then + mkdir -p /tmp/extensions + git clone --recurse-submodules https://github.com/JeffreyXiang/diffoctreerast.git /tmp/extensions/diffoctreerast + pip install /tmp/extensions/diffoctreerast + else + echo "[DIFFOCTREERAST] Unsupported platform: $PLATFORM" + fi +fi + +if [ "$MIPGAUSSIAN" = true ] ; then + if [ "$PLATFORM" = "cuda" ] ; then + mkdir -p /tmp/extensions + git clone https://github.com/autonomousvision/mip-splatting.git /tmp/extensions/mip-splatting + pip install /tmp/extensions/mip-splatting/submodules/diff-gaussian-rasterization/ + else + echo "[MIPGAUSSIAN] Unsupported platform: $PLATFORM" + fi +fi + +if [ "$VOX2SEQ" = true ] ; then + if [ "$PLATFORM" = "cuda" ] ; then + mkdir -p /tmp/extensions + cp -r extensions/vox2seq /tmp/extensions/vox2seq + pip install /tmp/extensions/vox2seq + else + echo "[VOX2SEQ] Unsupported platform: $PLATFORM" + fi +fi + +if [ "$SPCONV" = true ] ; then + # install spconv + if [ "$PLATFORM" = "cuda" ] ; then + case $CUDA_MAJOR_VERSION in + 11) pip install spconv-cu118 ;; + 12) pip install spconv-cu120 ;; + *) echo "[SPCONV] Unsupported PyTorch CUDA version: $CUDA_MAJOR_VERSION" ;; + esac + else + echo "[SPCONV] Unsupported platform: $PLATFORM" + fi +fi + +if [ "$DEMO" = true ] ; then + pip install gradio==4.44.1 gradio_litmodel3d==0.0.1 +fi diff --git a/OVOW/engine/oneposeviagen/Amodal3R/train_lightning.py b/OVOW/engine/oneposeviagen/Amodal3R/train_lightning.py new file mode 100644 index 0000000000000000000000000000000000000000..43bb0745a6de53e10b107732ed57d3536f4d8f0c --- /dev/null +++ b/OVOW/engine/oneposeviagen/Amodal3R/train_lightning.py @@ -0,0 +1,128 @@ +import os + +n_thread = 2 +os.environ["MKL_NUM_THREADS"] = f"{n_thread}" +os.environ["NUMEXPR_NUM_THREADS"] = f"{n_thread}" +os.environ["OMP_NUM_THREADS"] = f"4" +os.environ["VECLIB_MAXIMUM_THREADS"] = f"{n_thread}" +os.environ["OPENBLAS_NUM_THREADS"] = f"{n_thread}" + + +import torch +from dataLoader import dataset_dict +from omegaconf import OmegaConf + +# from lightning.system_vae import system +from lightning.system import system +from torch.utils.data import DataLoader +import pytorch_lightning as L + +from datetime import datetime + + +from pytorch_lightning.loggers import TensorBoardLogger +from pytorch_lightning.loggers import WandbLogger +from pytorch_lightning.callbacks import ModelCheckpoint +from pytorch_lightning.strategies import DDPStrategy + +from argparse import ArgumentParser +import sys + +def check_weights_dtype(weights): + for key, value in weights.items(): + print(f"{key}: {value.dtype}") + +def main(cfg, ckpt, cfg_path): + + torch.set_float32_matmul_precision('medium') + torch.autograd.set_detect_anomaly(True) + print("Using PyTorch {} and Lightning {}".format(torch.__version__, L.__version__)) + + # data loader + train_dataset = dataset_dict[cfg.train_dataset.dataset_name] + train_loader = DataLoader(train_dataset(cfg.train_dataset), + batch_size= cfg.train.batch_size, + num_workers= 8, + shuffle=True, + pin_memory=False) + val_dataset = dataset_dict[cfg.test_dataset.dataset_name] + val_loader = DataLoader(val_dataset(cfg.test_dataset), + batch_size=cfg.test.batch_size, + num_workers=2, + shuffle=True, + pin_memory=False) + + # build logger + project_name = cfg.exp_name.split("/")[0] + exp_name = cfg.exp_name.split("/")[1] + + if cfg.logger.name == "tensorboard": + logger = TensorBoardLogger(save_dir=cfg.logger.dir, name=exp_name) + elif cfg.logger.name == "wandb": + os.environ["WANDB__SERVICE_WAIT"] = "300" + logger = WandbLogger(name=exp_name,project=project_name, save_dir=cfg.logger.dir, entity="large-reconstruction-model") + + # Set up ModelCheckpoint callback + checkpoint_callback = ModelCheckpoint( + dirpath=cfg.vis_dir, # Path where checkpoints will be saved + filename='{epoch}', # Filename for the checkpoints + # save_top_k=1, # Set to -1 to save all checkpoints + every_n_epochs=5, # Save a checkpoint every K epochs + save_on_train_epoch_end=True, # Ensure it saves at the end of an epoch, not the beginning + ) + + print(cfg.vis_dir) + my_system = system(cfg, cfg_path) + max_epoch = cfg.train.n_epoch + + + trainer = L.Trainer(devices=cfg.gpu_id, + num_nodes=1, + max_epochs=max_epoch, + accelerator='gpu', + strategy=DDPStrategy(find_unused_parameters=True), + accumulate_grad_batches=8, + logger=logger, + precision="16-mixed", + callbacks=[checkpoint_callback], + check_val_every_n_epoch=cfg.train.check_val_every_n_epoch, + limit_val_batches=cfg.train.limit_val_batches, # Run on only 10% of the validation data + limit_train_batches=cfg.train.limit_train_batches, + ) + + + t0 = datetime.now() + trainer.fit( + my_system, + train_dataloaders=train_loader, + val_dataloaders=val_loader, + ckpt_path=ckpt + ) + + dt = datetime.now() - t0 + print('Training took {}'.format(dt)) + + +if __name__ == '__main__': + + parser = ArgumentParser(description="Training script parameters") + parser.add_argument("--config", type=str, default = "./configs/base.yaml") + parser.add_argument("--ckpt", type=str, default = None) + parser.add_argument("--vis_dir", type=str, default = None) + parser.add_argument("--strict", action="store_true") + args = parser.parse_args(sys.argv[1:]) + + base_conf = OmegaConf.load(args.config) + + cli_conf = OmegaConf.from_cli() + cfg = OmegaConf.merge(base_conf, cli_conf) + + if args.vis_dir is not None: + cfg.vis_dir = args.vis_dir + + if args.strict: + cfg.strict = True + else: + cfg.strict = False + + main(cfg, args.ckpt, args.config) \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/Amodal3R/train_slat.sh b/OVOW/engine/oneposeviagen/Amodal3R/train_slat.sh new file mode 100644 index 0000000000000000000000000000000000000000..ec2f27775fce158a699a0556a5d1f062745c21d5 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Amodal3R/train_slat.sh @@ -0,0 +1,3 @@ +torchrun --rdzv_endpoint=localhost:29500 --nproc_per_node=4 train_lightning.py \ +--config ./configs/slat.yaml \ +--vis ./train_slat diff --git a/OVOW/engine/oneposeviagen/Amodal3R/train_ss.sh b/OVOW/engine/oneposeviagen/Amodal3R/train_ss.sh new file mode 100644 index 0000000000000000000000000000000000000000..044d5e6377aa4a7a53d563318f8164980a99512a --- /dev/null +++ b/OVOW/engine/oneposeviagen/Amodal3R/train_ss.sh @@ -0,0 +1,3 @@ +torchrun --rdzv_endpoint=localhost:29500 --nproc_per_node=4 train_lightning.py \ +--config ./configs/ss.yaml \ +--vis ./train_sparse_strcuture diff --git a/OVOW/engine/oneposeviagen/DA3/.flake8 b/OVOW/engine/oneposeviagen/DA3/.flake8 new file mode 100644 index 0000000000000000000000000000000000000000..57d083009957dd371fb67cee54b80d356b10fe7e --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/.flake8 @@ -0,0 +1,3 @@ +[flake8] +max-line-length = 100 +ignore = E203 E741 W503 E731 diff --git a/OVOW/engine/oneposeviagen/DA3/.gitattributes b/OVOW/engine/oneposeviagen/DA3/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/OVOW/engine/oneposeviagen/DA3/.gitignore b/OVOW/engine/oneposeviagen/DA3/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..9c500c8613a9424f31507b4569dbfe0afa29849e --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/.gitignore @@ -0,0 +1,35 @@ +# Python cache +__pycache__/ +*.py[cod] + +# Distribution / packaging +workspace/ +build/ +dist/ +*.egg-info/ +.gradio/ + +# Test/coverage +.coverage +.pytest_cache/ +htmlcov/ +.tox/ +gallery*/ +debug*/ +DA3HF*/ +gradio_workspace/ +eval_workspace/ +FILTER*/ +input_images*/ +*.gradio/ + +# Jupyter notebooks +.ipynb_checkpoints + +# OS files +.DS_Store + +.vscode +src/debug_main.py +temp*.png +/outputs diff --git a/OVOW/engine/oneposeviagen/DA3/.pre-commit-config.yaml b/OVOW/engine/oneposeviagen/DA3/.pre-commit-config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3d9935935aee777bc71316f2e999759f8e612df2 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/.pre-commit-config.yaml @@ -0,0 +1,59 @@ +repos: + - repo: 'https://github.com/pre-commit/pre-commit-hooks' + rev: v4.5.0 + hooks: + - id: check-added-large-files + args: + - '--maxkb=125' + - id: check-ast + - id: check-executables-have-shebangs + - id: check-merge-conflict + - id: check-symlinks + - id: check-toml + - id: check-yaml + - id: debug-statements + - id: detect-private-key + - id: end-of-file-fixer + - id: no-commit-to-branch + args: + - '--branch' + - 'master' + - id: pretty-format-json + exclude: '.*\.ipynb$' + args: + - '--autofix' + - '--indent' + - '4' + - id: trailing-whitespace + args: + - '--markdown-linebreak-ext=md' + - repo: 'https://github.com/pycqa/isort' + rev: 5.13.2 + hooks: + - id: isort + args: + - '--settings-file' + - 'pyproject.toml' + - '--filter-files' + - repo: 'https://github.com/asottile/pyupgrade' + rev: v3.15.2 + hooks: + - id: pyupgrade + args: [--py38-plus, --keep-runtime-typing] + - repo: 'https://github.com/psf/black.git' + rev: 24.3.0 + hooks: + - id: black + args: + - '--config=pyproject.toml' + - repo: 'https://github.com/PyCQA/flake8' + rev: 7.0.0 + hooks: + - id: flake8 + args: + - '--config=.flake8' + - repo: 'https://github.com/myint/autoflake' + rev: v1.4 + hooks: + - id: autoflake + args: [ '--remove-all-unused-imports', '--recursive', '--remove-unused-variables', '--in-place'] diff --git a/OVOW/engine/oneposeviagen/DA3/LICENSE b/OVOW/engine/oneposeviagen/DA3/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..a2fa36578f5094f56f4b0ec57e70eb30aced4519 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on + the same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2025 The Depth Anything 3 Team + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/OVOW/engine/oneposeviagen/DA3/README.md b/OVOW/engine/oneposeviagen/DA3/README.md new file mode 100644 index 0000000000000000000000000000000000000000..647a451d7a7b7cd536c4b8cf3e383489892c7b0c --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/README.md @@ -0,0 +1,273 @@ +
+

Depth Anything 3: Recovering the Visual Space from Any Views

+ + + +[**Haotong Lin**](https://haotongl.github.io/)* · [**Sili Chen**](https://github.com/SiliChen321)* · [**Jun Hao Liew**](https://liewjunhao.github.io/)* · [**Donny Y. Chen**](https://donydchen.github.io)* · [**Zhenyu Li**](https://zhyever.github.io/) · [**Guang Shi**](https://scholar.google.com/citations?user=MjXxWbUAAAAJ&hl=en) · [**Jiashi Feng**](https://scholar.google.com.sg/citations?user=Q8iay0gAAAAJ&hl=en) +
+[**Bingyi Kang**](https://bingykang.github.io/)*† + +†project lead *Equal Contribution + +Paper PDF +Project Page + + + + +
+ +This work presents **Depth Anything 3 (DA3)**, a model that predicts spatially consistent geometry from +arbitrary visual inputs, with or without known camera poses. +In pursuit of minimal modeling, DA3 yields two key insights: +- 💎 A **single plain transformer** (e.g., vanilla DINO encoder) is sufficient as a backbone without architectural specialization, +- ✨ A singular **depth-ray representation** obviates the need for complex multi-task learning. + +🏆 DA3 significantly outperforms +[DA2](https://github.com/DepthAnything/Depth-Anything-V2) for monocular depth estimation, +and [VGGT](https://github.com/facebookresearch/vggt) for multi-view depth estimation and pose estimation. +All models are trained exclusively on **public academic datasets**. + + +

+ Depth Anything 3 - Left +

+

+ Depth Anything 3 +

+ + +## 📰 News +- **08-12-2025:** 📊 [Benchmark evaluation pipeline](docs/BENCHMARK.md) released! Evaluate pose estimation & 3D reconstruction on 5 datasets. +- **30-11-2025:** Add [`use_ray_pose`](#use-ray-pose) and [`ref_view_strategy`](docs/funcs/ref_view_strategy.md) (reference view selection for multi-view inputs). +- **25-11-2025:** Add [Awesome DA3 Projects](#-awesome-da3-projects), a community-driven section featuring DA3-based applications. +- **14-11-2025:** Paper, project page, code and models are all released. + +## ✨ Highlights + +### 🏆 Model Zoo +We release three series of models, each tailored for specific use cases in visual geometry. + +- 🌟 **DA3 Main Series** (`DA3-Giant`, `DA3-Large`, `DA3-Base`, `DA3-Small`) These are our flagship foundation models, trained with a unified depth-ray representation. By varying the input configuration, a single model can perform a wide range of tasks: + + 🌊 **Monocular Depth Estimation**: Predicts a depth map from a single RGB image. + + 🌊 **Multi-View Depth Estimation**: Generates consistent depth maps from multiple images for high-quality fusion. + + 🎯 **Pose-Conditioned Depth Estimation**: Achieves superior depth consistency when camera poses are provided as input. + + 📷 **Camera Pose Estimation**: Estimates camera extrinsics and intrinsics from one or more images. + + 🟡 **3D Gaussian Estimation**: Directly predicts 3D Gaussians, enabling high-fidelity novel view synthesis. + +- 📐 **DA3 Metric Series** (`DA3Metric-Large`) A specialized model fine-tuned for metric depth estimation in monocular settings, ideal for applications requiring real-world scale. + +- 🔍 **DA3 Monocular Series** (`DA3Mono-Large`). A dedicated model for high-quality relative monocular depth estimation. Unlike disparity-based models (e.g., [Depth Anything 2](https://github.com/DepthAnything/Depth-Anything-V2)), it directly predicts depth, resulting in superior geometric accuracy. + +🔗 Leveraging these available models, we developed a **nested series** (`DA3Nested-Giant-Large`). This series combines a any-view giant model with a metric model to reconstruct visual geometry at a real-world metric scale. + +### 🛠️ Codebase Features +Our repository is designed to be a powerful and user-friendly toolkit for both practical application and future research. +- 🎨 **Interactive Web UI & Gallery**: Visualize model outputs and compare results with an easy-to-use Gradio-based web interface. +- ⚡ **Flexible Command-Line Interface (CLI)**: Powerful and scriptable CLI for batch processing and integration into custom workflows. +- 💾 **Multiple Export Formats**: Save your results in various formats, including `glb`, `npz`, depth images, `ply`, 3DGS videos, etc, to seamlessly connect with other tools. +- 🔧 **Extensible and Modular Design**: The codebase is structured to facilitate future research and the integration of new models or functionalities. + + + + + +## 🚀 Quick Start + +### 📦 Installation + +```bash +pip install xformers torch\>=2 torchvision +pip install -e . # Basic +pip install --no-build-isolation git+https://github.com/nerfstudio-project/gsplat.git@0b4dddf04cb687367602c01196913cde6a743d70 # for gaussian head +pip install -e ".[app]" # Gradio, python>=3.10 +pip install -e ".[all]" # ALL +``` + +For detailed model information, please refer to the [Model Cards](#-model-cards) section below. + +### 💻 Basic Usage + +```python +import glob, os, torch +from depth_anything_3.api import DepthAnything3 +device = torch.device("cuda") +model = DepthAnything3.from_pretrained("depth-anything/DA3NESTED-GIANT-LARGE") +model = model.to(device=device) +example_path = "assets/examples/SOH" +images = sorted(glob.glob(os.path.join(example_path, "*.png"))) +prediction = model.inference( + images, +) +# prediction.processed_images : [N, H, W, 3] uint8 array +print(prediction.processed_images.shape) +# prediction.depth : [N, H, W] float32 array +print(prediction.depth.shape) +# prediction.conf : [N, H, W] float32 array +print(prediction.conf.shape) +# prediction.extrinsics : [N, 3, 4] float32 array # opencv w2c or colmap format +print(prediction.extrinsics.shape) +# prediction.intrinsics : [N, 3, 3] float32 array +print(prediction.intrinsics.shape) +``` + +```bash + +export MODEL_DIR=depth-anything/DA3NESTED-GIANT-LARGE +# This can be a Hugging Face repository or a local directory +# If you encounter network issues, consider using the following mirror: export HF_ENDPOINT=https://hf-mirror.com +# Alternatively, you can download the model directly from Hugging Face +export GALLERY_DIR=workspace/gallery +mkdir -p $GALLERY_DIR + +# CLI auto mode with backend reuse +da3 backend --model-dir ${MODEL_DIR} --gallery-dir ${GALLERY_DIR} # Cache model to gpu +da3 auto assets/examples/SOH \ + --export-format glb \ + --export-dir ${GALLERY_DIR}/TEST_BACKEND/SOH \ + --use-backend + +# CLI video processing with feature visualization +da3 video assets/examples/robot_unitree.mp4 \ + --fps 15 \ + --use-backend \ + --export-dir ${GALLERY_DIR}/TEST_BACKEND/robo \ + --export-format glb-feat_vis \ + --feat-vis-fps 15 \ + --process-res-method lower_bound_resize \ + --export-feat "11,21,31" + +# CLI auto mode without backend reuse +da3 auto assets/examples/SOH \ + --export-format glb \ + --export-dir ${GALLERY_DIR}/TEST_CLI/SOH \ + --model-dir ${MODEL_DIR} + +``` + +The model architecture is defined in [`DepthAnything3Net`](src/depth_anything_3/model/da3.py), and specified with a Yaml config file located at [`src/depth_anything_3/configs`](src/depth_anything_3/configs). The input and output processing are handled by [`DepthAnything3`](src/depth_anything_3/api.py). To customize the model architecture, simply create a new config file (*e.g.*, `path/to/new/config`) as: + +```yaml +__object__: + path: depth_anything_3.model.da3 + name: DepthAnything3Net + args: as_params + +net: + __object__: + path: depth_anything_3.model.dinov2.dinov2 + name: DinoV2 + args: as_params + + name: vitb + out_layers: [5, 7, 9, 11] + alt_start: 4 + qknorm_start: 4 + rope_start: 4 + cat_token: True + +head: + __object__: + path: depth_anything_3.model.dualdpt + name: DualDPT + args: as_params + + dim_in: &head_dim_in 1536 + output_dim: 2 + features: &head_features 128 + out_channels: &head_out_channels [96, 192, 384, 768] +``` + +Then, the model can be created with the following code snippet. +```python +from depth_anything_3.cfg import create_object, load_config + +Model = create_object(load_config("path/to/new/config")) +``` + + + +## 📚 Useful Documentation + +- 🖥️ [Command Line Interface](docs/CLI.md) +- 📑 [Python API](docs/API.md) +- 📊 [Benchmark Evaluation](docs/BENCHMARK.md) + +## 🗂️ Model Cards + +Generally, you should observe that DA3-LARGE achieves comparable results to VGGT. + +The Nested series uses an Any-view model to estimate pose and depth, and a monocular metric depth estimator for scaling. + +| 🗃️ Model Name | 📏 Params | 📊 Rel. Depth | 📷 Pose Est. | 🧭 Pose Cond. | 🎨 GS | 📐 Met. Depth | ☁️ Sky Seg | 📄 License | +|-------------------------------|-----------|---------------|--------------|---------------|-------|---------------|-----------|----------------| +| **Nested** | | | | | | | | | +| [DA3NESTED-GIANT-LARGE](https://huggingface.co/depth-anything/DA3NESTED-GIANT-LARGE) | 1.40B | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | CC BY-NC 4.0 | +| **Any-view Model** | | | | | | | | | +| [DA3-GIANT](https://huggingface.co/depth-anything/DA3-GIANT) | 1.15B | ✅ | ✅ | ✅ | ✅ | | | CC BY-NC 4.0 | +| [DA3-LARGE](https://huggingface.co/depth-anything/DA3-LARGE) | 0.35B | ✅ | ✅ | ✅ | | | | CC BY-NC 4.0 | +| [DA3-BASE](https://huggingface.co/depth-anything/DA3-BASE) | 0.12B | ✅ | ✅ | ✅ | | | | Apache 2.0 | +| [DA3-SMALL](https://huggingface.co/depth-anything/DA3-SMALL) | 0.08B | ✅ | ✅ | ✅ | | | | Apache 2.0 | +| | | | | | | | | | +| **Monocular Metric Depth** | | | | | | | | | +| [DA3METRIC-LARGE](https://huggingface.co/depth-anything/DA3METRIC-LARGE) | 0.35B | ✅ | | | | ✅ | ✅ | Apache 2.0 | +| | | | | | | | | | +| **Monocular Depth** | | | | | | | | | +| [DA3MONO-LARGE](https://huggingface.co/depth-anything/DA3MONO-LARGE) | 0.35B | ✅ | | | | | ✅ | Apache 2.0 | + + +## ❓ FAQ + +- **Monocular Metric Depth**: To obtain metric depth in meters from `DA3METRIC-LARGE`, use `metric_depth = focal * net_output / 300.`, where `focal` is the focal length in pixels (typically the average of fx and fy from the camera intrinsic matrix K). Note that the output from `DA3NESTED-GIANT-LARGE` is already in meters. + +- **Ray Head (`use_ray_pose`)**: Our API and CLI support `use_ray_pose` arg, which means that the model will derive camera pose from ray head, which is generally slightly slower, but more accurate. Note that the default is `False` for faster inference speed. +
+ AUC3 Results for DA3NESTED-GIANT-LARGE + + | Model | HiRoom | ETH3D | DTU | 7Scenes | ScanNet++ | + |-------|------|-------|-----|---------|-----------| + | `ray_head` | 84.4 | 52.6 | 93.9 | 29.5 | 89.4 | + | `cam_head` | 80.3 | 48.4 | 94.1 | 28.5 | 85.0 | + +
+ + + + +- **Older GPUs without XFormers support**: See [Issue #11](https://github.com/ByteDance-Seed/Depth-Anything-3/issues/11). Thanks to [@S-Mahoney](https://github.com/S-Mahoney) for the solution! + + +## 🏢 Awesome DA3 Projects + +A community-curated list of Depth Anything 3 integrations across 3D tools, creative pipelines, robotics, and web/VR viewers, including but not limited to these. You are welcome to submit your DA3-based project via PR, and we will review and feature it if applicable. + +- [DA3-blender](https://github.com/xy-gao/DA3-blender): Blender addon for DA3-based 3D reconstruction from a set of images. + +- [ComfyUI-DepthAnythingV3](https://github.com/PozzettiAndrea/ComfyUI-DepthAnythingV3): ComfyUI nodes for Depth Anything 3, supporting single/multi-view and video-consistent depth with optional point‑cloud export. + +- [DA3-ROS2-Wrapper](https://github.com/GerdsenAI/GerdsenAI-Depth-Anything-3-ROS2-Wrapper): Real-time DA3 depth in ROS2 with multi-camera support. + +- [DA3-ROS2-CPP-TensorRT](https://github.com/ika-rwth-aachen/ros2-depth-anything-v3-trt): DA3 ROS2 C++ TensorRT Inference Node: a ROS2 node for DA3 depth estimation using TensorRT for real-time inference. + +- [VideoDepthViewer3D](https://github.com/amariichi/VideoDepthViewer3D): Streaming videos with DA3 metric depth to a Three.js/WebXR 3D viewer for VR/stereo playback. + + +## 📝 Citations +If you find Depth Anything 3 useful in your research or projects, please cite our work: + +``` +@article{depthanything3, + title={Depth Anything 3: Recovering the visual space from any views}, + author={Haotong Lin and Sili Chen and Jun Hao Liew and Donny Y. Chen and Zhenyu Li and Guang Shi and Jiashi Feng and Bingyi Kang}, + journal={arXiv preprint arXiv:2511.10647}, + year={2025} +} +``` diff --git a/OVOW/engine/oneposeviagen/DA3/docs/API.md b/OVOW/engine/oneposeviagen/DA3/docs/API.md new file mode 100644 index 0000000000000000000000000000000000000000..89a9de362ce260b37cc86c6345974ef372ad9db9 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/docs/API.md @@ -0,0 +1,465 @@ +# 📚 DepthAnything3 API Documentation + +## 📑 Table of Contents + +1. [📖 Overview](#overview) +2. [💡 Usage Examples](#usage-examples) +3. [🔧 Core API](#core-api) + - [DepthAnything3 Class](#depthanything3-class) + - [inference() Method](#inference-method) +4. [⚙️ Parameters](#parameters) + - [Input Parameters](#input-parameters) + - [Pose Alignment Parameters](#pose-alignment-parameters) + - [Feature Export Parameters](#feature-export-parameters) + - [Rendering Parameters](#rendering-parameters) + - [Processing Parameters](#processing-parameters) + - [Export Parameters](#export-parameters) +5. [📤 Export Formats](#export-formats) +6. [↩️ Return Value](#return-value) + +## 📖 Overview + +This documentation provides comprehensive API reference for DepthAnything3, including usage examples, parameter specifications, export formats, and advanced features. It covers both basic pose and depth estimation workflows and advanced pose-conditioned processing with multiple export capabilities. + +## 💡 Usage Examples + +Here are quick examples to get you started: + +### 🚀 Basic Depth Estimation +```python +from depth_anything_3.api import DepthAnything3 + +# Initialize and run inference +model = DepthAnything3.from_pretrained("depth-anything/DA3NESTED-GIANT-LARGE").to("cuda") +prediction = model.inference(["image1.jpg", "image2.jpg"]) +``` + +### 📷 Pose-Conditioned Depth Estimation +```python +import numpy as np + +# With camera parameters for better consistency +prediction = model.inference( + image=["image1.jpg", "image2.jpg"], + extrinsics=extrinsics_array, # (N, 4, 4) + intrinsics=intrinsics_array # (N, 3, 3) +) +``` + +### 📤 Export Results +```python +# Export depth data and 3D visualization +prediction = model.inference( + image=image_paths, + export_dir="./output", + export_format="mini_npz-glb" +) +``` + +### 🔍 Feature Extraction +```python +# Export intermediate features from specific layers +prediction = model.inference( + image=image_paths, + export_dir="./output", + export_format="feat_vis", + export_feat_layers=[0, 1, 2] # Export features from layers 0, 1, 2 +) +``` + +### ✨ Advanced Export with Gaussian Splatting +```python +# Export multiple formats including Gaussian Splatting +# Note: infer_gs=True requires da3-giant or da3nested-giant-large model +model = DepthAnything3(model_name="da3-giant").to("cuda") + +prediction = model.inference( + image=image_paths, + extrinsics=extrinsics_array, + intrinsics=intrinsics_array, + export_dir="./output", + export_format="npz-glb-gs_ply-gs_video", + align_to_input_ext_scale=True, + infer_gs=True, # Required for gs_ply and gs_video exports +) +``` + +### 🎨 Advanced Export with Feature Visualization +```python +# Export with intermediate feature visualization +prediction = model.inference( + image=image_paths, + export_dir="./output", + export_format="mini_npz-glb-depth_vis-feat_vis", + export_feat_layers=[0, 5, 10, 15, 20], + feat_vis_fps=30, +) +``` + +### 📐 Using Ray-Based Pose Estimation +```python +# Use ray-based pose estimation instead of camera decoder +prediction = model.inference( + image=image_paths, + export_dir="./output", + export_format="glb", + use_ray_pose=True, # Enable ray-based pose estimation +) +``` + +### 🎯 Reference View Selection +```python +# For multi-view inputs, automatically select the best reference view +prediction = model.inference( + image=image_paths, + ref_view_strategy="saddle_balanced", # Default: balanced selection +) + +# For video sequences, use middle frame as reference +prediction = model.inference( + image=video_frames, + ref_view_strategy="middle", # Good for temporally ordered inputs +) +``` + +## 🔧 Core API + +### 🔨 DepthAnything3 Class + +The main API class that provides depth estimation capabilities with optional pose conditioning. + +#### 🎯 Initialization + +```python +from depth_anything_3 import DepthAnything3 + +# Initialize the model with a model name +model = DepthAnything3(model_name="da3-large") +model = model.to("cuda") # Move to GPU +``` + +**Parameters:** +- `model_name` (str, default: "da3-large"): The name of the model preset to use. + - **Available models:** + - 🦾 `"da3-giant"` - 1.15B params, any-view model with GS support + - ⭐ `"da3-large"` - 0.35B params, any-view model (recommended for most use cases) + - 📦 `"da3-base"` - 0.12B params, any-view model + - 🪶 `"da3-small"` - 0.08B params, any-view model + - 👁️ `"da3mono-large"` - 0.35B params, monocular depth only + - 📏 `"da3metric-large"` - 0.35B params, metric depth with sky segmentation + - 🎯 `"da3nested-giant-large"` - 1.40B params, nested model with all features + +### 🚀 inference() Method + +The primary inference method that processes images and returns depth predictions. + +```python +prediction = model.inference( + image=image_list, + extrinsics=extrinsics_array, # Optional + intrinsics=intrinsics_array, # Optional + align_to_input_ext_scale=True, # Whether to align predicted poses to input scale + infer_gs=True, # Enable Gaussian branch for gs exports + use_ray_pose=False, # Use ray-based pose estimation instead of camera decoder + ref_view_strategy="saddle_balanced", # Reference view selection strategy + render_exts=render_extrinsics, # Optional renders for gs_video + render_ixts=render_intrinsics, # Optional renders for gs_video + render_hw=(height, width), # Optional renders for gs_video + process_res=504, + process_res_method="upper_bound_resize", + export_dir="output_directory", # Optional + export_format="mini_npz", + export_feat_layers=[], # List of layer indices to export features from + conf_thresh_percentile=40.0, # Confidence threshold percentile for depth map in GLB export + num_max_points=1_000_000, # Maximum number of points to export in GLB export + show_cameras=True, # Whether to show cameras in GLB export + feat_vis_fps=15, # Frames per second for feature visualization in feat_vis export + export_kwargs={} # Optional, additional arguments to export functions. export_format:key:val, see 'Parameters/Export Parameters' for details +) +``` + +## ⚙️ Parameters + +### 📸 Input Parameters + +#### `image` (required) +- **Type**: `List[Union[np.ndarray, Image.Image, str]]` +- **Description**: List of input images. Can be numpy arrays, PIL Images, or file paths. +- **Example**: + ```python + # From file paths + image = ["image1.jpg", "image2.jpg", "image3.jpg"] + + # From numpy arrays + image = [np.array(img1), np.array(img2)] + + # From PIL Images + image = [Image.open("image1.jpg"), Image.open("image2.jpg")] + ``` + +#### `extrinsics` (optional) +- **Type**: `Optional[np.ndarray]` +- **Shape**: `(N, 4, 4)` where N is the number of input images +- **Description**: Camera extrinsic matrices (world-to-camera transformation). When provided, enables pose-conditioned depth estimation mode. +- **Note**: If not provided, the model operates in standard depth estimation mode. + +#### `intrinsics` (optional) +- **Type**: `Optional[np.ndarray]` +- **Shape**: `(N, 3, 3)` where N is the number of input images +- **Description**: Camera intrinsic matrices containing focal length and principal point information. When provided, enables pose-conditioned depth estimation mode. + +### 🎯 Pose Alignment Parameters + +#### `align_to_input_ext_scale` (default: True) +- **Type**: `bool` +- **Description**: When True the predicted extrinsics are replaced with the input + ones and the depth maps are rescaled to match their metric scale. When False the + function returns the internally aligned poses computed via Umeyama alignment. + +#### `infer_gs` (default: False) +- **Type**: `bool` +- **Description**: Enable Gaussian Splatting branch for gaussian splatting exports. Required when using `gs_ply` or `gs_video` export formats. + +#### `use_ray_pose` (default: False) +- **Type**: `bool` +- **Description**: Use ray-based pose estimation instead of camera decoder for pose prediction. When True, the model uses ray prediction heads to estimate camera poses; when False, it uses the camera decoder approach. + +#### `ref_view_strategy` (default: "saddle_balanced") +- **Type**: `str` +- **Description**: Strategy for selecting the reference view from multiple input views. Options: `"first"`, `"middle"`, `"saddle_balanced"`, `"saddle_sim_range"`. Only applied when number of views ≥ 3. See [detailed documentation](funcs/ref_view_strategy.md) for strategy comparisons. +- **Available strategies**: + - `"saddle_balanced"`: Selects view with balanced features across multiple metrics (recommended default) + - `"saddle_sim_range"`: Selects view with largest similarity range + - `"first"`: Always uses first view (not recommended, equivalent to no reordering for views < 3) + - `"middle"`: Uses middle view (recommended for video sequences) + +### 🔍 Feature Export Parameters + +#### `export_feat_layers` (default: []) +- **Type**: `List[int]` +- **Description**: List of layer indices to export intermediate features from. Features are stored in the `aux` dictionary of the Prediction object with keys like `feat_layer_0`, `feat_layer_1`, etc. + +### 🎥 Rendering Parameters + +These arguments are only used when exporting Gaussian-splatting videos (include +`"gs_video"` in `export_format`). They describe an auxiliary camera trajectory +with ``M`` views. + +#### `render_exts` (optional) +- **Type**: `Optional[np.ndarray]` +- **Shape**: `(M, 4, 4)` +- **Description**: Camera extrinsics for the synthesized trajectory. If omitted, + the exporter falls back to the predicted poses. + +#### `render_ixts` (optional) +- **Type**: `Optional[np.ndarray]` +- **Shape**: `(M, 3, 3)` +- **Description**: Camera intrinsics for each rendered frame. Leave `None` to + reuse the input intrinsics. + +#### `render_hw` (optional) +- **Type**: `Optional[Tuple[int, int]]` +- **Description**: Explicit output resolution `(height, width)` for the rendered + frames. Defaults to the input resolution when not provided. + +### ⚡ Processing Parameters + +#### `process_res` (default: 504) +- **Type**: `int` +- **Description**: Base resolution for processing. The model will resize images to this resolution for inference. + +#### `process_res_method` (default: "upper_bound_resize") +- **Type**: `str` +- **Description**: Method for resizing images to the target resolution. +- **Options**: + - `"upper_bound_resize"`: Resize so that the specified dimension (504) becomes the longer side + - `"lower_bound_resize"`: Resize so that the specified dimension (504) becomes the shorter side +- **Example**: + - Input: 1200×1600 → Output: 378×504 (with `process_res=504`, `process_res_method="upper_bound_resize"`) + - Input: 504×672 → Output: 504×672 (no change needed) + +### 📦 Export Parameters + +#### `export_dir` (optional) +- **Type**: `Optional[str]` +- **Description**: Directory path where exported files will be saved. If not provided, no files will be exported. + +#### `export_format` (default: "mini_npz") +- **Type**: `str` +- **Description**: Format for exporting results. Supports multiple formats separated by `-`. +- **Example**: `"mini_npz-glb"` exports both mini_npz and glb formats. + +#### 🌐 GLB Export Parameters + +These parameters are passed directly to the `inference()` method and only apply when `export_format` includes `"glb"`. + +##### `conf_thresh_percentile` (default: 40.0) +- **Type**: `float` +- **Description**: Lower percentile for adaptive confidence threshold. Points below this confidence percentile will be filtered out from the point cloud. + +##### `num_max_points` (default: 1,000,000) +- **Type**: `int` +- **Description**: Maximum number of points in the exported point cloud. If the point cloud exceeds this limit, it will be downsampled. + +##### `show_cameras` (default: True) +- **Type**: `bool` +- **Description**: Whether to include camera wireframes in the exported GLB file for visualization. + +#### 🎨 Feature Visualization Parameters + +These parameters are passed directly to the `inference()` method and only apply when `export_format` includes `"feat_vis"`. + +##### `feat_vis_fps` (default: 15) +- **Type**: `int` +- **Description**: Frame rate for the output video when visualizing features across multiple images. + +#### ✨🎥 3DGS and 3DGS Video Parameters + +These parameters are passed directly to the `inference()` method and only apply when `export_format` includes `"gs_ply"` or `"gs_video"`. + +##### `export_kwargs` (default: `{}`) +- Type: `dict[str, dict[str, Any]]` +- Description: Per-format extra arguments passed to export functions, mainly for `"gs_ply"` and `"gs_video"`. + - Access pattern: `export_kwargs[export_format][key] = value` + - Example: + ```python + { + "gs_ply": { + "gs_views_interval": 1, + }, + "gs_video": { + "trj_mode": "interpolate_smooth", + "chunk_size": 1, + "vis_depth": None, + }, + } + ``` + +## 📤 Export Formats + +The API supports multiple export formats for different use cases: + +### 📊 `mini_npz` +- **Description**: Minimal NPZ format containing essential data +- **Contents**: `depth`, `conf`, `exts`, `ixts` +- **Use case**: Lightweight storage for depth data with camera parameters + +### 📦 `npz` +- **Description**: Full NPZ format with comprehensive data +- **Contents**: `depth`, `conf`, `exts`, `ixts`, `image`, etc. +- **Use case**: Complete data export for advanced processing + +### 🌐 `glb` +- **Description**: 3D visualization format with point cloud and camera poses +- **Contents**: + - Point cloud with colors from original images + - Camera wireframes for visualization + - Confidence-based filtering and downsampling +- **Use case**: 3D visualization, inspection, and analysis +- **Features**: + - Automatic sky depth handling + - Confidence threshold filtering + - Background filtering (black/white) + - Scene scale normalization +- **Parameters** (passed via `inference()` method directly): + - `conf_thresh_percentile` (float, default: 40.0): Lower percentile for adaptive confidence threshold. Points below this confidence percentile will be filtered out. + - `num_max_points` (int, default: 1,000,000): Maximum number of points in the exported point cloud. If exceeded, points will be downsampled. + - `show_cameras` (bool, default: True): Whether to include camera wireframes in the exported GLB file for visualization. + +### ✨ `gs_ply` +- **Description**: Gaussian Splatting point cloud format +- **Contents**: 3DGS data in PLY format. Compatible with standard 3DGS viewers such as [SuperSplat](https://superspl.at/editor) (recommended), [SPARK](https://sparkjs.dev/viewer/). +- **Use case**: Gaussian Splatting reconstruction +- **Requirements**: Must set `infer_gs=True` when calling `inference()`. Only supported by `da3-giant` and `da3nested-giant-large` models. +- **Additional configs**, provided via `export_kwargs` (see [Export Parameters](#export-parameters)): + - `gs_views_interval`: Export to 3DGS every N views, default: `1`. + +### 🎥 `gs_video` +- **Description**: Rasterized 3DGS to obtain videos +- **Contents**: A video of 3DGS-rasterized views using either provided viewpoints or a predefined camera trajectory. +- **Use case**: Video rendering for Gaussian Splatting +- **Requirements**: Must set `infer_gs=True` when calling `inference()`. Only supported by `da3-giant` and `da3nested-giant-large` models. +- **Note**: Can optionally use `render_exts`, `render_ixts`, and `render_hw` parameters in `inference()` method to specify novel viewpoints. +- **Additional configs**, provided via `export_kwargs` (see [Export Parameters](#export-parameters)): + - `extrinsics`: Optional world-to-camera poses for novel views. Falls back to the predicted poses of input views if not provided. (Alternatively, use `render_exts` parameter in `inference()`) + - `intrinsics`: Optional camera intrinsics for novel views. Falls back to the predicted intrinsics of input views if not provided. (Alternatively, use `render_ixts` parameter in `inference()`) + - `out_image_hw`: Optional output resolution `H x W`. Falls back to input resolution if not provided. (Alternatively, use `render_hw` parameter in `inference()`) + - `chunk_size`: Number of views rasterized per batch. Default: `8`. + - `trj_mode`: Predefined camera trajectory for novel-view rendering. + - `color_mode`: Same as `render_mode` in [gsplat](https://docs.gsplat.studio/main/apis/rasterization.html#gsplat.rasterization). + - `vis_depth`: How depth is combined with RGB. Default: `hcat` (horizontal concatenation). + - `enable_tqdm`: Whether to display a tqdm progress bar during rendering. + - `output_name`: File name of the rendered video. + - `video_quality`: Video quality to save. Default: `high`. + - `high`: High quality video (default) + - `medium`: Medium quality video (balance of storage space and quality) + - `low`: Low quality video (fewer storage space) + +### 🔍 `feat_vis` +- **Description**: Feature visualization format +- **Contents**: PCA-visualized intermediate features from specified layers +- **Use case**: Model interpretability and feature analysis +- **Note**: Requires `export_feat_layers` to be specified +- **Parameters** (passed via `inference()` method directly): + - `feat_vis_fps` (int, default: 15): Frame rate for the output video when visualizing features across multiple images. + +### 🎨 `depth_vis` +- **Description**: Depth visualization format +- **Contents**: Color-coded depth maps alongside original images +- **Use case**: Visual inspection of depth estimation quality + +### 🔗 Multiple Format Export +You can export multiple formats simultaneously by separating them with `-`: + +```python +# Export both mini_npz and glb formats +export_format = "mini_npz-glb" + +# Export multiple formats +export_format = "npz-glb-gs_ply" +``` + +## ↩️ Return Value + +The `inference()` method returns a `Prediction` object with the following attributes: + +### 📊 Core Outputs + +- **depth**: `np.ndarray` - Estimated depth maps with shape `(N, H, W)` where N is the number of images, H is height, and W is width. +- **conf**: `np.ndarray` - Confidence maps with shape `(N, H, W)` indicating prediction reliability (optional, depends on model). + +### 📷 Camera Parameters + +- **extrinsics**: `np.ndarray` - Camera extrinsic matrices with shape `(N, 3, 4)` representing world-to-camera transformations. Only present if camera poses were estimated or provided as input. +- **intrinsics**: `np.ndarray` - Camera intrinsic matrices with shape `(N, 3, 3)` containing focal length and principal point information. Only present if poses were estimated or provided as input. + +### 🎁 Additional Outputs + +- **processed_images**: `np.ndarray` - Preprocessed input images with shape `(N, H, W, 3)` in RGB format (0-255 uint8). +- **aux**: `dict` - Auxiliary outputs including: + - `feat_layer_X`: Intermediate features from layer X (if `export_feat_layers` was specified) + - `gaussians`: 3D Gaussian Splats data (if `infer_gs=True`) + +### 💻 Usage Example + +```python +prediction = model.inference(image=["img1.jpg", "img2.jpg"]) + +# Access depth maps +depth_maps = prediction.depth # shape: (2, H, W) + +# Access confidence +if hasattr(prediction, 'conf'): + confidence = prediction.conf + +# Access camera parameters (if available) +if hasattr(prediction, 'extrinsics'): + camera_poses = prediction.extrinsics # shape: (2, 4, 4) + +if hasattr(prediction, 'intrinsics'): + camera_intrinsics = prediction.intrinsics # shape: (2, 3, 3) + +# Access intermediate features (if export_feat_layers was set) +if hasattr(prediction, 'aux') and 'feat_layer_0' in prediction.aux: + features = prediction.aux['feat_layer_0'] +``` diff --git a/OVOW/engine/oneposeviagen/DA3/docs/BENCHMARK.md b/OVOW/engine/oneposeviagen/DA3/docs/BENCHMARK.md new file mode 100644 index 0000000000000000000000000000000000000000..9c83ada4ae3ccc8a2c5fd66dc70e4a3bdc634029 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/docs/BENCHMARK.md @@ -0,0 +1,472 @@ +# 📏 DepthAnything3 Benchmark Evaluation + +This document provides comprehensive instructions for running benchmark evaluation on DepthAnything3. + +--- + +## 📑 Table of Contents + +- [🚀 Quick Start](#quick-start) +- [📥 Dataset Download](#dataset-download) +- [⚙️ Evaluation Pipeline](#evaluation-pipeline) +- [🔧 Configuration](#configuration) +- [📊 Metrics](#metrics) +- [🗂️ Dataset Details](#dataset-details) +- [💻 Command Reference](#command-reference) +- [🔍 Troubleshooting](#troubleshooting) + +--- + +## 🚀 Quick Start + +### 1. Download Benchmark Data + +> 💡 **Note:** Install HuggingFace CLI first: `pip install -U huggingface_hub[cli]` +> +> 🌐 **Mirror:** If download is slow, try: `export HF_ENDPOINT=https://hf-mirror.com` + +```bash +cd da3_release + +# Create directory and download from HuggingFace +mkdir -p workspace/benchmark_dataset +hf download depth-anything/DA3-BENCH \ + --local-dir workspace/benchmark_dataset \ + --repo-type dataset + +# Extract all datasets +cd workspace/benchmark_dataset +for f in *.zip; do unzip -q "$f"; done +``` + +### 2. Run Evaluation + +```bash +# Set model (default: depth-anything/DA3-GIANT) +MODEL=depth-anything/DA3-GIANT + +# Full evaluation (all datasets, all modes) +python -m depth_anything_3.bench.evaluator model.path=$MODEL + +# View results +python -m depth_anything_3.bench.evaluator eval.print_only=true +``` + +--- + +## 📥 Dataset Download + +All benchmark datasets are hosted on HuggingFace: **[depth-anything/DA3-BENCH](https://huggingface.co/datasets/depth-anything/DA3-BENCH)** + +| Dataset | File | Size | Description | +|---------|------|------|-------------| +| ETH3D | `eth3d.zip` | ~14.1 GB | High-resolution multi-view stereo (indoor/outdoor) | +| ScanNet++ | `scannetpp.zip` | ~10.1 GB | High-quality RGB-D indoor scenes | +| DTU-49 | `dtu.zip` | ~8.3 GB | Multi-view stereo benchmark (22 scenes × 49 views) | +| 7Scenes | `7scenes.zip` | ~3.3 GB | RGB-D indoor localization | +| DTU-64 | `dtu64.zip` | ~1.7 GB | DTU subset for pose evaluation (13 scenes × 64 views) | +| HiRoom | `hiroom.zip` | ~0.7 GB | High-resolution indoor rooms | + +### Download Options + +**Option 1: Download All (Recommended)** +```bash +hf download depth-anything/DA3-BENCH \ + --local-dir workspace/benchmark_dataset \ + --repo-type dataset +``` + +**Option 2: Download Specific Dataset** +```bash +# Download only HiRoom +hf download depth-anything/DA3-BENCH hiroom.zip \ + --local-dir workspace/benchmark_dataset \ + --repo-type dataset +``` + +**Option 3: Manual Download** + +Visit [https://huggingface.co/datasets/depth-anything/DA3-BENCH](https://huggingface.co/datasets/depth-anything/DA3-BENCH) and download the zip files manually. + +### Extract Datasets + +```bash +cd workspace/benchmark_dataset + +# Extract all +for f in *.zip; do unzip -q "$f"; done + +# Or extract specific dataset +unzip hiroom.zip +``` + +### Expected Directory Structure + +After extraction, your directory should look like: +``` +workspace/benchmark_dataset/ +├── eth3d/ +│ ├── courtyard/ +│ ├── electro/ +│ └── ... +├── 7scenes/ +│ └── 7Scenes/ +│ ├── chess/ +│ └── ... +├── scannetpp/ +│ ├── 09c1414f1b/ +│ └── ... +├── hiroom/ +│ ├── data/ +│ ├── fused_pcd/ +│ └── selected_scene_list_val.txt +├── dtu/ +│ ├── Rectified/ +│ ├── Cameras/ +│ ├── Points/ +│ ├── SampleSet/ +│ └── depth_raw/ +└── dtu64/ + ├── Cameras/ + ├── scan105/ + └── ... +``` + +--- + +## ⚙️ Evaluation Pipeline + + + +### Evaluation Modes + +| Mode | Description | Metrics | +|------|-------------|---------| +| `pose` | Camera pose estimation | AUC@3°, AUC@30° | +| `recon_unposed` | 3D reconstruction with **predicted** poses | F-score, Overall | +| `recon_posed` | 3D reconstruction with **GT** poses | F-score, Overall | + +### Basic Usage + +```bash +cd da3_release +MODEL=depth-anything/DA3-GIANT + +# Full evaluation (inference + evaluation + print results) +python -m depth_anything_3.bench.evaluator model.path=$MODEL + +# Skip inference, only evaluate existing predictions +python -m depth_anything_3.bench.evaluator eval.eval_only=true + +# Only print saved metrics +python -m depth_anything_3.bench.evaluator eval.print_only=true +``` + +### Selective Evaluation + +```bash +# Evaluate specific datasets +python -m depth_anything_3.bench.evaluator model.path=$MODEL eval.datasets=[hiroom] + +# Evaluate specific modes +python -m depth_anything_3.bench.evaluator model.path=$MODEL eval.modes=[pose,recon_unposed] + +# Combine dataset and mode selection +python -m depth_anything_3.bench.evaluator model.path=$MODEL \ + eval.datasets=[hiroom] \ + eval.modes=[pose] +``` + +### 🖥️ Multi-GPU Inference + +The evaluator automatically distributes inference across available GPUs: + +```bash +# Use 4 GPUs +CUDA_VISIBLE_DEVICES=0,1,2,3 python -m depth_anything_3.bench.evaluator model.path=$MODEL + +# Use all available GPUs (default) +python -m depth_anything_3.bench.evaluator model.path=$MODEL + +# Single GPU +CUDA_VISIBLE_DEVICES=0 python -m depth_anything_3.bench.evaluator model.path=$MODEL +``` + +--- + +## 🔧 Configuration + +### Config File + +Default config: `src/depth_anything_3/bench/configs/eval_bench.yaml` + +```yaml +# Model path +model: + path: depth-anything/DA3-GIANT + +# Workspace directory +workspace: + work_dir: ./workspace/evaluation + +# Evaluation settings +eval: + datasets: [eth3d, 7scenes, scannetpp, hiroom, dtu, dtu64] + modes: [pose, recon_unposed, recon_posed] + max_frames: 100 # Max frames per scene (-1 = no limit) + scenes: null # Specific scenes (null = all) + +# Inference settings +inference: + num_fusion_workers: 4 + debug: false +``` + +### Output Structure + +``` +workspace/evaluation/ +├── model_results/ # Inference outputs +│ ├── eth3d/ +│ │ └── {scene}/ +│ │ ├── unposed/ # Predictions for recon_unposed +│ │ └── posed/ # Predictions for recon_posed +│ ├── 7scenes/ +│ ├── scannetpp/ +│ ├── hiroom/ +│ ├── dtu/ +│ └── dtu64/ +└── metric_results/ # Evaluation metrics (JSON) + ├── eth3d_pose.json + ├── eth3d_recon_unposed.json + ├── eth3d_recon_posed.json + └── ... +``` + +--- + +## 📊 Metrics + +### 🎯 Pose Estimation + +| Metric | Description | +|--------|-------------| +| **Auc3** | Area Under Curve at 3° angular error threshold | +| **Auc30** | Area Under Curve at 30° angular error threshold | + +### 🏗️ 3D Reconstruction + +| Metric | Description | Note | +|--------|-------------|------| +| **F-score** | Harmonic mean of Precision and Recall | Higher is better | +| **Overall** | (Accuracy + Completeness) / 2 | Lower is better (error in meters/mm) | + +> **Note:** DTU reports Overall in millimeters; other datasets report in meters. + +### Expected Results for DA3-GIANT + +If your setup is correct, you should get the following results when evaluating the **DA3-GIANT** model: + +``` +======================================================== +📊 SUMMARY +======================================================== + +🎯 POSE ESTIMATION +--------------------------------------------------------------------------------------- +Metric Avg HiRoom ETH3D DTU-64 7Scenes ScanNet++ +--------------------------------------------------------------------------------------- +Auc3 0.6705 0.8030 0.4872 0.9408 0.2744 0.8470 +Auc30 0.9436 0.9592 0.9153 0.9939 0.8668 0.9827 + +🏗️ RECON_UNPOSED (Pred Pose) +--------------------------------------------------------------------------------------- +Metric Avg* HiRoom ETH3D DTU 7Scenes ScanNet++ +--------------------------------------------------------------------------------------- +F-score 0.7345 0.8629 0.7876 N/A 0.5043 0.7831 +Overall 0.1682 0.0457 0.4366 1.7927 0.1230 0.0676 + +🏗️ RECON_POSED (GT Pose) +--------------------------------------------------------------------------------------- +Metric Avg* HiRoom ETH3D DTU 7Scenes ScanNet++ +--------------------------------------------------------------------------------------- +F-score 0.7978 0.9546 0.8685 N/A 0.5635 0.8045 +Overall 0.1408 0.0213 0.3679 1.7488 0.1092 0.0649 + +* Avg F-score / Overall = average over HiRoom, ETH3D, 7Scenes, ScanNet++ (4 datasets) +``` + +--- + +## 🗂️ Dataset Details + +### ETH3D + +High-resolution multi-view stereo benchmark with laser-scanned ground truth. + +- **Scenes:** 11 (courtyard, electro, kicker, pipes, relief, delivery_area, facade, office, playground, relief_2, terrains) +- **Resolution:** Variable (high-res DSLR images) +- **GT:** Laser-scanned meshes + depth maps + +> **⚠️ Image Filtering:** Some images with unusual camera rotations are filtered out for stable evaluation. See `ETH3D_FILTER_KEYS` in `constants.py`. + +### 7Scenes + +RGB-D dataset for camera relocalization. + +- **Scenes:** 7 (chess, fire, heads, office, pumpkin, redkitchen, stairs) +- **Resolution:** 640×480 +- **GT:** Poses from KinectFusion, meshes from TSDF fusion + +### ScanNet++ + +High-quality indoor RGB-D dataset with dense annotations. + +- **Scenes:** 20 validation scenes +- **Resolution:** 768×1024 (after undistortion) +- **GT:** High-quality meshes from FARO scanner + +### HiRoom + +Indoor room scenes with high-resolution RGB-D data. + +- **Scenes:** 24 validation scenes +- **GT:** Fused point clouds + +### DTU-49 (Reconstruction Only) + +Multi-view stereo benchmark following MVSNet evaluation protocol. + +- **Scenes:** 22 evaluation scenes +- **Views:** 49 images per scene +- **GT:** Laser-scanned point clouds with observation masks +- **Metrics:** Overall only (accuracy + completeness in mm) + +### DTU-64 (Pose Only) + +DTU subset for pose estimation evaluation. + +- **Scenes:** 13 scenes +- **Views:** 64 images per scene +- **Metrics:** AUC@3°, AUC@30° + +> **Why two DTU settings?** +> - **DTU-64** (pose): More views = more challenging pose estimation +> - **DTU-49** (recon): Standard MVSNet protocol for fair comparison with MVS methods + +--- + +## 💻 Command Reference + +``` +python -m depth_anything_3.bench.evaluator [OPTIONS] [KEY=VALUE ...] + +Configuration: + --config PATH Config YAML file (default: bench/configs/eval_bench.yaml) + +Config Overrides (using dotlist notation): + model.path=VALUE Model path or HuggingFace ID + workspace.work_dir=VALUE Working directory for outputs + eval.datasets=[dataset1,dataset2] Datasets to evaluate (eth3d,7scenes,scannetpp,hiroom,dtu,dtu64) + eval.modes=[mode1,mode2] Evaluation modes (pose,recon_unposed,recon_posed) + eval.scenes=[scene1,scene2] Specific scenes to evaluate (null=all) + eval.max_frames=VALUE Max frames per scene (-1=no limit, default: 100) + eval.ref_view_strategy=VALUE Reference view strategy (default: first) + eval.eval_only=VALUE Only run evaluation (skip inference) (true/false) + eval.print_only=VALUE Only print saved metrics (true/false) + inference.num_fusion_workers=VALUE Number of parallel workers (default: 4) + inference.debug=VALUE Enable debug mode (true/false) + +Special Flags: + --help, -h Show this help message + +Multi-GPU: + Use CUDA_VISIBLE_DEVICES to specify GPUs (auto-detected and distributed) +``` + +### Examples + +```bash +MODEL=depth-anything/DA3-GIANT + +# Full evaluation +python -m depth_anything_3.bench.evaluator model.path=$MODEL + +# Quick test on HiRoom only +python -m depth_anything_3.bench.evaluator \ + model.path=$MODEL \ + eval.datasets=[hiroom] \ + eval.modes=[pose] + +# Pose-only evaluation (all 5 pose datasets) +python -m depth_anything_3.bench.evaluator \ + model.path=$MODEL \ + eval.datasets=[eth3d,7scenes,scannetpp,hiroom,dtu64] \ + eval.modes=[pose] + +# Recon-only evaluation (all 5 recon datasets) +python -m depth_anything_3.bench.evaluator \ + model.path=$MODEL \ + eval.datasets=[eth3d,7scenes,scannetpp,hiroom,dtu] \ + eval.modes=[recon_unposed,recon_posed] + +# Debug specific scenes +python -m depth_anything_3.bench.evaluator \ + model.path=$MODEL \ + eval.datasets=[eth3d] \ + eval.scenes=[courtyard] \ + inference.debug=true + +# Re-evaluate without re-running inference +python -m depth_anything_3.bench.evaluator eval.eval_only=true + +# Just view results +python -m depth_anything_3.bench.evaluator eval.print_only=true +``` + +--- + +## 🔍 Troubleshooting + +### Data Path Issues + +Ensure dataset paths in `src/depth_anything_3/utils/constants.py` are correct: + +```python +# Default paths (relative to project root) +ETH3D_EVAL_DATA_ROOT = "workspace/benchmark_dataset/eth3d" +SEVENSCENES_EVAL_DATA_ROOT = "workspace/benchmark_dataset/7scenes" +SCANNETPP_EVAL_DATA_ROOT = "workspace/benchmark_dataset/scannetpp" +HIROOM_EVAL_DATA_ROOT = "workspace/benchmark_dataset/hiroom/data" +DTU_EVAL_DATA_ROOT = "workspace/benchmark_dataset/dtu" +DTU64_EVAL_DATA_ROOT = "workspace/benchmark_dataset/dtu64" +``` + +--- + +## 📝 Citation + +If you find this benchmark useful, please cite: + +``` +@article{depthanything3, + title={Depth Anything 3: Recovering the visual space from any views}, + author={Haotong Lin and Sili Chen and Jun Hao Liew and Donny Y. Chen and Zhenyu Li and Guang Shi and Jiashi Feng and Bingyi Kang}, + journal={arXiv preprint arXiv:2511.10647}, + year={2025} +} +``` + +Please also cite the original dataset papers for each benchmark you use. + +--- + +## 📄 License + +The benchmark datasets are provided for research purposes only. Users must follow the original licenses of each dataset: + +- **ETH3D:** [https://www.eth3d.net/](https://www.eth3d.net/) +- **7Scenes:** [Microsoft Research](https://www.microsoft.com/en-us/research/project/rgb-d-dataset-7-scenes/) +- **ScanNet++:** [http://www.scan-net.org/](http://www.scan-net.org/) +- **DTU:** [https://roboimagedata.compute.dtu.dk/](https://roboimagedata.compute.dtu.dk/) +- **HiRoom:** [SVLightVerse](https://jerrypiglet.github.io/SVLightVerse/) diff --git a/OVOW/engine/oneposeviagen/DA3/docs/CLI.md b/OVOW/engine/oneposeviagen/DA3/docs/CLI.md new file mode 100644 index 0000000000000000000000000000000000000000..c99ba0bb7540028bae3e0fbe93c0945fe5140c1e --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/docs/CLI.md @@ -0,0 +1,654 @@ +# 🚀 Depth Anything 3 Command Line Interface + +## 📋 Table of Contents + +- [📖 Overview](#overview) +- [⚡ Quick Start](#quick-start) +- [📚 Command Reference](#command-reference) + - [🤖 auto - Auto Mode](#auto---auto-mode) + - [🖼️ image - Single Image Processing](#image---single-image-processing) + - [🗂️ images - Image Directory Processing](#images---image-directory-processing) + - [🎬 video - Video Processing](#video---video-processing) + - [📐 colmap - COLMAP Dataset Processing](#colmap---colmap-dataset-processing) + - [🔧 backend - Backend Service](#backend---backend-service) + - [🎨 gradio - Gradio Application](#gradio---gradio-application) + - [🖼️ gallery - Gallery Server](#gallery---gallery-server) +- [⚙️ Parameter Details](#parameter-details) +- [💡 Usage Examples](#usage-examples) + +## 📖 Overview + +The Depth Anything 3 CLI provides a comprehensive command-line toolkit supporting image depth estimation, video processing, COLMAP dataset handling, and web applications. + +The backend service enables cache model to GPU so that we do not need to reload model for each command. + +## ⚡ Quick Start + +The CLI can run fully offline or connect to the backend for cached weights and task scheduling: + +```bash +# 🔧 Start backend service (optional, keeps model resident in GPU memory) +da3 backend --model-dir depth-anything/DA3NESTED-GIANT-LARGE + +# 🚀 Use auto mode to process input +da3 auto path/to/input --export-dir ./workspace/scene001 + +# ♻️ Reuse backend for next job +da3 auto path/to/video.mp4 \ + --export-dir ./workspace/scene002 \ + --use-backend \ + --backend-url http://localhost:8008 +``` + +Each export directory contains `scene.glb`, `scene.jpg`, and optional extras such as `depth_vis/` or `gs_video/` depending on the requested format. + +## 📚 Command Reference + +### 🤖 auto - Auto Mode + +Automatically detect input type and dispatch to the appropriate handler. + +**Usage:** + +```bash +da3 auto INPUT_PATH [OPTIONS] +``` + +**Input Type Detection:** +- 🖼️ Single image file (.jpg, .png, .jpeg, .webp, .bmp, .tiff, .tif) +- 📁 Image directory +- 🎬 Video file (.mp4, .avi, .mov, .mkv, .flv, .wmv, .webm, .m4v) +- 📐 COLMAP directory (containing `images/` and `sparse/` subdirectories) + +**Parameters:** + +| Parameter | Type | Default | Description | +|-----------|------|---------|-------------| +| `INPUT_PATH` | str | Required | Input path (image, directory, video, or COLMAP) | +| `--model-dir` | str | Default model | Model directory path | +| `--export-dir` | str | `debug` | Export directory | +| `--export-format` | str | `glb` | Export format (supports `mini_npz`, `glb`, `feat_vis`, etc., can be combined with hyphens) | +| `--device` | str | `cuda` | Device to use | +| `--use-backend` | bool | `False` | Use backend service for inference | +| `--backend-url` | str | `http://localhost:8008` | Backend service URL | +| `--process-res` | int | `504` | Processing resolution | +| `--process-res-method` | str | `upper_bound_resize` | Processing resolution method | +| `--export-feat` | str | `""` | Export features from specified layers, comma-separated (e.g., `"0,1,2"`) | +| `--auto-cleanup` | bool | `False` | Automatically clean export directory without confirmation | +| `--fps` | float | `1.0` | [Video] Frame sampling FPS | +| `--sparse-subdir` | str | `""` | [COLMAP] Sparse reconstruction subdirectory (e.g., `"0"` for `sparse/0/`) | +| `--align-to-input-ext-scale` | bool | `True` | [COLMAP] Align prediction to input extrinsics scale | +| `--use-ray-pose` | bool | `False` | Use ray-based pose estimation instead of camera decoder | +| `--ref-view-strategy` | str | `saddle_balanced` | Reference view selection strategy: `first`, `middle`, `saddle_balanced`, `saddle_sim_range`. See [docs](funcs/ref_view_strategy.md) | +| `--conf-thresh-percentile` | float | `40.0` | [GLB] Lower percentile for adaptive confidence threshold | +| `--num-max-points` | int | `1000000` | [GLB] Maximum number of points in the point cloud | +| `--show-cameras` | bool | `True` | [GLB] Show camera wireframes in the exported scene | +| `--feat-vis-fps` | int | `15` | [FEAT_VIS] Frame rate for output video | + +**Examples:** + +```bash +# 🖼️ Auto-process an image +da3 auto path/to/image.jpg --export-dir ./output + +# 🎬 Auto-process a video +da3 auto path/to/video.mp4 --fps 2.0 --export-dir ./output + +# 🔧 Use backend service +da3 auto path/to/input \ + --export-format mini_npz-glb \ + --use-backend \ + --backend-url http://localhost:8008 \ + --export-dir ./output +``` + +--- + +### 🖼️ image - Single Image Processing + +Process a single image for camera pose and depth estimation. + +**Usage:** + +```bash +da3 image IMAGE_PATH [OPTIONS] +``` + +**Parameters:** + +| Parameter | Type | Default | Description | +|-----------|------|---------|-------------| +| `IMAGE_PATH` | str | Required | Input image file path | +| `--model-dir` | str | Default model | Model directory path | +| `--export-dir` | str | `debug` | Export directory | +| `--export-format` | str | `glb` | Export format | +| `--device` | str | `cuda` | Device to use | +| `--use-backend` | bool | `False` | Use backend service for inference | +| `--backend-url` | str | `http://localhost:8008` | Backend service URL | +| `--process-res` | int | `504` | Processing resolution | +| `--process-res-method` | str | `upper_bound_resize` | Processing resolution method | +| `--export-feat` | str | `""` | Export feature layer indices (comma-separated) | +| `--auto-cleanup` | bool | `False` | Automatically clean export directory | +| `--use-ray-pose` | bool | `False` | Use ray-based pose estimation instead of camera decoder | +| `--ref-view-strategy` | str | `saddle_balanced` | Reference view selection strategy. See [docs](funcs/ref_view_strategy.md) | +| `--conf-thresh-percentile` | float | `40.0` | [GLB] Confidence threshold percentile | +| `--num-max-points` | int | `1000000` | [GLB] Maximum number of points | +| `--show-cameras` | bool | `True` | [GLB] Show cameras | +| `--feat-vis-fps` | int | `15` | [FEAT_VIS] Video frame rate | + +**Examples:** + +```bash +# ✨ Basic usage +da3 image path/to/image.png --export-dir ./output + +# ⚡ With backend acceleration +da3 image path/to/image.png \ + --use-backend \ + --backend-url http://localhost:8008 \ + --export-dir ./output + +# 🔍 Export feature visualization +da3 image image.jpg \ + --export-format feat_vis \ + --export-feat "9,19,29,39" \ + --export-dir ./results +``` + +--- + +### 🗂️ images - Image Directory Processing + +Process a directory of images for batch depth estimation. + +**Usage:** + +```bash +da3 images IMAGES_DIR [OPTIONS] +``` + +**Parameters:** + +| Parameter | Type | Default | Description | +|-----------|------|---------|-------------| +| `IMAGES_DIR` | str | Required | Directory path containing images | +| `--image-extensions` | str | `png,jpg,jpeg` | Image file extensions to process (comma-separated) | +| `--model-dir` | str | Default model | Model directory path | +| `--export-dir` | str | `debug` | Export directory | +| `--export-format` | str | `glb` | Export format | +| `--device` | str | `cuda` | Device to use | +| `--use-backend` | bool | `False` | Use backend service for inference | +| `--backend-url` | str | `http://localhost:8008` | Backend service URL | +| `--process-res` | int | `504` | Processing resolution | +| `--process-res-method` | str | `upper_bound_resize` | Processing resolution method | +| `--export-feat` | str | `""` | Export feature layer indices | +| `--auto-cleanup` | bool | `False` | Automatically clean export directory | +| `--use-ray-pose` | bool | `False` | Use ray-based pose estimation instead of camera decoder | +| `--ref-view-strategy` | str | `saddle_balanced` | Reference view selection strategy. See [docs](funcs/ref_view_strategy.md) | +| `--conf-thresh-percentile` | float | `40.0` | [GLB] Confidence threshold percentile | +| `--num-max-points` | int | `1000000` | [GLB] Maximum number of points | +| `--show-cameras` | bool | `True` | [GLB] Show cameras | +| `--feat-vis-fps` | int | `15` | [FEAT_VIS] Video frame rate | + +**Examples:** + +```bash +# 📁 Process directory (defaults to png/jpg/jpeg) +da3 images ./image_folder --export-dir ./output + +# 🎯 Custom extensions +da3 images ./dataset --image-extensions "png,jpg,webp" --export-dir ./output + +# 🔧 Use backend service +da3 images ./dataset \ + --use-backend \ + --backend-url http://localhost:8008 \ + --export-dir ./output +``` + +--- + +### 🎬 video - Video Processing + +Process video by extracting frames for depth estimation. + +**Usage:** + +```bash +da3 video VIDEO_PATH [OPTIONS] +``` + +**Parameters:** + +| Parameter | Type | Default | Description | +|-----------|------|---------|-------------| +| `VIDEO_PATH` | str | Required | Input video file path | +| `--fps` | float | `1.0` | Frame extraction sampling FPS | +| `--model-dir` | str | Default model | Model directory path | +| `--export-dir` | str | `debug` | Export directory | +| `--export-format` | str | `glb` | Export format | +| `--device` | str | `cuda` | Device to use | +| `--use-backend` | bool | `False` | Use backend service for inference | +| `--backend-url` | str | `http://localhost:8008` | Backend service URL | +| `--process-res` | int | `504` | Processing resolution | +| `--process-res-method` | str | `upper_bound_resize` | Processing resolution method | +| `--export-feat` | str | `""` | Export feature layer indices | +| `--auto-cleanup` | bool | `False` | Automatically clean export directory | +| `--use-ray-pose` | bool | `False` | Use ray-based pose estimation instead of camera decoder | +| `--ref-view-strategy` | str | `saddle_balanced` | Reference view selection strategy. See [docs](funcs/ref_view_strategy.md) | +| `--conf-thresh-percentile` | float | `40.0` | [GLB] Confidence threshold percentile | +| `--num-max-points` | int | `1000000` | [GLB] Maximum number of points | +| `--show-cameras` | bool | `True` | [GLB] Show cameras | +| `--feat-vis-fps` | int | `15` | [FEAT_VIS] Video frame rate | + +**Examples:** + +```bash +# ✨ Basic video processing +da3 video path/to/video.mp4 --export-dir ./output + +# ⚙️ Control frame sampling and resolution +da3 video path/to/video.mp4 \ + --fps 2.0 \ + --process-res 1024 \ + --export-dir ./output + +# 🔧 Use backend service +da3 video path/to/video.mp4 \ + --use-backend \ + --backend-url http://localhost:8008 \ + --export-dir ./output +``` + +--- + +### 📐 colmap - COLMAP Dataset Processing + +Run pose-conditioned depth estimation on COLMAP data. + +**Usage:** + +```bash +da3 colmap COLMAP_DIR [OPTIONS] +``` + +**Parameters:** + +| Parameter | Type | Default | Description | +|-----------|------|---------|-------------| +| `COLMAP_DIR` | str | Required | COLMAP directory containing `images/` and `sparse/` subdirectories | +| `--sparse-subdir` | str | `""` | Sparse reconstruction subdirectory (e.g., `"0"` for `sparse/0/`) | +| `--align-to-input-ext-scale` | bool | `True` | Align prediction to input extrinsics scale | +| `--model-dir` | str | Default model | Model directory path | +| `--export-dir` | str | `debug` | Export directory | +| `--export-format` | str | `glb` | Export format | +| `--device` | str | `cuda` | Device to use | +| `--use-backend` | bool | `False` | Use backend service for inference | +| `--backend-url` | str | `http://localhost:8008` | Backend service URL | +| `--process-res` | int | `504` | Processing resolution | +| `--process-res-method` | str | `upper_bound_resize` | Processing resolution method | +| `--export-feat` | str | `""` | Export feature layer indices | +| `--auto-cleanup` | bool | `False` | Automatically clean export directory | +| `--use-ray-pose` | bool | `False` | Use ray-based pose estimation instead of camera decoder | +| `--ref-view-strategy` | str | `saddle_balanced` | Reference view selection strategy. See [docs](funcs/ref_view_strategy.md) | +| `--conf-thresh-percentile` | float | `40.0` | [GLB] Confidence threshold percentile | +| `--num-max-points` | int | `1000000` | [GLB] Maximum number of points | +| `--show-cameras` | bool | `True` | [GLB] Show cameras | +| `--feat-vis-fps` | int | `15` | [FEAT_VIS] Video frame rate | + +**Examples:** + +```bash +# 📐 Process COLMAP dataset +da3 colmap ./colmap_dataset --export-dir ./output + +# 🎯 Use specific sparse subdirectory and align scale +da3 colmap ./colmap_dataset \ + --sparse-subdir 0 \ + --align-to-input-ext-scale \ + --export-dir ./output + +# 🔧 Use backend service +da3 colmap ./colmap_dataset \ + --use-backend \ + --backend-url http://localhost:8008 \ + --export-dir ./output +``` + +--- + +### 🔧 backend - Backend Service + +Start model backend service with integrated gallery. + +**Usage:** + +```bash +da3 backend [OPTIONS] +``` + +**Parameters:** + +| Parameter | Type | Default | Description | +|-----------|------|---------|-------------| +| `--model-dir` | str | Default model | Model directory path | +| `--device` | str | `cuda` | Device to use | +| `--host` | str | `127.0.0.1` | Host address to bind to | +| `--port` | int | `8008` | Port number to bind to | +| `--gallery-dir` | str | Default gallery dir | Gallery directory path (optional) | + +**Features:** +- 🎯 Keeps model resident in GPU memory +- 🔌 Provides REST inference API +- 📊 Integrated dashboard and status monitoring +- 🖼️ Optional gallery browser (if `--gallery-dir` is provided) + +**Available Endpoints:** +- 🏠 `/` - Home page +- 📊 `/dashboard` - Dashboard +- ✅ `/status` - API status +- 🖼️ `/gallery/` - Gallery browser (if enabled) + +**Examples:** + +```bash +# 🚀 Basic backend service +da3 backend --model-dir depth-anything/DA3NESTED-GIANT-LARGE + +# 🖼️ Backend with gallery +da3 backend \ + --model-dir depth-anything/DA3NESTED-GIANT-LARGE \ + --device cuda \ + --host 0.0.0.0 \ + --port 8008 \ + --gallery-dir ./workspace + +# 💻 Use CPU +da3 backend --model-dir depth-anything/DA3NESTED-GIANT-LARGE --device cpu +``` + +--- + +### 🎨 gradio - Gradio Application + +Launch Depth Anything 3 Gradio interactive web application. + +**Usage:** + +```bash +da3 gradio [OPTIONS] +``` + +**Parameters:** + +| Parameter | Type | Default | Description | +|-----------|------|---------|-------------| +| `--model-dir` | str | Required | Model directory path | +| `--workspace-dir` | str | Required | Workspace directory path | +| `--gallery-dir` | str | Required | Gallery directory path | +| `--host` | str | `127.0.0.1` | Host address to bind to | +| `--port` | int | `7860` | Port number to bind to | +| `--share` | bool | `False` | Create a public link | +| `--debug` | bool | `False` | Enable debug mode | +| `--cache-examples` | bool | `False` | Pre-cache all example scenes at startup | +| `--cache-gs-tag` | str | `""` | Tag to match scene names for high-res+3DGS caching | + +**Examples:** + +```bash +# 🎨 Basic Gradio application +da3 gradio \ + --model-dir depth-anything/DA3NESTED-GIANT-LARGE \ + --workspace-dir ./workspace \ + --gallery-dir ./gallery + +# 🌐 Enable sharing and debug +da3 gradio \ + --model-dir depth-anything/DA3NESTED-GIANT-LARGE \ + --workspace-dir ./workspace \ + --gallery-dir ./gallery \ + --share \ + --debug + +# ⚡ Pre-cache examples +da3 gradio \ + --model-dir depth-anything/DA3NESTED-GIANT-LARGE \ + --workspace-dir ./workspace \ + --gallery-dir ./gallery \ + --cache-examples \ + --cache-gs-tag "dl3dv" +``` + +--- + +### 🖼️ gallery - Gallery Server + +Launch standalone Depth Anything 3 Gallery server. + +**Usage:** + +```bash +da3 gallery [OPTIONS] +``` + +**Parameters:** + +| Parameter | Type | Default | Description | +|-----------|------|---------|-------------| +| `--gallery-dir` | str | Default gallery dir | Gallery root directory | +| `--host` | str | `127.0.0.1` | Host address to bind to | +| `--port` | int | `8007` | Port number to bind to | +| `--open-browser` | bool | `False` | Open browser after launch | + +**Note:** +The gallery expects each scene folder to contain at least `scene.glb` and `scene.jpg`, with optional subfolders such as `depth_vis/` or `gs_video/`. + +**Examples:** + +```bash +# 🖼️ Basic gallery server +da3 gallery --gallery-dir ./workspace + +# 🌐 Custom host and port +da3 gallery \ + --gallery-dir ./workspace \ + --host 0.0.0.0 \ + --port 8007 + +# 🚀 Auto-open browser +da3 gallery --gallery-dir ./workspace --open-browser +``` + +--- + +## ⚙️ Parameter Details + +### 🔧 Common Parameters + +- **`--export-dir`**: Output directory, defaults to `debug` +- **`--export-format`**: Export format, supports combining multiple formats with hyphens: + - 📦 `mini_npz`: Compressed NumPy format + - 🎨 `glb`: glTF binary format (3D scene) + - 🔍 `feat_vis`: Feature visualization + - Example: `mini_npz-glb` exports both formats + +- **`--process-res`** / **`--process-res-method`**: Control preprocessing resolution strategy + - `process-res`: Target resolution (default 504) + - `process-res-method`: Resize method (default `upper_bound_resize`) + +- **`--auto-cleanup`**: Remove existing export directory without confirmation + +- **`--use-backend`** / **`--backend-url`**: Reuse running backend service + - ⚡ Reduces model loading time + - 🌐 Supports distributed processing + +- **`--export-feat`**: Layer indices for exporting intermediate features (comma-separated) + - Example: `"9,19,29,39"` + +### 🎨 GLB Export Parameters + +- **`--conf-thresh-percentile`**: Lower percentile for adaptive confidence threshold (default 40.0) + - Used to filter low-confidence points + +- **`--num-max-points`**: Maximum number of points in point cloud (default 1,000,000) + - Controls output file size and performance + +- **`--show-cameras`**: Show camera wireframes in exported scene (default True) + +### 🔍 Feature Visualization Parameters + +- **`--feat-vis-fps`**: Frame rate for feature visualization output video (default 15) + +### 🎬 Video-Specific Parameters + +- **`--fps`**: Video frame extraction sampling rate (default 1.0 FPS) + - Higher values extract more frames + +### 📐 COLMAP-Specific Parameters + +- **`--sparse-subdir`**: Sparse reconstruction subdirectory + - Empty string uses `sparse/` directory + - `"0"` uses `sparse/0/` directory + +- **`--align-to-input-ext-scale`**: Align prediction to input extrinsics scale (default True) + - Ensures depth estimation is consistent with COLMAP scale + +--- + +## 💡 Usage Examples + +### 1️⃣ Basic Workflow + +```bash +# 🔧 Start backend service +da3 backend --model-dir depth-anything/DA3NESTED-GIANT-LARGE --host 0.0.0.0 --port 8008 + +# 🖼️ Process single image +da3 image image.jpg --export-dir ./output1 --use-backend + +# 🎬 Process video +da3 video video.mp4 --fps 2.0 --export-dir ./output2 --use-backend + +# 📐 Process COLMAP dataset +da3 colmap ./colmap_data --export-dir ./output3 --use-backend +``` + +### 2️⃣ Using Auto Mode + +```bash +# 🤖 Auto-detect and process +da3 auto ./unknown_input --export-dir ./output + +# ⚡ With backend acceleration +da3 auto ./unknown_input \ + --use-backend \ + --backend-url http://localhost:8008 \ + --export-dir ./output +``` + +### 3️⃣ Multi-Format Export + +```bash +# 📦 Export both NPZ and GLB formats +da3 auto assets/examples/SOH \ + --export-format mini_npz-glb \ + --export-dir ./workspace/soh + +# 🔍 Export feature visualization +da3 image image.jpg \ + --export-format feat_vis \ + --export-feat "9,19,29,39" \ + --export-dir ./results +``` + +### 4️⃣ Advanced Configuration + +```bash +# ⚙️ Custom resolution and point cloud density +da3 image image.jpg \ + --process-res 1024 \ + --num-max-points 2000000 \ + --conf-thresh-percentile 30.0 \ + --export-dir ./output + +# 📐 COLMAP advanced options +da3 colmap ./colmap_data \ + --sparse-subdir 0 \ + --align-to-input-ext-scale \ + --process-res 756 \ + --export-dir ./output +``` + +### 5️⃣ Batch Processing Workflow + +```bash +# 🔧 Start backend +da3 backend \ + --model-dir depth-anything/DA3NESTED-GIANT-LARGE \ + --device cuda \ + --host 0.0.0.0 \ + --port 8008 \ + --gallery-dir ./workspace + +# 🔄 Batch process multiple scenes +for scene in scene1 scene2 scene3; do + da3 auto ./data/$scene \ + --export-dir ./workspace/$scene \ + --use-backend \ + --auto-cleanup +done + +# 🖼️ Launch gallery to view results +da3 gallery --gallery-dir ./workspace --open-browser +``` + +### 6️⃣ Web Applications + +```bash +# 🎨 Launch Gradio application +da3 gradio \ + --model-dir depth-anything/DA3NESTED-GIANT-LARGE \ + --workspace-dir workspace/gradio \ + --gallery-dir ./gallery \ + --host 0.0.0.0 \ + --port 7860 \ + --share +``` + +### 7️⃣ Transformer Feature Visualization + +```bash +# 🔍 Export Transformer features +# 📦 Combined with numerical output +da3 auto video.mp4 \ + --export-format glb-feat_vis \ + --export-feat "11,21,31" \ + --export-dir ./debug \ + --use-backend +``` + +--- + +## 📝 Notes + +1. **🔧 Backend Service**: Recommended for processing multiple tasks to improve efficiency +2. **💾 GPU Memory**: Be mindful of GPU memory usage when processing high-resolution inputs +3. **📁 Export Directory**: Use `--auto-cleanup` to avoid manual confirmation for deletion +4. **🔀 Format Combination**: Multiple export formats can be combined with hyphens (e.g., `mini_npz-glb-feat_vis`) +5. **📐 COLMAP Data**: Ensure COLMAP directory structure is correct (contains `images/` and `sparse/` subdirectories) + +--- + +## ❓ Getting Help + +View detailed help for any command: + +```bash +# 📖 View main help +da3 --help + +# 🔍 View specific command help +da3 auto --help +da3 image --help +da3 backend --help +``` diff --git a/OVOW/engine/oneposeviagen/DA3/docs/funcs/ref_view_strategy.md b/OVOW/engine/oneposeviagen/DA3/docs/funcs/ref_view_strategy.md new file mode 100644 index 0000000000000000000000000000000000000000..840f27293653557e323d4b3aae29fbc88ec738de --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/docs/funcs/ref_view_strategy.md @@ -0,0 +1,183 @@ +# 📐 Reference View Selection Strategy + +## 📖 Overview + +Reference view selection is a component in multi-view depth estimation. When processing multiple input views, the model needs to determine which view should serve as the primary reference frame for depth prediction, defining the world coordinate system. + +Different reference view will leads to different reconstruction results. This is a known consideration in multi-view geometry and was analyzed in [PI3](https://arxiv.org/abs/2507.13347). The choice of reference view can affect the quality and consistency of depth predictions across the scene. + + +## 🚀 Our Simple Solution: Automatic Reference View Selection + +DA3 provides a simple approach to address this through **automatic reference view selection** based on **class tokens**. Instead of relying on heuristics or manual selection, the model analyzes the class token features from all input views and intelligently selects the most suitable reference frame. + +--- + +## 🎨 Available Strategies + +### 1. ⚖️ `saddle_balanced` (Recommended, Default) + +**Philosophy:** +Select a view that achieves balance across multiple feature metrics. This strategy looks for a "middle ground" view that is neither too similar nor too different from other views, making it a stable reference point. + +**How it works:** +1. Extracts and normalizes class tokens from all views +2. Computes three complementary metrics for each view: + - **Similarity score**: Average cosine similarity with other views + - **Feature norm**: L2 norm of the original features + - **Feature variance**: Variance across feature dimensions +3. Normalizes each metric to [0, 1] range +4. Selects the view closest to 0.5 (median) across all three metrics + +### 2. 🎢 `saddle_sim_range` + +**Philosophy:** +Select a view with the largest similarity range to other views. This identifies "saddle point" views that are highly similar to some views but dissimilar to others, making them information-rich anchor points. + +**How it works:** +1. Computes pairwise cosine similarity between all views +2. For each view, calculates the range (max - min) of similarities to other views +3. Selects the view with the maximum similarity range + +--- + +### 3. 1️⃣ `first` (Not Recommended) + +**Philosophy:** +Always use the first view in the input sequence as the reference. + +**How it works:** +Simply returns index 0. + +**When to use:** +- ⛔ **Not recommended** in general +- 🔧 Only use when you have manually pre-sorted your views and know the first view is optimal +- 🐛 Debugging or baseline comparisons + +--- + +### 4. ⏸️ `middle` + +**Philosophy:** +Select the view in the middle of the input sequence. + +**How it works:** +Returns the view at index `S // 2` where S is the number of views. + +**When to use:** +- ⏱️ **Only recommended when input images are temporally ordered** +- 🎬 Video sequences (e.g., **DA3-LONG** setting) +- 📹 Sequential captures where the middle frame likely has the most stable viewpoint + +**Specific use case: DA3-LONG** 🎬 +In video-based depth estimation scenarios (like DA3-LONG), where inputs are consecutive frames, `middle` is often the **optimal choice** because that it has maximum overlap with all other frames. + + +## 💻 Usage + +### 🐍 Python API + +```python +from depth_anything_3 import DepthAnything3 + +model = DepthAnything3.from_pretrained("depth-anything/DA3NESTED-GIANT-LARGE") + +# Use default (saddle_balanced) +prediction = model.inference( + images, + ref_view_strategy="saddle_balanced" +) + +# For video sequences, consider using middle +prediction = model.inference( + video_frames, + ref_view_strategy="middle" # Good for temporal sequences +) + +# For complex scenes with wide baselines +prediction = model.inference( + images, + ref_view_strategy="saddle_sim_range" +) +``` + +### 🖥️ Command Line Interface + +```bash +# Default (saddle_balanced) +da3 auto input/ --export-dir output/ + +# Explicitly specify strategy +da3 auto input/ --ref-view-strategy saddle_balanced + +# For video processing +da3 video input.mp4 --ref-view-strategy middle + +# For wide-baseline multi-view +da3 images captures/ --ref-view-strategy saddle_sim_range +``` + +--- + +### 🎯 When Selection Is Applied + +Reference view selection is applied when: +- 3️⃣ Number of views S ≥ 3 + +--- + +## 💡 Recommendations + +### 📋 Quick Guide + +| Scenario | Recommended Strategy | Rationale | +|----------|---------------------|-----------| +| **Default / Unknown** | `saddle_balanced` | Robust, balanced, works well across diverse scenarios | +| **Video frames** | `middle` | Temporal coherence, stable middle frame | +| **Wide-baseline multi-view** | `saddle_sim_range` | Maximizes information coverage | +| **Pre-sorted inputs** | `first` | Use only if you've manually optimized ordering | +| **Single image** | `first` | Automatically used (no reordering needed for S ≤ 2) | + +### ✨ Best Practices + +1. 🎯 **Start with defaults**: `saddle_balanced` works well in most cases +2. 🎬 **Consider your input type**: Use `middle` for videos, `saddle_balanced` for photos +3. 🔬 **Experiment if needed**: Try different strategies if results are suboptimal +4. 📊 **Monitor performance**: Check `glb` quality and consistency across views. + +--- + +## 🔧 Technical Details + +### 🎚️ Selection Threshold + +The reference view selection is only triggered when: +```python +num_views >= 3 # At least 3 views required +``` + +For 1-2 views, no reordering is performed (equivalent to using `first`). + +### ⚙️ Implementation + +The selection happens at layer `alt_start - 1` in the vision transformer, before the first global attention layer. This ensures the selected reference view influences the entire depth prediction pipeline. + +--- + +## ❓ FAQ + +**Q: 🤔 Why is this feature provided?** +A: The model can handle any view order, but this feature provides automatic optimization for reference view selection, which can help improve depth prediction quality in multi-view scenarios. + +**Q: ⏱️ Does this add computational cost?** +A: The overhead is totally negligible. + +**Q: 🎮 Can I manually specify which view to use as reference?** +A: Not directly through this parameter. You can pre-sort your input images to place your preferred reference view first and use `ref_view_strategy="first"`. + +**Q: ⚙️ What happens if I don't specify this parameter?** +A: The default `saddle_balanced` strategy is used automatically. + +**Q: 📊 Is this feature used in the DA3 paper benchmarks?** +A: No, the paper used `first` as the default strategy for all multi-view experiments. The current default has been updated to `saddle_balanced` for better robustness. + diff --git a/OVOW/engine/oneposeviagen/DA3/notebooks/da3.ipynb b/OVOW/engine/oneposeviagen/DA3/notebooks/da3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..9f98cdbb641292f658139d34d3286b71a3b2009c --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/notebooks/da3.ipynb @@ -0,0 +1,150 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Depth Anything 3 (DA3) Usage Example\n", + "\n", + "This notebook demonstrates how to use Depth Anything 3 for camera poses and depth estimation.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Install required packages\n", + "# !pip install depth-anything-3" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Loading weights from local directory\n", + "Model loaded on cuda\n" + ] + } + ], + "source": [ + "import os\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from PIL import Image\n", + "import torch\n", + "from depth_anything_3.api import DepthAnything3\n", + "from depth_anything_3.utils.visualize import visualize_depth\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "model = DepthAnything3.from_pretrained(\"depth-anything/DA3NESTED-GIANT-LARGE\")\n", + "model = model.to(device)\n", + "model.eval()\n", + "print(f\"Model loaded on {device}\")\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Depth shape: (2, 280, 504)\n", + "Extrinsics: (2, 3, 4)\n", + "Intrinsics: (2, 3, 3)\n" + ] + } + ], + "source": [ + "# Load sample images and run inference\n", + "image_paths = [\n", + " \"assets/examples/SOH/000.png\",\n", + " \"assets/examples/SOH/010.png\"\n", + "]\n", + "\n", + "# Run inference\n", + "prediction = model.inference(\n", + " image=image_paths,\n", + " process_res=504,\n", + " process_res_method=\"upper_bound_resize\",\n", + " export_dir=None,\n", + " export_format=\"glb\"\n", + ")\n", + "print(f\"Depth shape: {prediction.depth.shape}\")\n", + "print(f\"Extrinsics: {prediction.extrinsics.shape if prediction.extrinsics is not None else 'None'}\")\n", + "print(f\"Intrinsics: {prediction.intrinsics.shape if prediction.intrinsics is not None else 'None'}\")\n" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": {}, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAABBkAAAJOCAYAAADyJN+HAAAAOnRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjEwLjcsIGh0dHBzOi8vbWF0cGxvdGxpYi5vcmcvTLEjVAAAAAlwSFlzAAAPYQAAD2EBqD+naQABAABJREFUeJzs/VusbUlyFox+kTnmXGvtte916+q2++K2227j3wcwxwbJli3EkUEgZFtICAQWMtI5biE/YFl+MtCW4AFhGyMhg4Stg2xkyW/wgoRkZAPiWFwewDS4bffvrr5UV1fVrtq3dZmXkRnnISNyRObIMedce+/q6mqPqFp7zjlG3jMyIjIyIpKYmTHDDDPMMMMMM8wwwwwzzDDDDDPM8JTg3u0GzDDDDDPMMMMMM8wwwwwzzDDDDF8bMCsZZphhhhlmmGGGGWaYYYYZZphhhmcCs5JhhhlmmGGGGWaYYYYZZphhhhlmeCYwKxlmmGGGGWaYYYYZZphhhhlmmGGGZwKzkmGGGWaYYYYZZphhhhlmmGGGGWZ4JjArGWaYYYYZZphhhhlmmGGGGWaYYYZnArOSYYYZZphhhhlmmGGGGWaYYYYZZngmMCsZZphhhhlmmGGGGWaYYYYZZphhhmcCs5JhhhlmmGGGGWaYYYYZZphhhhlmeCYwKxlmmGGGGWaYYYYZZphhhhlmmGGGZwKzkmGGGZ4R/Mt/+S9BRPjv//2/v9tNAQBcXFzgk5/8JH7zN3/z4Dz/4B/8A/zFv/gX8dJLL4GI8MlPfvIda98MM8wwwwwzzPDegfe6nPPpT38aP/mT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DAAAAEAISQYAAAAghCQDAAAAEEKSAQAAAAghyQAAAACEkGQAAAAAQkgyAAAAACEkGQAAAIAQPzLkLh5MW42iAAAAAElFTkSuQmCC", + "text/plain": [ + "
" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "# Visualize input images and depth maps\n", + "n_images = prediction.depth.shape[0]\n", + "\n", + "fig, axes = plt.subplots(2, n_images, figsize=(12, 6))\n", + "\n", + "if n_images == 1:\n", + " axes = axes.reshape(2, 1)\n", + "\n", + "for i in range(n_images):\n", + " # Show original image\n", + " if prediction.processed_images is not None:\n", + " axes[0, i].imshow(prediction.processed_images[i])\n", + " axes[0, i].set_title(f\"Input {i+1}\")\n", + " axes[0, i].axis('off')\n", + " \n", + " # Show depth map\n", + " depth_vis = visualize_depth(prediction.depth[i], cmap=\"Spectral\")\n", + " axes[1, i].imshow(depth_vis)\n", + " axes[1, i].set_title(f\"Depth {i+1}\")\n", + " axes[1, i].axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.11.2" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/OVOW/engine/oneposeviagen/DA3/opg_freeze.txt b/OVOW/engine/oneposeviagen/DA3/opg_freeze.txt new file mode 100644 index 0000000000000000000000000000000000000000..a04b0c84f06a9b8f72b41120a6ce9221ae2f5678 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/opg_freeze.txt @@ -0,0 +1,265 @@ +accelerate==1.12.0 +addict==2.4.0 +aiofiles==24.1.0 +aiohappyeyeballs==2.6.1 +aiohttp==3.13.2 +aiohttp-cors==0.8.1 +aiosignal==1.4.0 +albucore==0.0.24 +albumentations==2.0.8 +# Editable install with no version control (amodal3r==0.1) +-e /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/Amodal3R +annotated-doc==0.0.4 +annotated-types==0.7.0 +antlr4-python3-runtime==4.9.3 +anyio==4.12.0 +asttokens==3.0.1 +attrs==25.4.0 +beautifulsoup4==4.14.3 +blinker==1.9.0 +cachetools==6.2.2 +ccimport==0.4.4 +certifi==2025.11.12 +charset-normalizer==3.4.4 +click==8.2.1 +coloredlogs==15.0.1 +colorful==0.5.8 +comm==0.2.3 +# Editable install with no version control (common==0.0.0) +-e /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/bundlesdf/mycuda +ConfigArgParse==1.7.1 +contourpy==1.3.3 +cumm-cu121==0.7.11 +cycler==0.12.1 +dash==3.3.0 +decorator==4.4.2 +decord==0.6.0 +deepspeed==0.18.2 +diff_gaussian_rasterization @ file:///mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/tmp/extensions/mip-splatting/submodules/diff-gaussian-rasterization +diffoctreerast @ file:///mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/tmp/extensions/diffoctreerast +distlib==0.4.0 +easydict==1.13 +einops==0.8.1 +einx==0.3.0 +executing==2.2.1 +fastapi==0.123.0 +fastjsonschema==2.21.2 +ffmpy==1.0.0 +filelock==3.20.0 +fire==0.7.1 +Flask==3.1.2 +flatbuffers==25.9.23 +flow-vis==0.1 +fonttools==4.61.0 +# Editable install with no version control (fpose==0.1) +-e /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose +frozendict==2.4.7 +frozenlist==1.8.0 +fsspec==2025.10.0 +gdown==5.2.0 +glcontext==3.0.0 +google-api-core==2.28.1 +google-auth==2.43.0 +googleapis-common-protos==1.72.0 +gradio==5.31.0 +gradio_client==1.10.1 +groovy==0.1.2 +grpcio==1.76.0 +h11==0.16.0 +h5py==3.15.1 +hf-xet==1.2.0 +hjson==3.1.0 +httpcore==1.0.9 +httpx==0.28.1 +huggingface-hub==0.36.0 +humanfriendly==10.0 +hydra-core==1.3.2 +idna==3.11 +igraph==1.0.0 +ImageIO==2.37.2 +imageio-ffmpeg==0.6.0 +importlib_metadata==8.7.0 +iopath==0.1.10 +ipython==9.7.0 +ipython_pygments_lexers==1.1.1 +ipywidgets==8.1.8 +itsdangerous==2.2.0 +jaxtyping==0.3.3 +jedi==0.19.2 +Jinja2==3.1.6 +joblib==1.5.2 +jsonschema==4.25.1 +jsonschema-specifications==2025.9.1 +jupyter_core==5.9.1 +jupyterlab_widgets==3.0.16 +kiwisolver==1.4.9 +kornia==0.8.1 +kornia_rs==0.1.10 +lark==1.3.1 +lazy_loader==0.4 +lightning-utilities==0.15.2 +llvmlite==0.45.1 +markdown-it-py==4.0.0 +MarkupSafe==3.0.3 +matplotlib==3.10.7 +matplotlib-inline==0.2.1 +mdurl==0.1.2 +mediapy==1.2.4 +# Editable install with no version control (models==0.1) +-e /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/SpaTrackerV2 +moderngl==5.12.0 +moviepy==1.0.0 +mpmath==1.3.0 +msgpack==1.1.2 +multidict==6.7.0 +narwhals==2.12.0 +nbformat==5.10.4 +nest-asyncio==1.6.0 +networkx==3.6 +ninja==1.13.0 +numba==0.62.1 +numpy==1.26.4 +nvdiffrast @ git+https://github.com/NVlabs/nvdiffrast@20c4135fda78ae29d7658bea28b6c1d5b5e103e5 +nvidia-cublas-cu12==12.1.3.1 +nvidia-cuda-cupti-cu12==12.1.105 +nvidia-cuda-nvrtc-cu12==12.1.105 +nvidia-cuda-runtime-cu12==12.1.105 +nvidia-cudnn-cu12==9.1.0.70 +nvidia-cufft-cu12==11.0.2.54 +nvidia-curand-cu12==10.3.2.106 +nvidia-cusolver-cu12==11.4.5.107 +nvidia-cusparse-cu12==12.1.0.106 +nvidia-ml-py==13.580.82 +nvidia-nccl-cu12==2.20.5 +nvidia-nvjitlink-cu12==12.9.86 +nvidia-nvtx-cu12==12.1.105 +nvitop==1.6.0 +omegaconf==2.3.0 +onnxruntime==1.23.2 +open3d==0.19.0 +opencensus==0.11.4 +opencensus-context==0.1.3 +opencv-python-headless==4.10.0.84 +opentelemetry-api==1.38.0 +opentelemetry-exporter-prometheus==0.59b0 +opentelemetry-proto==1.38.0 +opentelemetry-sdk==1.38.0 +opentelemetry-semantic-conventions==0.59b0 +orjson==3.11.4 +packaging @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_packaging_1745345660/work +pandas==2.3.3 +parso==0.8.5 +pccm==0.4.16 +peft==0.18.0 +pexpect==4.9.0 +pillow==11.3.0 +platformdirs==4.5.0 +plotly==6.5.0 +plyfile==1.1.3 +pooch==1.8.2 +portalocker==3.2.0 +prettytable==3.17.0 +proglog==0.1.12 +prometheus_client==0.23.1 +prompt_toolkit==3.0.52 +propcache==0.4.1 +proto-plus==1.26.1 +protobuf==6.33.1 +psutil==5.9.8 +ptyprocess==0.7.0 +pure_eval==0.2.3 +py-cpuinfo==9.0.0 +py-spy==0.4.1 +pyasn1==0.6.1 +pyasn1_modules==0.4.2 +pybind11==3.0.1 +pyceres==2.4 +pycolmap==3.11.1 +pydantic==2.10.6 +pydantic_core==2.27.2 +pydub==0.25.1 +Pygments==2.19.2 +PyJWT==2.10.1 +PyMatting==1.1.14 +pymeshfix==0.17.1 +pyparsing==3.2.5 +pyquaternion==0.9.9 +PySocks==1.7.1 +python-dateutil==2.9.0.post0 +python-multipart==0.0.20 +pytorch-lightning==2.6.0 +pytorch3d @ file:///mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/pytorch3d +pytz==2025.2 +pyvista==0.46.4 +PyYAML==6.0.3 +ray==2.52.1 +referencing==0.37.0 +regex==2025.11.3 +rembg==2.0.68 +requests==2.32.5 +retrying==1.4.2 +rich==14.2.0 +rpds-py==0.30.0 +rsa==4.9.1 +ruamel.yaml==0.18.6 +ruamel.yaml.clib==0.2.15 +ruff==0.14.7 +safehttpx==0.1.7 +safetensors==0.7.0 +SAM-2 @ file:///mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/SAM2-in-video +sam2==0.1.0 +scikit-image==0.25.2 +scikit-learn==1.7.2 +scipy==1.16.3 +scooby==0.11.0 +segment_anything @ git+https://github.com/facebookresearch/segment-anything.git@dca509fe793f601edb92606367a655c15ac00fdf +semantic-version==2.10.0 +shellingham==1.5.4 +simsimd==6.5.3 +six==1.17.0 +smart_open==7.5.0 +soupsieve==2.8 +spaces==0.43.0 +spconv-cu121==2.3.7 +stack-data==0.6.3 +starlette==0.50.0 +stringzilla==4.4.0 +sympy==1.14.0 +termcolor==3.2.0 +texttable==1.7.0 +threadpoolctl==3.6.0 +tifffile==2025.10.16 +timm==1.0.22 +tokenizers==0.22.1 +tomlkit==0.13.3 +torch==2.4.1+cu121 +torchaudio==2.4.1+cu121 +torchmetrics==1.8.2 +torchvision==0.19.1+cu121 +tqdm==4.67.1 +traitlets==5.14.3 +transformations==2024.6.1 +transformers==4.57.3 +# Editable install with no version control (trellis==0.1) +-e /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/trellis +trimesh==4.5.3 +triton==3.0.0 +typer==0.20.0 +typing_extensions==4.15.0 +tzdata==2025.2 +urllib3==2.5.0 +utils3d @ file:///mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/utils3d-0.0.2-py3-none-any.whl#sha256=45f60320229bda3e924f9d3ad45aa6f4e08c121f588635c0b22ff9d70142c6ef +uvicorn==0.38.0 +virtualenv==20.35.4 +vtk==9.5.2 +wadler_lindig==0.1.7 +warp-lang==1.0.2 +wcwidth==0.2.14 +websockets==15.0.1 +Werkzeug==3.1.4 +widgetsnbextension==4.0.15 +wrapt==2.0.1 +xatlas==0.0.11 +xformers==0.0.28 +yarl==1.22.0 +zipp==3.23.0 diff --git a/OVOW/engine/oneposeviagen/DA3/pyproject.toml b/OVOW/engine/oneposeviagen/DA3/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..6a11c7ae0e2978de8a726d3ac9e6668db0c5248a --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/pyproject.toml @@ -0,0 +1,94 @@ +[build-system] +requires = ["hatchling>=1.25", "hatch-vcs>=0.4"] +build-backend = "hatchling.build" + +[project] +name = "depth-anything-3" +version = "0.0.0" +description = "Depth Anything 3" +readme = "README.md" +requires-python = ">=3.9, <=3.13" +license = { text = "Apache-2.0" } +authors = [{ name = "Your Name" }] + +dependencies = [ + "pre-commit", + "trimesh", + "torch>=2", + "torchvision", + "einops", + "huggingface_hub", + "imageio", + "numpy<2", + "opencv-python", + "xformers", + "open3d", + "fastapi", + "uvicorn", + "requests", + "typer", + "pillow", + "omegaconf", + "evo", + "e3nn", + "moviepy", + "plyfile", + "pillow_heif", + "safetensors", + "uvicorn", + "moviepy==1.0.3", + "typer>=0.9.0", + "pycolmap", +] + +[project.optional-dependencies] +app = ["gradio>=5", "pillow>=9.0"] # requires that python3>=3.10 +gs = ["gsplat @ git+https://github.com/nerfstudio-project/gsplat.git@0b4dddf04cb687367602c01196913cde6a743d70"] +all = ["depth-anything-3[app,gs]"] + + +[project.scripts] +da3 = "depth_anything_3.cli:app" + +[project.urls] +Homepage = "https://github.com/ByteDance-Seed/Depth-Anything-3" + +[tool.hatch.version] +source = "vcs" + +[tool.hatch.build.targets.wheel] +packages = ["src/depth_anything_3"] + +[tool.hatch.build.targets.sdist] +include = [ + "/README.md", + "/pyproject.toml", + "/src/depth_anything_3", +] + +[tool.hatch.metadata] +allow-direct-references = true + +[tool.mypy] +plugins = ["jaxtyping.mypy_plugin"] + +[tool.black] +line-length = 99 +target-version = ['py37', 'py38', 'py39', 'py310', 'py311'] +include = '\.pyi?$' +exclude = ''' +/( + | \.git +)/ +''' + +[tool.isort] +profile = "black" +multi_line_output = 3 +include_trailing_comma = true +known_third_party = ["bson","cruise","cv2","dataloader","diffusers","omegaconf","tensorflow","torch","torchvision","transformers","gsplat"] +known_first_party = ["common", "data", "models", "projects"] +sections = ["FUTURE","STDLIB","THIRDPARTY","FIRSTPARTY","LOCALFOLDER"] +skip_gitignore = true +line_length = 99 +no_lines_before="THIRDPARTY" diff --git a/OVOW/engine/oneposeviagen/DA3/requirements.txt b/OVOW/engine/oneposeviagen/DA3/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..878db3f3cbb194289faa99b4c96c5e63488096c8 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/requirements.txt @@ -0,0 +1,24 @@ +pre-commit +trimesh +torch>=2 +torchvision +einops +huggingface_hub +imageio +numpy<2 +opencv-python +xformers +open3d +fastapi +uvicorn +requests +typer +pillow +omegaconf +evo +e3nn +moviepy +plyfile +pillow_heif +safetensors +pycolmap \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/api.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/api.py new file mode 100644 index 0000000000000000000000000000000000000000..d0f18aad68c6ded86a27952576064cca2aec59d4 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/api.py @@ -0,0 +1,446 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +Depth Anything 3 API module. + +This module provides the main API for Depth Anything 3, including model loading, +inference, and export capabilities. It supports both single and nested model architectures. +""" + +from __future__ import annotations + +import time +from typing import Optional, Sequence +import numpy as np +import torch +import torch.nn as nn +from huggingface_hub import PyTorchModelHubMixin +from PIL import Image + +from depth_anything_3.cfg import create_object, load_config +from depth_anything_3.registry import MODEL_REGISTRY +from depth_anything_3.specs import Prediction +from depth_anything_3.utils.export import export +from depth_anything_3.utils.geometry import affine_inverse +from depth_anything_3.utils.io.input_processor import InputProcessor +from depth_anything_3.utils.io.output_processor import OutputProcessor +from depth_anything_3.utils.logger import logger +from depth_anything_3.utils.pose_align import align_poses_umeyama + +torch.backends.cudnn.benchmark = False +# logger.info("CUDNN Benchmark Disabled") + +SAFETENSORS_NAME = "model.safetensors" +CONFIG_NAME = "config.json" + + +class DepthAnything3(nn.Module, PyTorchModelHubMixin): + """ + Depth Anything 3 main API class. + + This class provides a high-level interface for depth estimation using Depth Anything 3. + It supports both single and nested model architectures with metric scaling capabilities. + + Features: + - Hugging Face Hub integration via PyTorchModelHubMixin + - Support for multiple model presets (vitb, vitg, nested variants) + - Automatic mixed precision inference + - Export capabilities for various formats (GLB, PLY, NPZ, etc.) + - Camera pose estimation and metric depth scaling + + Usage: + # Load from Hugging Face Hub + model = DepthAnything3.from_pretrained("huggingface/model-name") + + # Or create with specific preset + model = DepthAnything3(preset="vitg") + + # Run inference + prediction = model.inference(images, export_dir="output", export_format="glb") + """ + + _commit_hash: str | None = None # Set by mixin when loading from Hub + + def __init__(self, model_name: str = "da3-large", **kwargs): + """ + Initialize DepthAnything3 with specified preset. + + Args: + model_name: The name of the model preset to use. + Examples: 'da3-giant', 'da3-large', 'da3metric-large', 'da3nested-giant-large'. + **kwargs: Additional keyword arguments (currently unused). + """ + super().__init__() + self.model_name = model_name + + # Build the underlying network + self.config = load_config(MODEL_REGISTRY[self.model_name]) + self.model = create_object(self.config) + self.model.eval() + + # Initialize processors + self.input_processor = InputProcessor() + self.output_processor = OutputProcessor() + + # Device management (set by user) + self.device = None + + @torch.inference_mode() + def forward( + self, + image: torch.Tensor, + extrinsics: torch.Tensor | None = None, + intrinsics: torch.Tensor | None = None, + export_feat_layers: list[int] | None = None, + infer_gs: bool = False, + use_ray_pose: bool = False, + ref_view_strategy: str = "saddle_balanced", + ) -> dict[str, torch.Tensor]: + """ + Forward pass through the model. + + Args: + image: Input batch with shape ``(B, N, 3, H, W)`` on the model device. + extrinsics: Optional camera extrinsics with shape ``(B, N, 4, 4)``. + intrinsics: Optional camera intrinsics with shape ``(B, N, 3, 3)``. + export_feat_layers: Layer indices to return intermediate features for. + infer_gs: Enable Gaussian Splatting branch. + use_ray_pose: Use ray-based pose estimation instead of camera decoder. + ref_view_strategy: Strategy for selecting reference view from multiple views. + + Returns: + Dictionary containing model predictions + """ + # Determine optimal autocast dtype + autocast_dtype = torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16 + with torch.no_grad(): + with torch.autocast(device_type=image.device.type, dtype=autocast_dtype): + return self.model( + image, extrinsics, intrinsics, export_feat_layers, infer_gs, use_ray_pose, ref_view_strategy + ) + + def inference( + self, + image: list[np.ndarray | Image.Image | str], + extrinsics: np.ndarray | None = None, + intrinsics: np.ndarray | None = None, + align_to_input_ext_scale: bool = True, + infer_gs: bool = False, + use_ray_pose: bool = False, + ref_view_strategy: str = "saddle_balanced", + render_exts: np.ndarray | None = None, + render_ixts: np.ndarray | None = None, + render_hw: tuple[int, int] | None = None, + process_res: int = 504, + process_res_method: str = "upper_bound_resize", + export_dir: str | None = None, + export_format: str = "mini_npz", + export_feat_layers: Sequence[int] | None = None, + # GLB export parameters + conf_thresh_percentile: float = 40.0, + num_max_points: int = 1_000_000, + show_cameras: bool = True, + # Feat_vis export parameters + feat_vis_fps: int = 15, + # Other export parameters, e.g., gs_ply, gs_video + export_kwargs: Optional[dict] = {}, + ) -> Prediction: + """ + Run inference on input images. + + Args: + image: List of input images (numpy arrays, PIL Images, or file paths) + extrinsics: Camera extrinsics (N, 4, 4) + intrinsics: Camera intrinsics (N, 3, 3) + align_to_input_ext_scale: whether to align the input pose scale to the prediction + infer_gs: Enable the 3D Gaussian branch (needed for `gs_ply`/`gs_video` exports) + use_ray_pose: Use ray-based pose estimation instead of camera decoder (default: False) + ref_view_strategy: Strategy for selecting reference view from multiple views. + Options: "first", "middle", "saddle_balanced", "saddle_sim_range". + Default: "saddle_balanced". For single view input (S ≤ 2), no reordering is performed. + render_exts: Optional render extrinsics for Gaussian video export + render_ixts: Optional render intrinsics for Gaussian video export + render_hw: Optional render resolution for Gaussian video export + process_res: Processing resolution + process_res_method: Resize method for processing + export_dir: Directory to export results + export_format: Export format (mini_npz, npz, glb, ply, gs, gs_video) + export_feat_layers: Layer indices to export intermediate features from + conf_thresh_percentile: [GLB] Lower percentile for adaptive confidence threshold (default: 40.0) # noqa: E501 + num_max_points: [GLB] Maximum number of points in the point cloud (default: 1,000,000) + show_cameras: [GLB] Show camera wireframes in the exported scene (default: True) + feat_vis_fps: [FEAT_VIS] Frame rate for output video (default: 15) + export_kwargs: additional arguments to export functions. + + Returns: + Prediction object containing depth maps and camera parameters + """ + if "gs" in export_format: + assert infer_gs, "must set `infer_gs=True` to perform gs-related export." + + if "colmap" in export_format: + assert isinstance(image[0], str), "`image` must be image paths for COLMAP export." + + # Preprocess images + imgs_cpu, extrinsics, intrinsics = self._preprocess_inputs( + image, extrinsics, intrinsics, process_res, process_res_method + ) + + # Prepare tensors for model + imgs, ex_t, in_t = self._prepare_model_inputs(imgs_cpu, extrinsics, intrinsics) + + # Normalize extrinsics + ex_t_norm = self._normalize_extrinsics(ex_t.clone() if ex_t is not None else None) + + # Run model forward pass + export_feat_layers = list(export_feat_layers) if export_feat_layers is not None else [] + + raw_output = self._run_model_forward( + imgs, ex_t_norm, in_t, export_feat_layers, infer_gs, use_ray_pose, ref_view_strategy + ) + + # Convert raw output to prediction + prediction = self._convert_to_prediction(raw_output) + + # Align prediction to extrinsincs + prediction = self._align_to_input_extrinsics_intrinsics( + extrinsics, intrinsics, prediction, align_to_input_ext_scale + ) + + # Add processed images for visualization + prediction = self._add_processed_images(prediction, imgs_cpu) + + # Export if requested + if export_dir is not None: + + if "gs" in export_format: + if infer_gs and "gs_video" not in export_format: + export_format = f"{export_format}-gs_video" + if "gs_video" in export_format: + if "gs_video" not in export_kwargs: + export_kwargs["gs_video"] = {} + export_kwargs["gs_video"].update( + { + "extrinsics": render_exts, + "intrinsics": render_ixts, + "out_image_hw": render_hw, + } + ) + # Add GLB export parameters + if "glb" in export_format: + if "glb" not in export_kwargs: + export_kwargs["glb"] = {} + export_kwargs["glb"].update( + { + "conf_thresh_percentile": conf_thresh_percentile, + "num_max_points": num_max_points, + "show_cameras": show_cameras, + } + ) + # Add Feat_vis export parameters + if "feat_vis" in export_format: + if "feat_vis" not in export_kwargs: + export_kwargs["feat_vis"] = {} + export_kwargs["feat_vis"].update( + { + "fps": feat_vis_fps, + } + ) + # Add COLMAP export parameters + if "colmap" in export_format: + if "colmap" not in export_kwargs: + export_kwargs["colmap"] = {} + export_kwargs["colmap"].update( + { + "image_paths": image, + "conf_thresh_percentile": conf_thresh_percentile, + "process_res_method": process_res_method, + } + ) + self._export_results(prediction, export_format, export_dir, **export_kwargs) + + return prediction + + def _preprocess_inputs( + self, + image: list[np.ndarray | Image.Image | str], + extrinsics: np.ndarray | None = None, + intrinsics: np.ndarray | None = None, + process_res: int = 504, + process_res_method: str = "upper_bound_resize", + ) -> tuple[torch.Tensor, torch.Tensor | None, torch.Tensor | None]: + """Preprocess input images using input processor.""" + start_time = time.time() + imgs_cpu, extrinsics, intrinsics = self.input_processor( + image, + extrinsics.copy() if extrinsics is not None else None, + intrinsics.copy() if intrinsics is not None else None, + process_res, + process_res_method, + ) + end_time = time.time() + logger.info( + "Processed Images Done taking", + end_time - start_time, + "seconds. Shape: ", + imgs_cpu.shape, + ) + return imgs_cpu, extrinsics, intrinsics + + def _prepare_model_inputs( + self, + imgs_cpu: torch.Tensor, + extrinsics: torch.Tensor | None, + intrinsics: torch.Tensor | None, + ) -> tuple[torch.Tensor, torch.Tensor | None, torch.Tensor | None]: + """Prepare tensors for model input.""" + device = self._get_model_device() + + # Move images to model device + imgs = imgs_cpu.to(device, non_blocking=True)[None].float() + + # Convert camera parameters to tensors + ex_t = ( + extrinsics.to(device, non_blocking=True)[None].float() + if extrinsics is not None + else None + ) + in_t = ( + intrinsics.to(device, non_blocking=True)[None].float() + if intrinsics is not None + else None + ) + + return imgs, ex_t, in_t + + def _normalize_extrinsics(self, ex_t: torch.Tensor | None) -> torch.Tensor | None: + """Normalize extrinsics""" + if ex_t is None: + return None + transform = affine_inverse(ex_t[:, :1]) + ex_t_norm = ex_t @ transform + c2ws = affine_inverse(ex_t_norm) + translations = c2ws[..., :3, 3] + dists = translations.norm(dim=-1) + median_dist = torch.median(dists) + median_dist = torch.clamp(median_dist, min=1e-1) + ex_t_norm[..., :3, 3] = ex_t_norm[..., :3, 3] / median_dist + return ex_t_norm + + def _align_to_input_extrinsics_intrinsics( + self, + extrinsics: torch.Tensor | None, + intrinsics: torch.Tensor | None, + prediction: Prediction, + align_to_input_ext_scale: bool = True, + ransac_view_thresh: int = 10, + ) -> Prediction: + """Align depth map to input extrinsics""" + if extrinsics is None: + return prediction + prediction.intrinsics = intrinsics.numpy() + _, _, scale, aligned_extrinsics = align_poses_umeyama( + prediction.extrinsics, + extrinsics.numpy(), + ransac=len(extrinsics) >= ransac_view_thresh, + return_aligned=True, + random_state=42, + ) + if align_to_input_ext_scale: + prediction.extrinsics = extrinsics[..., :3, :].numpy() + prediction.depth /= scale + else: + prediction.extrinsics = aligned_extrinsics + return prediction + + def _run_model_forward( + self, + imgs: torch.Tensor, + ex_t: torch.Tensor | None, + in_t: torch.Tensor | None, + export_feat_layers: Sequence[int] | None = None, + infer_gs: bool = False, + use_ray_pose: bool = False, + ref_view_strategy: str = "saddle_balanced", + ) -> dict[str, torch.Tensor]: + """Run model forward pass.""" + device = imgs.device + need_sync = device.type == "cuda" + if need_sync: + torch.cuda.synchronize(device) + start_time = time.time() + feat_layers = list(export_feat_layers) if export_feat_layers is not None else None + output = self.forward(imgs, ex_t, in_t, feat_layers, infer_gs, use_ray_pose, ref_view_strategy) + if need_sync: + torch.cuda.synchronize(device) + end_time = time.time() + logger.info(f"Model Forward Pass Done. Time: {end_time - start_time} seconds") + return output + + def _convert_to_prediction(self, raw_output: dict[str, torch.Tensor]) -> Prediction: + """Convert raw model output to Prediction object.""" + start_time = time.time() + output = self.output_processor(raw_output) + end_time = time.time() + logger.info(f"Conversion to Prediction Done. Time: {end_time - start_time} seconds") + return output + + def _add_processed_images(self, prediction: Prediction, imgs_cpu: torch.Tensor) -> Prediction: + """Add processed images to prediction for visualization.""" + # Convert from (N, 3, H, W) to (N, H, W, 3) and denormalize + processed_imgs = imgs_cpu.permute(0, 2, 3, 1).cpu().numpy() # (N, H, W, 3) + + # Denormalize from ImageNet normalization + mean = np.array([0.485, 0.456, 0.406]) + std = np.array([0.229, 0.224, 0.225]) + processed_imgs = processed_imgs * std + mean + processed_imgs = np.clip(processed_imgs, 0, 1) + processed_imgs = (processed_imgs * 255).astype(np.uint8) + + prediction.processed_images = processed_imgs + return prediction + + def _export_results( + self, prediction: Prediction, export_format: str, export_dir: str, **kwargs + ) -> None: + """Export results to specified format and directory.""" + start_time = time.time() + export(prediction, export_format, export_dir, **kwargs) + end_time = time.time() + logger.info(f"Export Results Done. Time: {end_time - start_time} seconds") + + def _get_model_device(self) -> torch.device: + """ + Get the device where the model is located. + + Returns: + Device where the model parameters are located + + Raises: + ValueError: If no tensors are found in the model + """ + if self.device is not None: + return self.device + + # Find device from parameters + for param in self.parameters(): + self.device = param.device + return param.device + + # Find device from buffers + for buffer in self.buffers(): + self.device = buffer.device + return buffer.device + + raise ValueError("No tensor found in model") diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/app/css_and_html.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/app/css_and_html.py new file mode 100644 index 0000000000000000000000000000000000000000..d414df9db72a4a395bc15d87ff4edbeb213f18bb --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/app/css_and_html.py @@ -0,0 +1,594 @@ +# flake8: noqa: E501 + +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +CSS and HTML content for the Depth Anything 3 Gradio application. +This module contains all the CSS styles and HTML content blocks +used in the Gradio interface. +""" + +# CSS Styles for the Gradio interface +GRADIO_CSS = """ +/* Add Font Awesome CDN with all styles including brands and colors */ +@import url('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css'); + +/* Add custom styles for colored icons */ +.fa-color-blue { + color: #3b82f6; +} + +.fa-color-purple { + color: #8b5cf6; +} + +.fa-color-cyan { + color: #06b6d4; +} + +.fa-color-green { + color: #10b981; +} + +.fa-color-yellow { + color: #f59e0b; +} + +.fa-color-red { + color: #ef4444; +} + +.link-btn { + display: inline-flex; + align-items: center; + gap: 8px; + text-decoration: none; + padding: 12px 24px; + border-radius: 50px; + font-weight: 500; + transition: all 0.3s ease; +} + +/* Dark mode tech theme */ +@media (prefers-color-scheme: dark) { + html, body { + background: #1e293b; + color: #ffffff; + } + + .gradio-container { + background: #1e293b; + color: #ffffff; + } + + .link-btn { + background: rgba(255, 255, 255, 0.2); + color: white; + backdrop-filter: blur(10px); + border: 1px solid rgba(255, 255, 255, 0.3); + } + + .link-btn:hover { + background: rgba(255, 255, 255, 0.3); + transform: translateY(-2px); + box-shadow: 0 8px 25px rgba(0, 0, 0, 0.2); + } + + .tech-bg { + background: linear-gradient(135deg, #0f172a, #1e293b); /* Darker colors */ + position: relative; + overflow: hidden; + } + + .tech-bg::before { + content: ''; + position: absolute; + top: 0; + left: 0; + right: 0; + bottom: 0; + background: + radial-gradient(circle at 20% 80%, rgba(59, 130, 246, 0.15) 0%, transparent 50%), /* Reduced opacity */ + radial-gradient(circle at 80% 20%, rgba(139, 92, 246, 0.15) 0%, transparent 50%), /* Reduced opacity */ + radial-gradient(circle at 40% 40%, rgba(18, 194, 233, 0.1) 0%, transparent 50%); /* Reduced opacity */ + animation: techPulse 8s ease-in-out infinite; + } + + .gradio-container .panel, + .gradio-container .block, + .gradio-container .form { + background: rgba(0, 0, 0, 0.3); + border: 1px solid rgba(59, 130, 246, 0.2); + border-radius: 10px; + } + + .gradio-container * { + color: #ffffff; + } + + .gradio-container label { + color: #e0e0e0; + } + + .gradio-container .markdown { + color: #e0e0e0; + } +} + +/* Light mode tech theme */ +@media (prefers-color-scheme: light) { + html, body { + background: #ffffff; + color: #1e293b; + } + + .gradio-container { + background: #ffffff; + color: #1e293b; + } + + .tech-bg { + background: linear-gradient(135deg, #ffffff, #f1f5f9); + position: relative; + overflow: hidden; + } + + .link-btn { + background: rgba(59, 130, 246, 0.15); + color: var(--body-text-color); + border: 1px solid rgba(59, 130, 246, 0.3); + } + + .link-btn:hover { + background: rgba(59, 130, 246, 0.25); + transform: translateY(-2px); + box-shadow: 0 8px 25px rgba(59, 130, 246, 0.2); + } + + .tech-bg::before { + content: ''; + position: absolute; + top: 0; + left: 0; + right: 0; + bottom: 0; + background: + radial-gradient(circle at 20% 80%, rgba(59, 130, 246, 0.1) 0%, transparent 50%), + radial-gradient(circle at 80% 20%, rgba(139, 92, 246, 0.1) 0%, transparent 50%), + radial-gradient(circle at 40% 40%, rgba(18, 194, 233, 0.08) 0%, transparent 50%); + animation: techPulse 8s ease-in-out infinite; + } + + .gradio-container .panel, + .gradio-container .block, + .gradio-container .form { + background: rgba(255, 255, 255, 0.8); + border: 1px solid rgba(59, 130, 246, 0.3); + border-radius: 10px; + box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); + } + + .gradio-container * { + color: #1e293b; + } + + .gradio-container label { + color: #334155; + } + + .gradio-container .markdown { + color: #334155; + } +} + + + + +@keyframes techPulse { + 0%, 100% { opacity: 0.5; } + 50% { opacity: 0.8; } +} + +/* Custom log with tech gradient */ +.custom-log * { + font-style: italic; + font-size: 22px !important; + background: linear-gradient(135deg, #3b82f6, #8b5cf6); + background-size: 400% 400%; + -webkit-background-clip: text; + background-clip: text; + font-weight: bold !important; + color: transparent !important; + text-align: center !important; + animation: techGradient 3s ease infinite; +} + +@keyframes techGradient { + 0% { background-position: 0% 50%; } + 50% { background-position: 100% 50%; } + 100% { background-position: 0% 50%; } +} + +@keyframes metricPulse { + 0%, 100% { background-position: 0% 50%; } + 50% { background-position: 100% 50%; } +} + +@keyframes pointcloudPulse { + 0%, 100% { background-position: 0% 50%; } + 50% { background-position: 100% 50%; } +} + +@keyframes camerasPulse { + 0%, 100% { background-position: 0% 50%; } + 50% { background-position: 100% 50%; } +} + +@keyframes gaussiansPulse { + 0%, 100% { background-position: 0% 50%; } + 50% { background-position: 100% 50%; } +} + +/* Special colors for key terms - Global styles */ +.metric-text { + background: linear-gradient(45deg, #ff6b6b, #ff8e53, #ff6b6b); + background-size: 200% 200%; + -webkit-background-clip: text; + background-clip: text; + color: transparent !important; + animation: metricPulse 2s ease-in-out infinite; + font-weight: 700; + text-shadow: 0 0 10px rgba(255, 107, 107, 0.5); +} + +.pointcloud-text { + background: linear-gradient(45deg, #4ecdc4, #44a08d, #4ecdc4); + background-size: 200% 200%; + -webkit-background-clip: text; + background-clip: text; + color: transparent !important; + animation: pointcloudPulse 2.5s ease-in-out infinite; + font-weight: 700; + text-shadow: 0 0 10px rgba(78, 205, 196, 0.5); +} + +.cameras-text { + background: linear-gradient(45deg, #667eea, #764ba2, #667eea); + background-size: 200% 200%; + -webkit-background-clip: text; + background-clip: text; + color: transparent !important; + animation: camerasPulse 3s ease-in-out infinite; + font-weight: 700; + text-shadow: 0 0 10px rgba(102, 126, 234, 0.5); +} + +.gaussians-text { + background: linear-gradient(45deg, #f093fb, #f5576c, #f093fb); + background-size: 200% 200%; + -webkit-background-clip: text; + background-clip: text; + color: transparent !important; + animation: gaussiansPulse 2.2s ease-in-out infinite; + font-weight: 700; + text-shadow: 0 0 10px rgba(240, 147, 251, 0.5); +} + +.example-log * { + font-style: italic; + font-size: 16px !important; + background: linear-gradient(135deg, #3b82f6, #8b5cf6); + -webkit-background-clip: text; + background-clip: text; + color: transparent !important; +} + +#my_radio .wrap { + display: flex; + flex-wrap: nowrap; + justify-content: center; + align-items: center; +} + +#my_radio .wrap label { + display: flex; + width: 50%; + justify-content: center; + align-items: center; + margin: 0; + padding: 10px 0; + box-sizing: border-box; +} + +/* Align navigation buttons with dropdown bottom */ +.navigation-row { + display: flex !important; + align-items: flex-end !important; + gap: 8px !important; +} + +.navigation-row > div:nth-child(1), +.navigation-row > div:nth-child(3) { + align-self: flex-end !important; +} + +.navigation-row > div:nth-child(2) { + flex: 1 !important; +} + +/* Make thumbnails clickable with pointer cursor */ +.clickable-thumbnail img { + cursor: pointer !important; +} + +.clickable-thumbnail:hover img { + cursor: pointer !important; + opacity: 0.8; + transition: opacity 0.3s ease; +} + +/* Make thumbnail containers narrower horizontally */ +.clickable-thumbnail { + padding: 5px 2px !important; + margin: 0 2px !important; +} + +.clickable-thumbnail .image-container { + margin: 0 !important; + padding: 0 !important; +} + +.scene-info { + text-align: center !important; + padding: 5px 2px !important; + margin: 0 !important; +} +""" + + +def get_header_html(logo_base64=None): + """ + Generate the main header HTML with logo and title. + + Args: + logo_base64 (str, optional): Base64 encoded logo image + + Returns: + str: HTML string for the header + """ + return """ +
+
+

+ Depth Anything 3 +

+

+ Recovering the Visual Space from Any Views +

+ +
+
+ + + """ + + +def get_description_html(): + """ + Generate the main description and getting started HTML. + + Returns: + str: HTML string for the description + """ + return """ +
+

+ What This Demo Does +

+
+

+ Upload images or videos → Get Metric Point Clouds, Cameras and Novel Views → Explore in 3D +

+
+ +
+

+ Tip: Landscape-oriented images or videos are preferred for best 3D recovering. +

+
+
+ + + """ + + +def get_acknowledgements_html(): + """ + Generate the acknowledgements section HTML. + + Returns: + str: HTML string for the acknowledgements + """ + return """ +
+

+ Research Credits & Acknowledgments +

+ +
+ +
+

Original Research

+

+ + Depth Anything 3 + +

+
+ + +
+

Previous Versions

+ +
+
+ + +
+

+ HF demo adapted from Map Anything +

+
+
+ """ + + +def get_gradio_theme(): + """ + Get the configured Gradio theme with adaptive tech colors. + + Returns: + gr.themes.Base: Configured Gradio theme + """ + import gradio as gr + + return gr.themes.Base( + primary_hue=gr.themes.Color( + c50="#eff6ff", + c100="#dbeafe", + c200="#bfdbfe", + c300="#93c5fd", + c400="#60a5fa", + c500="#3b82f6", + c600="#2563eb", + c700="#1d4ed8", + c800="#1e40af", + c900="#1e3a8a", + c950="#172554", + ), + secondary_hue=gr.themes.Color( + c50="#f5f3ff", + c100="#ede9fe", + c200="#ddd6fe", + c300="#c4b5fd", + c400="#a78bfa", + c500="#8b5cf6", + c600="#7c3aed", + c700="#6d28d9", + c800="#5b21b6", + c900="#4c1d95", + c950="#2e1065", + ), + neutral_hue=gr.themes.Color( + c50="#f8fafc", + c100="#f1f5f9", + c200="#e2e8f0", + c300="#cbd5e1", + c400="#94a3b8", + c500="#64748b", + c600="#475569", + c700="#334155", + c800="#1e293b", + c900="#0f172a", + c950="#020617", + ), + ) + + +# Measure tab instructions HTML +MEASURE_INSTRUCTIONS_HTML = """ +### Click points on the image to compute distance. +> Metric scale estimation is difficult on aerial/drone images. +""" diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/app/gradio_app.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/app/gradio_app.py new file mode 100644 index 0000000000000000000000000000000000000000..ef188c0994c3562ef0671e2ff918a534566d38ca --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/app/gradio_app.py @@ -0,0 +1,724 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Refactored Gradio App for Depth Anything 3. + +This is the main application file that orchestrates all components. +The original functionality has been split into modular components for better maintainability. +""" + +import argparse +import os +from typing import Any, Dict, List +import gradio as gr + +from depth_anything_3.app.css_and_html import GRADIO_CSS, get_gradio_theme +from depth_anything_3.app.modules.event_handlers import EventHandlers +from depth_anything_3.app.modules.ui_components import UIComponents + +# Set environment variables +os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True" + + +class DepthAnything3App: + """ + Main application class for Depth Anything 3 Gradio app. + """ + + def __init__(self, model_dir: str = None, workspace_dir: str = None, gallery_dir: str = None): + """ + Initialize the application. + + Args: + model_dir: Path to the model directory + workspace_dir: Path to the workspace directory + gallery_dir: Path to the gallery directory + """ + self.model_dir = model_dir + self.workspace_dir = workspace_dir + self.gallery_dir = gallery_dir + + # Set environment variables for directories + if self.model_dir: + os.environ["DA3_MODEL_DIR"] = self.model_dir + if self.workspace_dir: + os.environ["DA3_WORKSPACE_DIR"] = self.workspace_dir + if self.gallery_dir: + os.environ["DA3_GALLERY_DIR"] = self.gallery_dir + + self.event_handlers = EventHandlers() + self.ui_components = UIComponents() + + def cache_examples( + self, + show_cam: bool = True, + filter_black_bg: bool = False, + filter_white_bg: bool = False, + save_percentage: float = 20.0, + num_max_points: int = 1000, + cache_gs_tag: str = "", + gs_trj_mode: str = "smooth", + gs_video_quality: str = "low", + ) -> None: + """ + Pre-cache all example scenes at startup. + + Args: + show_cam: Whether to show camera in visualization + filter_black_bg: Whether to filter black background + filter_white_bg: Whether to filter white background + save_percentage: Filter percentage for point cloud + num_max_points: Maximum number of points + cache_gs_tag: Tag to match scene names for high-res+3DGS caching (e.g., "dl3dv") + gs_trj_mode: Trajectory mode for 3DGS + gs_video_quality: Video quality for 3DGS + """ + from depth_anything_3.app.modules.utils import get_scene_info + + examples_dir = os.path.join(self.workspace_dir, "examples") + if not os.path.exists(examples_dir): + print(f"Examples directory not found: {examples_dir}") + return + + scenes = get_scene_info(examples_dir) + if not scenes: + print("No example scenes found to cache.") + return + + print(f"\n{'='*60}") + print(f"Caching {len(scenes)} example scenes...") + print(f"{'='*60}\n") + + for i, scene in enumerate(scenes, 1): + scene_name = scene["name"] + + # Check if scene name matches the gs tag for high-res+3DGS caching + use_high_res_gs = cache_gs_tag and cache_gs_tag.lower() in scene_name.lower() + + if use_high_res_gs: + print(f"[{i}/{len(scenes)}] Caching scene: {scene_name} (HIGH-RES + 3DGS)") + print(f" - Number of images: {scene['num_images']}") + print(f" - Matched tag: '{cache_gs_tag}' - using high_res + 3DGS") + else: + print(f"[{i}/{len(scenes)}] Caching scene: {scene_name} (LOW-RES)") + print(f" - Number of images: {scene['num_images']}") + + try: + # Load example scene + _, target_dir, _, _, _, _, _, _, _ = self.event_handlers.load_example_scene( + scene_name + ) + + if target_dir and target_dir != "None": + # Run reconstruction with appropriate settings + print(" - Running reconstruction...") + result = self.event_handlers.gradio_demo( + target_dir=target_dir, + show_cam=show_cam, + filter_black_bg=filter_black_bg, + filter_white_bg=filter_white_bg, + process_res_method="high_res" if use_high_res_gs else "low_res", + save_percentage=save_percentage, + num_max_points=num_max_points, + infer_gs=use_high_res_gs, + ref_view_strategy="saddle_balanced", + gs_trj_mode=gs_trj_mode, + gs_video_quality=gs_video_quality, + ) + + # Check if successful + if result[0] is not None: # reconstruction_output + print(f" ✓ Scene '{scene_name}' cached successfully") + else: + print(f" ✗ Scene '{scene_name}' caching failed: {result[1]}") + else: + print(f" ✗ Scene '{scene_name}' loading failed") + + except Exception as e: + print(f" ✗ Error caching scene '{scene_name}': {str(e)}") + + print() + + print("=" * 60) + print("Example scene caching completed!") + print("=" * 60 + "\n") + + def create_app(self) -> gr.Blocks: + """ + Create and configure the Gradio application. + + Returns: + Configured Gradio Blocks interface + """ + + # Initialize theme + def get_theme(): + return get_gradio_theme() + + with gr.Blocks(theme=get_theme(), css=GRADIO_CSS) as demo: + # State variables for the tabbed interface + is_example = gr.Textbox(label="is_example", visible=False, value="None") + processed_data_state = gr.State(value=None) + measure_points_state = gr.State(value=[]) + selected_image_index_state = gr.State(value=0) # Track selected image index + # current_view_index = gr.State(value=0) # noqa: F841 Track current view index + + # Header and description + self.ui_components.create_header_section() + self.ui_components.create_description_section() + + target_dir_output = gr.Textbox(label="Target Dir", visible=False, value="None") + + # Main content area + with gr.Row(): + with gr.Column(scale=2): + # Upload section + ( + input_video, + s_time_interval, + input_images, + image_gallery, + ) = self.ui_components.create_upload_section() + + with gr.Column(scale=4): + with gr.Column(): + # gr.Markdown("**Metric 3D Reconstruction (Point Cloud and Camera Poses)**") + # Reconstruction control section (buttons) - moved below tabs + + log_output = gr.Markdown( + "Please upload a video or images, then click Reconstruct.", + elem_classes=["custom-log"], + ) + + # Tabbed interface + with gr.Tabs(): + with gr.Tab("Point Cloud & Cameras"): + reconstruction_output = ( + self.ui_components.create_3d_viewer_section() + ) + + with gr.Tab("Metric Depth"): + ( + prev_measure_btn, + measure_view_selector, + next_measure_btn, + measure_image, + measure_depth_image, + measure_text, + ) = self.ui_components.create_measure_section() + + with gr.Tab("3DGS Rendered Novel Views"): + gs_video, gs_info = self.ui_components.create_nvs_video() + + # Inference control section (before inference) + (process_res_method_dropdown, infer_gs, ref_view_strategy_dropdown) = ( + self.ui_components.create_inference_control_section() + ) + + # Display control section - includes 3DGS options, buttons, and Visualization Options # noqa: E501 + ( + show_cam, + filter_black_bg, + filter_white_bg, + save_percentage, + num_max_points, + gs_trj_mode, + gs_video_quality, + submit_btn, + clear_btn, + ) = self.ui_components.create_display_control_section() + + # bind visibility of gs_trj_mode to infer_gs + infer_gs.change( + fn=lambda checked: ( + gr.update(visible=checked), + gr.update(visible=checked), + gr.update(visible=checked), + gr.update(visible=(not checked)), + ), + inputs=infer_gs, + outputs=[gs_trj_mode, gs_video_quality, gs_video, gs_info], + ) + + # Example scenes section + gr.Markdown("## Example Scenes") + + scenes = self.ui_components.create_example_scenes_section() + scene_components = self.ui_components.create_example_scene_grid(scenes) + + # Set up event handlers + self._setup_event_handlers( + demo, + is_example, + processed_data_state, + measure_points_state, + target_dir_output, + input_video, + input_images, + s_time_interval, + image_gallery, + reconstruction_output, + log_output, + show_cam, + filter_black_bg, + filter_white_bg, + process_res_method_dropdown, + save_percentage, + submit_btn, + clear_btn, + num_max_points, + infer_gs, + ref_view_strategy_dropdown, + selected_image_index_state, + measure_view_selector, + measure_image, + measure_depth_image, + measure_text, + prev_measure_btn, + next_measure_btn, + scenes, + scene_components, + gs_video, + gs_info, + gs_trj_mode, + gs_video_quality, + ) + + # Acknowledgements + self.ui_components.create_acknowledgements_section() + + return demo + + def _setup_event_handlers( + self, + demo: gr.Blocks, + is_example: gr.Textbox, + processed_data_state: gr.State, + measure_points_state: gr.State, + target_dir_output: gr.Textbox, + input_video: gr.Video, + input_images: gr.File, + s_time_interval: gr.Slider, + image_gallery: gr.Gallery, + reconstruction_output: gr.Model3D, + log_output: gr.Markdown, + show_cam: gr.Checkbox, + filter_black_bg: gr.Checkbox, + filter_white_bg: gr.Checkbox, + process_res_method_dropdown: gr.Dropdown, + save_percentage: gr.Slider, + submit_btn: gr.Button, + clear_btn: gr.ClearButton, + num_max_points: gr.Slider, + infer_gs: gr.Checkbox, + ref_view_strategy_dropdown: gr.Dropdown, + selected_image_index_state: gr.State, + measure_view_selector: gr.Dropdown, + measure_image: gr.Image, + measure_depth_image: gr.Image, + measure_text: gr.Markdown, + prev_measure_btn: gr.Button, + next_measure_btn: gr.Button, + scenes: List[Dict[str, Any]], + scene_components: List[gr.Image], + gs_video: gr.Video, + gs_info: gr.Markdown, + gs_trj_mode: gr.Dropdown, + gs_video_quality: gr.Dropdown, + ) -> None: + """ + Set up all event handlers for the application. + + Args: + demo: Gradio Blocks interface + All other arguments: Gradio components to connect + """ + # Configure clear button + clear_btn.add( + [ + input_video, + input_images, + reconstruction_output, + log_output, + target_dir_output, + image_gallery, + gs_video, + ] + ) + + # Main reconstruction button + submit_btn.click( + fn=self.event_handlers.clear_fields, inputs=[], outputs=[reconstruction_output] + ).then(fn=self.event_handlers.update_log, inputs=[], outputs=[log_output]).then( + fn=self.event_handlers.gradio_demo, + inputs=[ + target_dir_output, + show_cam, + filter_black_bg, + filter_white_bg, + process_res_method_dropdown, + save_percentage, + # pass num_max_points + num_max_points, + infer_gs, + ref_view_strategy_dropdown, + gs_trj_mode, + gs_video_quality, + ], + outputs=[ + reconstruction_output, + log_output, + processed_data_state, + measure_image, + measure_depth_image, + measure_text, + measure_view_selector, + gs_video, + gs_video, # gs_video visibility + gs_info, # gs_info visibility + ], + ).then( + fn=lambda: "False", + inputs=[], + outputs=[is_example], # set is_example to "False" + ) + + # Real-time visualization updates + self._setup_visualization_handlers( + show_cam, + filter_black_bg, + filter_white_bg, + process_res_method_dropdown, + target_dir_output, + is_example, + reconstruction_output, + log_output, + ) + + # File upload handlers + input_video.change( + fn=self.event_handlers.handle_uploads, + inputs=[input_video, input_images, s_time_interval], + outputs=[reconstruction_output, target_dir_output, image_gallery, log_output], + ) + input_images.change( + fn=self.event_handlers.handle_uploads, + inputs=[input_video, input_images, s_time_interval], + outputs=[reconstruction_output, target_dir_output, image_gallery, log_output], + ) + + # Navigation handlers + self._setup_navigation_handlers( + prev_measure_btn, + next_measure_btn, + measure_view_selector, + measure_image, + measure_depth_image, + measure_points_state, + processed_data_state, + ) + + # Measurement handler + measure_image.select( + fn=self.event_handlers.measure, + inputs=[processed_data_state, measure_points_state, measure_view_selector], + outputs=[measure_image, measure_depth_image, measure_points_state, measure_text], + ) + + # Example scene handlers + self._setup_example_scene_handlers( + scenes, + scene_components, + reconstruction_output, + target_dir_output, + image_gallery, + log_output, + is_example, + processed_data_state, + measure_view_selector, + measure_image, + measure_depth_image, + gs_video, + gs_info, + ) + + def _setup_visualization_handlers( + self, + show_cam: gr.Checkbox, + filter_black_bg: gr.Checkbox, + filter_white_bg: gr.Checkbox, + process_res_method_dropdown: gr.Dropdown, + target_dir_output: gr.Textbox, + is_example: gr.Textbox, + reconstruction_output: gr.Model3D, + log_output: gr.Markdown, + ) -> None: + """Set up visualization update handlers.""" + # Common inputs for visualization updates + viz_inputs = [ + target_dir_output, + show_cam, + is_example, + filter_black_bg, + filter_white_bg, + process_res_method_dropdown, + ] + + # Set up change handlers for all visualization controls + for component in [show_cam, filter_black_bg, filter_white_bg]: + component.change( + fn=self.event_handlers.update_visualization, + inputs=viz_inputs, + outputs=[reconstruction_output, log_output], + ) + + def _setup_navigation_handlers( + self, + prev_measure_btn: gr.Button, + next_measure_btn: gr.Button, + measure_view_selector: gr.Dropdown, + measure_image: gr.Image, + measure_depth_image: gr.Image, + measure_points_state: gr.State, + processed_data_state: gr.State, + ) -> None: + """Set up navigation handlers for measure tab.""" + # Measure tab navigation + prev_measure_btn.click( + fn=lambda processed_data, current_selector: self.event_handlers.navigate_measure_view( + processed_data, current_selector, -1 + ), + inputs=[processed_data_state, measure_view_selector], + outputs=[ + measure_view_selector, + measure_image, + measure_depth_image, + measure_points_state, + ], + ) + + next_measure_btn.click( + fn=lambda processed_data, current_selector: self.event_handlers.navigate_measure_view( + processed_data, current_selector, 1 + ), + inputs=[processed_data_state, measure_view_selector], + outputs=[ + measure_view_selector, + measure_image, + measure_depth_image, + measure_points_state, + ], + ) + + measure_view_selector.change( + fn=lambda processed_data, selector_value: ( + self.event_handlers.update_measure_view( + processed_data, int(selector_value.split()[1]) - 1 + ) + if selector_value + else (None, None, []) + ), + inputs=[processed_data_state, measure_view_selector], + outputs=[measure_image, measure_depth_image, measure_points_state], + ) + + def _setup_example_scene_handlers( + self, + scenes: List[Dict[str, Any]], + scene_components: List[gr.Image], + reconstruction_output: gr.Model3D, + target_dir_output: gr.Textbox, + image_gallery: gr.Gallery, + log_output: gr.Markdown, + is_example: gr.Textbox, + processed_data_state: gr.State, + measure_view_selector: gr.Dropdown, + measure_image: gr.Image, + measure_depth_image: gr.Image, + gs_video: gr.Video, + gs_info: gr.Markdown, + ) -> None: + """Set up example scene handlers.""" + + def load_and_update_measure(name): + result = self.event_handlers.load_example_scene(name) + # result = (reconstruction_output, target_dir, image_paths, log_message, processed_data, measure_view_selector, gs_video, gs_video_vis, gs_info_vis) # noqa: E501 + + # Update measure view if processed_data is available + measure_img = None + measure_depth = None + if result[4] is not None: # processed_data exists + measure_img, measure_depth, _ = ( + self.event_handlers.visualization_handler.update_measure_view(result[4], 0) + ) + + return result + ("True", measure_img, measure_depth) + + for i, scene in enumerate(scenes): + if i < len(scene_components): + scene_components[i].select( + fn=lambda name=scene["name"]: load_and_update_measure(name), + outputs=[ + reconstruction_output, + target_dir_output, + image_gallery, + log_output, + processed_data_state, + measure_view_selector, + gs_video, + gs_video, # gs_video_visibility + gs_info, # gs_info_visibility + is_example, + measure_image, + measure_depth_image, + ], + ) + + def launch(self, host: str = "127.0.0.1", port: int = 7860, **kwargs) -> None: + """ + Launch the application. + + Args: + host: Host address to bind to + port: Port number to bind to + **kwargs: Additional arguments for demo.launch() + """ + demo = self.create_app() + demo.queue(max_size=20).launch( + show_error=True, ssr_mode=False, server_name=host, server_port=port, **kwargs + ) + + +def main(): + """Main function to run the application.""" + parser = argparse.ArgumentParser( + description="Depth Anything 3 Gradio Application", + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog=""" +Examples: + # Basic usage + python gradio_app.py --help + python gradio_app.py --host 0.0.0.0 --port 8080 + python gradio_app.py --model-dir /path/to/model --workspace-dir /path/to/workspace + + # Cache examples at startup (all low-res) + python gradio_app.py --cache-examples + + # Cache with selective high-res+3DGS for scenes matching tag + python gradio_app.py --cache-examples --cache-gs-tag dl3dv + # This will use high-res + 3DGS for scenes containing "dl3dv" in their name, + # and low-res only for other scenes + """, + ) + + # Server configuration + parser.add_argument( + "--host", default="127.0.0.1", help="Host address to bind to (default: 127.0.0.1)" + ) + parser.add_argument( + "--port", type=int, default=7860, help="Port number to bind to (default: 7860)" + ) + + # Directory configuration + parser.add_argument( + "--model-dir", + default="depth-anything/DA3NESTED-GIANT-LARGE", + help="Path to the model directory (default: depth-anything/DA3NESTED-GIANT-LARGE)", + ) + parser.add_argument( + "--workspace-dir", + default="workspace/gradio", # noqa: E501 + help="Path to the workspace directory (default: workspace/gradio)", # noqa: E501 + ) + parser.add_argument( + "--gallery-dir", + default="workspace/gallery", + help="Path to the gallery directory (default: workspace/gallery)", # noqa: E501 + ) + + # Additional Gradio options + parser.add_argument("--share", action="store_true", help="Create a public link for the app") + parser.add_argument("--debug", action="store_true", help="Enable debug mode") + + # Example caching options + parser.add_argument( + "--cache-examples", + action="store_true", + help="Pre-cache all example scenes at startup for faster loading", + ) + parser.add_argument( + "--cache-gs-tag", + type=str, + default="", + help="Tag to match scene names for high-res+3DGS caching (e.g., 'dl3dv'). Scenes containing this tag will use high_res and infer_gs=True; others will use low_res only.", # noqa: E501 + ) + + args = parser.parse_args() + + # Create directories if they don't exist + os.makedirs(args.workspace_dir, exist_ok=True) + os.makedirs(args.gallery_dir, exist_ok=True) + + # Initialize and launch the application + app = DepthAnything3App( + model_dir=args.model_dir, workspace_dir=args.workspace_dir, gallery_dir=args.gallery_dir + ) + + # Prepare launch arguments + launch_kwargs = {"share": args.share, "debug": args.debug} + + print("Starting Depth Anything 3 Gradio App...") + print(f"Host: {args.host}") + print(f"Port: {args.port}") + print(f"Model Directory: {args.model_dir}") + print(f"Workspace Directory: {args.workspace_dir}") + print(f"Gallery Directory: {args.gallery_dir}") + print(f"Share: {args.share}") + print(f"Debug: {args.debug}") + print(f"Cache Examples: {args.cache_examples}") + if args.cache_examples: + if args.cache_gs_tag: + print( + f"Cache GS Tag: '{args.cache_gs_tag}' (scenes matching this tag will use high-res + 3DGS)" # noqa: E501 + ) # noqa: E501 + else: + print("Cache GS Tag: None (all scenes will use low-res only)") + + # Pre-cache examples if requested + if args.cache_examples: + print("\n" + "=" * 60) + print("Pre-caching mode enabled") + if args.cache_gs_tag: + print(f"Scenes containing '{args.cache_gs_tag}' will use HIGH-RES + 3DGS") + print("Other scenes will use LOW-RES only") + else: + print("All scenes will use LOW-RES only") + print("=" * 60) + app.cache_examples( + show_cam=True, + filter_black_bg=False, + filter_white_bg=False, + save_percentage=5.0, + num_max_points=1000, + cache_gs_tag=args.cache_gs_tag, + gs_trj_mode="smooth", + gs_video_quality="low", + ) + + app.launch(host=args.host, port=args.port, **launch_kwargs) + + +if __name__ == "__main__": + main() diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/app/modules/__init__.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/app/modules/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..dd0b71780214eeadbc4fc44f4ac070e0e5fa7795 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/app/modules/__init__.py @@ -0,0 +1,43 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Modules package for Depth Anything 3 Gradio app. + +This package contains all the modular components for the Gradio application. +""" + +from depth_anything_3.app.modules.event_handlers import EventHandlers +from depth_anything_3.app.modules.file_handlers import FileHandler +from depth_anything_3.app.modules.model_inference import ModelInference +from depth_anything_3.app.modules.ui_components import UIComponents +from depth_anything_3.app.modules.utils import ( + create_depth_visualization, + get_logo_base64, + get_scene_info, + save_to_gallery_func, +) +from depth_anything_3.app.modules.visualization import VisualizationHandler + +__all__ = [ + "ModelInference", + "FileHandler", + "VisualizationHandler", + "EventHandlers", + "UIComponents", + "create_depth_visualization", + "save_to_gallery_func", + "get_scene_info", + "get_logo_base64", +] diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/app/modules/event_handlers.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/app/modules/event_handlers.py new file mode 100644 index 0000000000000000000000000000000000000000..c494edb649c634efc9d1883f6aa523f3c0c82b24 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/app/modules/event_handlers.py @@ -0,0 +1,619 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Event handling module for Depth Anything 3 Gradio app. + +This module handles all event callbacks and user interactions. +""" + +import os +import time +from glob import glob +from typing import Any, Dict, List, Optional, Tuple +import gradio as gr +import numpy as np +import torch + +from depth_anything_3.app.modules.file_handlers import FileHandler +from depth_anything_3.app.modules.model_inference import ModelInference +from depth_anything_3.utils.memory import cleanup_cuda_memory +from depth_anything_3.app.modules.visualization import VisualizationHandler + + +class EventHandlers: + """ + Handles all event callbacks and user interactions for the Gradio app. + """ + + def __init__(self): + """Initialize the event handlers.""" + self.model_inference = ModelInference() + self.file_handler = FileHandler() + self.visualization_handler = VisualizationHandler() + + def clear_fields(self) -> None: + """ + Clears the 3D viewer, the stored target_dir, and empties the gallery. + """ + return None + + def update_log(self) -> str: + """ + Display a quick log message while waiting. + """ + return "Loading and Reconstructing..." + + def save_current_visualization( + self, + target_dir: str, + save_percentage: float, + show_cam: bool, + filter_black_bg: bool, + filter_white_bg: bool, + processed_data: Optional[Dict], + scene_name: str = "", + ) -> str: + """ + Save current visualization results to gallery with specified save percentage. + + Args: + target_dir: Directory containing results + save_percentage: Percentage of points to save (0-100) + show_cam: Whether to show cameras + filter_black_bg: Whether to filter black background + filter_white_bg: Whether to filter white background + processed_data: Processed data from reconstruction + + Returns: + Status message + """ + if not target_dir or target_dir == "None" or not os.path.isdir(target_dir): + return "No reconstruction available. Please run 'Reconstruct' first." + + if processed_data is None: + return "No processed data available. Please run 'Reconstruct' first." + + try: + # Add debug information + print("[DEBUG] save_current_visualization called with:") + print(f" target_dir: {target_dir}") + print(f" save_percentage: {save_percentage}") + print(f" show_cam: {show_cam}") + print(f" filter_black_bg: {filter_black_bg}") + print(f" filter_white_bg: {filter_white_bg}") + print(f" processed_data: {processed_data is not None}") + + # Import the gallery save function + # Create gallery name with user input or auto-generated + import datetime + + from .utils import save_to_gallery_func + + timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S") + if scene_name and scene_name.strip(): + gallery_name = f"{scene_name.strip()}_{timestamp}_pct{save_percentage:.0f}" + else: + gallery_name = f"save_{timestamp}_pct{save_percentage:.0f}" + + print(f"[DEBUG] Saving to gallery with name: {gallery_name}") + + # Save entire process folder to gallery + success, message = save_to_gallery_func( + target_dir=target_dir, processed_data=processed_data, gallery_name=gallery_name + ) + + if success: + print(f"[DEBUG] Gallery save completed successfully: {message}") + return ( + "Successfully saved to gallery!\n" + f"Gallery name: {gallery_name}\n" + f"Save percentage: {save_percentage}%\n" + f"Show cameras: {show_cam}\n" + f"Filter black bg: {filter_black_bg}\n" + f"Filter white bg: {filter_white_bg}\n\n" + f"{message}" + ) + else: + print(f"[DEBUG] Gallery save failed: {message}") + return f"Failed to save to gallery: {message}" + + except Exception as e: + return f"Error saving visualization: {str(e)}" + + def gradio_demo( + self, + target_dir: str, + show_cam: bool = True, + filter_black_bg: bool = False, + filter_white_bg: bool = False, + process_res_method: str = "upper_bound_resize", + save_percentage: float = 30.0, + num_max_points: int = 1_000_000, + infer_gs: bool = False, + ref_view_strategy: str = "saddle_balanced", + gs_trj_mode: str = "extend", + gs_video_quality: str = "high", + ) -> Tuple[ + Optional[str], + str, + Optional[Dict], + Optional[np.ndarray], + Optional[np.ndarray], + str, + gr.Dropdown, + Optional[str], # gs video path + gr.update, # gs video visibility update + gr.update, # gs info visibility update + ]: + """ + Perform reconstruction using the already-created target_dir/images. + + Args: + target_dir: Directory containing images + show_cam: Whether to show camera + filter_black_bg: Whether to filter black background + filter_white_bg: Whether to filter white background + process_res_method: Method for resizing input images + save_percentage: Filter percentage for point cloud + num_max_points: Maximum number of points + infer_gs: Whether to infer 3D Gaussian Splatting + ref_view_strategy: Reference view selection strategy + + Returns: + Tuple of reconstruction results + """ + if not os.path.isdir(target_dir) or target_dir == "None": + return ( + None, + "No valid target directory found. Please upload first.", + None, + None, + None, + "", + None, + None, + gr.update(visible=False), # gs_video + gr.update(visible=True), # gs_info + ) + + start_time = time.time() + cleanup_cuda_memory() + + # Get image files for logging + target_dir_images = os.path.join(target_dir, "images") + all_files = ( + sorted(os.listdir(target_dir_images)) if os.path.isdir(target_dir_images) else [] + ) + + print("Running DepthAnything3 model...") + print(f"Reference view strategy: {ref_view_strategy}") + + with torch.no_grad(): + prediction, processed_data = self.model_inference.run_inference( + target_dir, + process_res_method=process_res_method, + show_camera=show_cam, + save_percentage=save_percentage, + num_max_points=int(num_max_points * 1000), # Convert K to actual count + infer_gs=infer_gs, + ref_view_strategy=ref_view_strategy, + gs_trj_mode=gs_trj_mode, + gs_video_quality=gs_video_quality, + ) + + # The GLB file is already generated by the API + glbfile = os.path.join(target_dir, "scene.glb") + + # Handle 3DGS video based on infer_gs flag + gsvideo_path = None + gs_video_visible = False + gs_info_visible = True + + if infer_gs: + try: + gsvideo_path = sorted(glob(os.path.join(target_dir, "gs_video", "*.mp4")))[-1] + gs_video_visible = True + gs_info_visible = False + except IndexError: + gsvideo_path = None + print("3DGS video not found, but infer_gs was enabled") + + # Cleanup + cleanup_cuda_memory() + + end_time = time.time() + print(f"Total time: {end_time - start_time:.2f} seconds") + log_msg = f"Reconstruction Success ({len(all_files)} frames). Waiting for visualization." + + # Populate visualization tabs with processed data + depth_vis, measure_img, measure_depth_vis, measure_pts = ( + self.visualization_handler.populate_visualization_tabs(processed_data) + ) + + # Update view selectors based on available views + depth_selector, measure_selector = self.visualization_handler.update_view_selectors( + processed_data + ) + + return ( + glbfile, + log_msg, + processed_data, + measure_img, # measure_image + measure_depth_vis, # measure_depth_image + "", # measure_text (empty initially) + measure_selector, # measure_view_selector + gsvideo_path, + gr.update(visible=gs_video_visible), # gs_video visibility + gr.update(visible=gs_info_visible), # gs_info visibility + ) + + def update_visualization( + self, + target_dir: str, + show_cam: bool, + is_example: str, + filter_black_bg: bool = False, + filter_white_bg: bool = False, + process_res_method: str = "upper_bound_resize", + ) -> Tuple[gr.update, str]: + """ + Reload saved predictions from npz, create (or reuse) the GLB for new parameters, + and return it for the 3D viewer. + + Args: + target_dir: Directory containing results + show_cam: Whether to show camera + is_example: Whether this is an example scene + filter_black_bg: Whether to filter black background + filter_white_bg: Whether to filter white background + process_res_method: Method for resizing input images + + Returns: + Tuple of (glb_file, log_message) + """ + if not target_dir or target_dir == "None" or not os.path.isdir(target_dir): + return ( + gr.update(), + "No reconstruction available. Please click the Reconstruct button first.", + ) + + # Check if GLB exists (could be cached example or reconstructed scene) + glbfile = os.path.join(target_dir, "scene.glb") + if os.path.exists(glbfile): + return ( + glbfile, + ( + "Visualization loaded from cache." + if is_example == "True" + else "Visualization updated." + ), + ) + + # If no GLB but it's an example that hasn't been reconstructed yet + if is_example == "True": + return ( + gr.update(), + "No reconstruction available. Please click the Reconstruct button first.", + ) + + # For non-examples, check predictions.npz + predictions_path = os.path.join(target_dir, "predictions.npz") + if not os.path.exists(predictions_path): + error_message = ( + f"No reconstruction available at {predictions_path}. " + "Please run 'Reconstruct' first." + ) + return gr.update(), error_message + + loaded = np.load(predictions_path, allow_pickle=True) + predictions = {key: loaded[key] for key in loaded.keys()} # noqa: F841 + + return ( + glbfile, + "Visualization updated.", + ) + + def handle_uploads( + self, + input_video: Optional[str], + input_images: Optional[List], + s_time_interval: float = 10.0, + ) -> Tuple[Optional[str], Optional[str], Optional[List], Optional[str]]: + """ + Handle file uploads and update gallery. + + Args: + input_video: Path to input video file + input_images: List of input image files + s_time_interval: Sampling FPS (frames per second) for frame extraction + + Returns: + Tuple of (reconstruction_output, target_dir, image_paths, log_message) + """ + return self.file_handler.update_gallery_on_upload( + input_video, input_images, s_time_interval + ) + + def load_example_scene(self, scene_name: str, examples_dir: str = None) -> Tuple[ + Optional[str], + Optional[str], + Optional[List], + str, + Optional[Dict], + gr.Dropdown, + Optional[str], + gr.update, + gr.update, + ]: + """ + Load a scene from examples directory. + + Args: + scene_name: Name of the scene to load + examples_dir: Path to examples directory (if None, uses workspace_dir/examples) + + Returns: + Tuple of (reconstruction_output, target_dir, image_paths, log_message, processed_data, measure_view_selector, gs_video, gs_video_vis, gs_info_vis) # noqa: E501 + """ + if examples_dir is None: + # Get workspace directory from environment variable + workspace_dir = os.environ.get("DA3_WORKSPACE_DIR", "gradio_workspace") + examples_dir = os.path.join(workspace_dir, "examples") + + reconstruction_output, target_dir, image_paths, log_message = ( + self.file_handler.load_example_scene(scene_name, examples_dir) + ) + + # Try to load cached processed data if available + processed_data = None + measure_view_selector = gr.Dropdown(choices=["View 1"], value="View 1") + gs_video_path = None + gs_video_visible = False + gs_info_visible = True + + if target_dir and target_dir != "None": + predictions_path = os.path.join(target_dir, "predictions.npz") + if os.path.exists(predictions_path): + try: + # Load predictions from cache + loaded = np.load(predictions_path, allow_pickle=True) + predictions = {key: loaded[key] for key in loaded.keys()} + + # Reconstruct processed_data structure + num_images = len(predictions.get("images", [])) + processed_data = {} + + for i in range(num_images): + processed_data[i] = { + "image": predictions["images"][i] if "images" in predictions else None, + "depth": predictions["depths"][i] if "depths" in predictions else None, + "depth_image": os.path.join( + target_dir, "depth_vis", f"{i:04d}.jpg" # Fixed: use .jpg not .png + ), + "intrinsics": ( + predictions["intrinsics"][i] + if "intrinsics" in predictions + and i < len(predictions["intrinsics"]) + else None + ), + "mask": None, + } + + # Update measure view selector + choices = [f"View {i + 1}" for i in range(num_images)] + measure_view_selector = gr.Dropdown(choices=choices, value=choices[0]) + + except Exception as e: + print(f"Error loading cached data: {e}") + + # Check for cached 3DGS video + gs_video_dir = os.path.join(target_dir, "gs_video") + if os.path.exists(gs_video_dir): + try: + from glob import glob + + gs_videos = sorted(glob(os.path.join(gs_video_dir, "*.mp4"))) + if gs_videos: + gs_video_path = gs_videos[-1] + gs_video_visible = True + gs_info_visible = False + print(f"Loaded cached 3DGS video: {gs_video_path}") + except Exception as e: + print(f"Error loading cached 3DGS video: {e}") + + return ( + reconstruction_output, + target_dir, + image_paths, + log_message, + processed_data, + measure_view_selector, + gs_video_path, + gr.update(visible=gs_video_visible), + gr.update(visible=gs_info_visible), + ) + + def navigate_depth_view( + self, + processed_data: Optional[Dict[int, Dict[str, Any]]], + current_selector: str, + direction: int, + ) -> Tuple[str, Optional[str]]: + """ + Navigate depth view. + + Args: + processed_data: Processed data dictionary + current_selector: Current selector value + direction: Direction to navigate + + Returns: + Tuple of (new_selector_value, depth_vis) + """ + return self.visualization_handler.navigate_depth_view( + processed_data, current_selector, direction + ) + + def update_depth_view( + self, processed_data: Optional[Dict[int, Dict[str, Any]]], view_index: int + ) -> Optional[str]: + """ + Update depth view for a specific view index. + + Args: + processed_data: Processed data dictionary + view_index: Index of the view to update + + Returns: + Path to depth visualization image or None + """ + return self.visualization_handler.update_depth_view(processed_data, view_index) + + def navigate_measure_view( + self, + processed_data: Optional[Dict[int, Dict[str, Any]]], + current_selector: str, + direction: int, + ) -> Tuple[str, Optional[np.ndarray], Optional[np.ndarray], List]: + """ + Navigate measure view. + + Args: + processed_data: Processed data dictionary + current_selector: Current selector value + direction: Direction to navigate + + Returns: + Tuple of (new_selector_value, measure_image, depth_right_half, measure_points) + """ + return self.visualization_handler.navigate_measure_view( + processed_data, current_selector, direction + ) + + def update_measure_view( + self, processed_data: Optional[Dict[int, Dict[str, Any]]], view_index: int + ) -> Tuple[Optional[np.ndarray], Optional[np.ndarray], List]: + """ + Update measure view for a specific view index. + + Args: + processed_data: Processed data dictionary + view_index: Index of the view to update + + Returns: + Tuple of (measure_image, depth_right_half, measure_points) + """ + return self.visualization_handler.update_measure_view(processed_data, view_index) + + def measure( + self, + processed_data: Optional[Dict[int, Dict[str, Any]]], + measure_points: List, + current_view_selector: str, + event: gr.SelectData, + ) -> List: + """ + Handle measurement on images. + + Args: + processed_data: Processed data dictionary + measure_points: List of current measure points + current_view_selector: Current view selector value + event: Gradio select event + + Returns: + List of [image, depth_right_half, measure_points, text] + """ + return self.visualization_handler.measure( + processed_data, measure_points, current_view_selector, event + ) + + def select_first_frame( + self, image_gallery: List, selected_index: int = 0 + ) -> Tuple[List, str, str]: + """ + Select the first frame from the image gallery. + + Args: + image_gallery: List of images in the gallery + selected_index: Index of the selected image (default: 0) + + Returns: + Tuple of (updated_image_gallery, log_message, selected_frame_path) + """ + try: + if not image_gallery or len(image_gallery) == 0: + return image_gallery, "No images available to select as first frame.", "" + + # Handle None or invalid selected_index + if ( + selected_index is None + or selected_index < 0 + or selected_index >= len(image_gallery) + ): + selected_index = 0 + print(f"Invalid selected_index: {selected_index}, using default: 0") + + # Get the selected image based on index + selected_image = image_gallery[selected_index] + print(f"Selected image index: {selected_index}") + print(f"Total images: {len(image_gallery)}") + + # Extract the file path from the selected image + selected_frame_path = "" + print(f"Selected image type: {type(selected_image)}") + print(f"Selected image: {selected_image}") + + if isinstance(selected_image, tuple): + # Gradio Gallery returns tuple (path, None) + selected_frame_path = selected_image[0] + elif isinstance(selected_image, str): + selected_frame_path = selected_image + elif hasattr(selected_image, "name"): + selected_frame_path = selected_image.name + elif isinstance(selected_image, dict): + if "name" in selected_image: + selected_frame_path = selected_image["name"] + elif "path" in selected_image: + selected_frame_path = selected_image["path"] + elif "src" in selected_image: + selected_frame_path = selected_image["src"] + else: + # Try to convert to string + selected_frame_path = str(selected_image) + + print(f"Extracted path: {selected_frame_path}") + + # Extract filename from the path for matching + import os + + selected_filename = os.path.basename(selected_frame_path) + print(f"Selected filename: {selected_filename}") + + # Move the selected image to the front + updated_gallery = [selected_image] + [ + img for img in image_gallery if img != selected_image + ] + + log_message = ( + f"Selected frame: {selected_filename}. " + f"Moved to first position. Total frames: {len(updated_gallery)}" + ) + return updated_gallery, log_message, selected_filename + + except Exception as e: + print(f"Error selecting first frame: {e}") + return image_gallery, f"Error selecting first frame: {e}", "" diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/app/modules/file_handlers.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/app/modules/file_handlers.py new file mode 100644 index 0000000000000000000000000000000000000000..d738bfeb1e70ab2af752e022899d1bda91eb397d --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/app/modules/file_handlers.py @@ -0,0 +1,304 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +File handling module for Depth Anything 3 Gradio app. + +This module handles file uploads, video processing, and file operations. +""" + +import os +import shutil +import time +from datetime import datetime +from typing import List, Optional, Tuple +import cv2 +from PIL import Image +from pillow_heif import register_heif_opener + +register_heif_opener() + + +class FileHandler: + """ + Handles file uploads and processing for the Gradio app. + """ + + def __init__(self): + """Initialize the file handler.""" + + def handle_uploads( + self, + input_video: Optional[str], + input_images: Optional[List], + s_time_interval: float = 10.0, + ) -> Tuple[str, List[str]]: + """ + Create a new 'target_dir' + 'images' subfolder, and place user-uploaded + images or extracted frames from video into it. + + Args: + input_video: Path to input video file + input_images: List of input image files + s_time_interval: Sampling FPS (frames per second) for frame extraction + + Returns: + Tuple of (target_dir, image_paths) + """ + start_time = time.time() + + # Get workspace directory from environment variable or use default + workspace_dir = os.environ.get("DA3_WORKSPACE_DIR", "gradio_workspace") + if not os.path.exists(workspace_dir): + os.makedirs(workspace_dir) + + # Create input_images subdirectory + input_images_dir = os.path.join(workspace_dir, "input_images") + if not os.path.exists(input_images_dir): + os.makedirs(input_images_dir) + + # Create a unique folder name within input_images + timestamp = datetime.now().strftime("%Y%m%d_%H%M%S_%f") + target_dir = os.path.join(input_images_dir, f"session_{timestamp}") + target_dir_images = os.path.join(target_dir, "images") + + # Clean up if somehow that folder already exists + if os.path.exists(target_dir): + shutil.rmtree(target_dir) + os.makedirs(target_dir) + os.makedirs(target_dir_images) + + image_paths = [] + + # Handle images + if input_images is not None: + image_paths.extend(self._process_images(input_images, target_dir_images)) + + # Handle video + if input_video is not None: + image_paths.extend( + self._process_video(input_video, target_dir_images, s_time_interval) + ) + + # Sort final images for gallery + image_paths = sorted(image_paths) + + end_time = time.time() + print(f"Files copied to {target_dir_images}; took {end_time - start_time:.3f} seconds") + return target_dir, image_paths + + def _process_images(self, input_images: List, target_dir_images: str) -> List[str]: + """ + Process uploaded images. + + Args: + input_images: List of input image files + target_dir_images: Target directory for images + + Returns: + List of processed image paths + """ + image_paths = [] + + for file_data in input_images: + if isinstance(file_data, dict) and "name" in file_data: + file_path = file_data["name"] + else: + file_path = file_data + + # Check if the file is a HEIC image + file_ext = os.path.splitext(file_path)[1].lower() + if file_ext in [".heic", ".heif"]: + # Convert HEIC to JPEG for better gallery compatibility + try: + with Image.open(file_path) as img: + # Convert to RGB if necessary (HEIC can have different color modes) + if img.mode not in ("RGB", "L"): + img = img.convert("RGB") + + # Create JPEG filename + base_name = os.path.splitext(os.path.basename(file_path))[0] + dst_path = os.path.join(target_dir_images, f"{base_name}.jpg") + + # Save as JPEG with high quality + img.save(dst_path, "JPEG", quality=95) + image_paths.append(dst_path) + print( + f"Converted HEIC to JPEG: {os.path.basename(file_path)} -> " + f"{os.path.basename(dst_path)}" + ) + except Exception as e: + print(f"Error converting HEIC file {file_path}: {e}") + # Fall back to copying as is + dst_path = os.path.join(target_dir_images, os.path.basename(file_path)) + shutil.copy(file_path, dst_path) + image_paths.append(dst_path) + else: + # Regular image files - copy as is + dst_path = os.path.join(target_dir_images, os.path.basename(file_path)) + shutil.copy(file_path, dst_path) + image_paths.append(dst_path) + + return image_paths + + def _process_video( + self, input_video: str, target_dir_images: str, s_time_interval: float + ) -> List[str]: + """ + Process video file and extract frames. + + Args: + input_video: Path to input video file + target_dir_images: Target directory for extracted frames + s_time_interval: Sampling FPS (frames per second) for frame extraction + + Returns: + List of extracted frame paths + """ + image_paths = [] + + if isinstance(input_video, dict) and "name" in input_video: + video_path = input_video["name"] + else: + video_path = input_video + + vs = cv2.VideoCapture(video_path) + fps = vs.get(cv2.CAP_PROP_FPS) + frame_interval = max(1, int(fps / s_time_interval)) # Convert FPS to frame interval + + count = 0 + video_frame_num = 0 + while True: + gotit, frame = vs.read() + if not gotit: + break + count += 1 + if count % frame_interval == 0: + image_path = os.path.join(target_dir_images, f"{video_frame_num:06}.png") + cv2.imwrite(image_path, frame) + image_paths.append(image_path) + video_frame_num += 1 + + return image_paths + + def update_gallery_on_upload( + self, + input_video: Optional[str], + input_images: Optional[List], + s_time_interval: float = 10.0, + ) -> Tuple[Optional[str], Optional[str], Optional[List], Optional[str]]: + """ + Handle file uploads and update gallery. + + Args: + input_video: Path to input video file + input_images: List of input image files + s_time_interval: Sampling FPS (frames per second) for frame extraction + + Returns: + Tuple of (reconstruction_output, target_dir, image_paths, log_message) + """ + if not input_video and not input_images: + return None, None, None, None + + target_dir, image_paths = self.handle_uploads(input_video, input_images, s_time_interval) + return ( + None, + target_dir, + image_paths, + "Upload complete. Click 'Reconstruct' to begin 3D processing.", + ) + + def load_example_scene( + self, scene_name: str, examples_dir: str = "examples" + ) -> Tuple[Optional[str], Optional[str], Optional[List], str]: + """ + Load a scene from examples directory. + + Args: + scene_name: Name of the scene to load + examples_dir: Path to examples directory + + Returns: + Tuple of (reconstruction_output, target_dir, image_paths, log_message) + """ + from depth_anything_3.app.modules.utils import get_scene_info + + scenes = get_scene_info(examples_dir) + + # Find the selected scene + selected_scene = None + for scene in scenes: + if scene["name"] == scene_name: + selected_scene = scene + break + + if selected_scene is None: + return None, None, None, "Scene not found" + + # Use fixed directory name for examples (not timestamp-based) + workspace_dir = os.environ.get("DA3_WORKSPACE_DIR", "gradio_workspace") + input_images_dir = os.path.join(workspace_dir, "input_images") + if not os.path.exists(input_images_dir): + os.makedirs(input_images_dir) + + # Create a fixed folder name based on scene name + target_dir = os.path.join(input_images_dir, f"example_{scene_name}") + target_dir_images = os.path.join(target_dir, "images") + + # Check if already cached (GLB file exists) + glb_path = os.path.join(target_dir, "scene.glb") + is_cached = os.path.exists(glb_path) + + # Create directory if it doesn't exist + if not os.path.exists(target_dir): + os.makedirs(target_dir) + os.makedirs(target_dir_images) + + # Copy images if directory is new or empty + if not os.path.exists(target_dir_images) or len(os.listdir(target_dir_images)) == 0: + os.makedirs(target_dir_images, exist_ok=True) + image_paths = [] + for file_path in selected_scene["image_files"]: + dst_path = os.path.join(target_dir_images, os.path.basename(file_path)) + shutil.copy(file_path, dst_path) + image_paths.append(dst_path) + else: + # Use existing images + image_paths = sorted( + [ + os.path.join(target_dir_images, f) + for f in os.listdir(target_dir_images) + if f.lower().endswith((".png", ".jpg", ".jpeg", ".bmp", ".tiff", ".tif")) + ] + ) + + # Return cached GLB if available + if is_cached: + return ( + glb_path, # Return cached reconstruction + target_dir, # Set target directory + image_paths, # Set gallery + f"Loaded cached scene '{scene_name}' with {selected_scene['num_images']} images.", + ) + else: + return ( + None, # No cached reconstruction + target_dir, # Set target directory + image_paths, # Set gallery + ( + f"Loaded scene '{scene_name}' with {selected_scene['num_images']} images. " + "Click 'Reconstruct' to begin 3D processing." + ), + ) diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/app/modules/model_inference.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/app/modules/model_inference.py new file mode 100644 index 0000000000000000000000000000000000000000..6ce77b4388b303f95c2f0a9da5c81b2dc55f38f6 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/app/modules/model_inference.py @@ -0,0 +1,260 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Model inference module for Depth Anything 3 Gradio app. + +This module handles all model-related operations including inference, +data processing, and result preparation. +""" + +import glob +import os +from typing import Any, Dict, Optional, Tuple +import numpy as np +import torch + +from depth_anything_3.api import DepthAnything3 +from depth_anything_3.utils.memory import cleanup_cuda_memory +from depth_anything_3.utils.export.glb import export_to_glb +from depth_anything_3.utils.export.gs import export_to_gs_video + + +class ModelInference: + """ + Handles model inference and data processing for Depth Anything 3. + """ + + def __init__(self): + """Initialize the model inference handler.""" + self.model = None + + def initialize_model(self, device: str = "cuda") -> None: + """ + Initialize the DepthAnything3 model. + + Args: + device: Device to load the model on + """ + if self.model is None: + # Get model directory from environment variable or use default + model_dir = os.environ.get( + "DA3_MODEL_DIR", "/dev/shm/da3_models/DA3HF-VITG-METRIC_VITL" + ) + self.model = DepthAnything3.from_pretrained(model_dir) + self.model = self.model.to(device) + else: + self.model = self.model.to(device) + + self.model.eval() + + def run_inference( + self, + target_dir: str, + filter_black_bg: bool = False, + filter_white_bg: bool = False, + process_res_method: str = "upper_bound_resize", + show_camera: bool = True, + save_percentage: float = 30.0, + num_max_points: int = 1_000_000, + infer_gs: bool = False, + ref_view_strategy: str = "saddle_balanced", + gs_trj_mode: str = "extend", + gs_video_quality: str = "high", + ) -> Tuple[Any, Dict[int, Dict[str, Any]]]: + """ + Run DepthAnything3 model inference on images. + + Args: + target_dir: Directory containing images + filter_black_bg: Whether to filter black background + filter_white_bg: Whether to filter white background + process_res_method: Method for resizing input images + show_camera: Whether to show camera in 3D view + save_percentage: Percentage of points to save (0-100) + num_max_points: Maximum number of points in point cloud + infer_gs: Whether to infer 3D Gaussian Splatting + ref_view_strategy: Reference view selection strategy + gs_trj_mode: Trajectory mode for 3DGS + gs_video_quality: Video quality for 3DGS + + Returns: + Tuple of (prediction, processed_data) + """ + print(f"Processing images from {target_dir}") + + # Device check + device = "cuda" if torch.cuda.is_available() else "cpu" + device = torch.device(device) + + # Initialize model if needed + self.initialize_model(device) + + # Get image paths + print("Loading images...") + image_folder_path = os.path.join(target_dir, "images") + all_image_paths = sorted(glob.glob(os.path.join(image_folder_path, "*"))) + + # Filter for image files + image_extensions = [".jpg", ".jpeg", ".png", ".bmp", ".tiff", ".tif"] + all_image_paths = [ + path + for path in all_image_paths + if any(path.lower().endswith(ext) for ext in image_extensions) + ] + + print(f"Found {len(all_image_paths)} images") + print(f"All image paths: {all_image_paths}") + + # Use sorted image order (reference view will be selected automatically) + image_paths = all_image_paths + print(f"Reference view selection strategy: {ref_view_strategy}") + + if len(image_paths) == 0: + raise ValueError("No images found. Check your upload.") + + # Map UI options to actual method names + method_mapping = {"high_res": "lower_bound_resize", "low_res": "upper_bound_resize"} + actual_method = method_mapping.get(process_res_method, "upper_bound_crop") + + # Run model inference + print(f"Running inference with method: {actual_method}") + with torch.no_grad(): + prediction = self.model.inference( + image_paths, + export_dir=None, + process_res_method=actual_method, + infer_gs=infer_gs, + ref_view_strategy=ref_view_strategy, + ) + # num_max_points: int = 1_000_000, + export_to_glb( + prediction, + filter_black_bg=filter_black_bg, + filter_white_bg=filter_white_bg, + export_dir=target_dir, + show_cameras=show_camera, + conf_thresh_percentile=save_percentage, + num_max_points=int(num_max_points), + ) + + # export to gs video if needed + if infer_gs: + mode_mapping = {"extend": "extend", "smooth": "interpolate_smooth"} + print(f"GS mode: {gs_trj_mode}; Backend mode: {mode_mapping[gs_trj_mode]}") + export_to_gs_video( + prediction, + export_dir=target_dir, + chunk_size=4, + trj_mode=mode_mapping.get(gs_trj_mode, "extend"), + enable_tqdm=True, + vis_depth="hcat", + video_quality=gs_video_quality, + ) + + # Save predictions.npz for caching metric depth data + self._save_predictions_cache(target_dir, prediction) + + # Process results + processed_data = self._process_results(target_dir, prediction, image_paths) + + # Clean up using centralized memory utilities for consistency with backend + cleanup_cuda_memory() + + return prediction, processed_data + + def _save_predictions_cache(self, target_dir: str, prediction: Any) -> None: + """ + Save predictions data to predictions.npz for caching. + + Args: + target_dir: Directory to save the cache + prediction: Model prediction object + """ + try: + output_file = os.path.join(target_dir, "predictions.npz") + + # Build save dict with prediction data + save_dict = {} + + # Save processed images if available + if prediction.processed_images is not None: + save_dict["images"] = prediction.processed_images + + # Save depth data + if prediction.depth is not None: + save_dict["depths"] = np.round(prediction.depth, 6) + + # Save confidence if available + if prediction.conf is not None: + save_dict["conf"] = np.round(prediction.conf, 2) + + # Save camera parameters + if prediction.extrinsics is not None: + save_dict["extrinsics"] = prediction.extrinsics + if prediction.intrinsics is not None: + save_dict["intrinsics"] = prediction.intrinsics + + # Save to file + np.savez_compressed(output_file, **save_dict) + print(f"Saved predictions cache to: {output_file}") + + except Exception as e: + print(f"Warning: Failed to save predictions cache: {e}") + + def _process_results( + self, target_dir: str, prediction: Any, image_paths: list + ) -> Dict[int, Dict[str, Any]]: + """ + Process model results into structured data. + + Args: + target_dir: Directory containing results + prediction: Model prediction object + image_paths: List of input image paths + + Returns: + Dictionary containing processed data for each view + """ + processed_data = {} + + # Read generated depth visualization files + depth_vis_dir = os.path.join(target_dir, "depth_vis") + + if os.path.exists(depth_vis_dir): + depth_files = sorted(glob.glob(os.path.join(depth_vis_dir, "*.jpg"))) + for i, depth_file in enumerate(depth_files): + # Use processed images directly from API + processed_image = None + if prediction.processed_images is not None and i < len( + prediction.processed_images + ): + processed_image = prediction.processed_images[i] + + processed_data[i] = { + "depth_image": depth_file, + "image": processed_image, + "original_image_path": image_paths[i] if i < len(image_paths) else None, + "depth": prediction.depth[i] if i < len(prediction.depth) else None, + "intrinsics": ( + prediction.intrinsics[i] + if prediction.intrinsics is not None and i < len(prediction.intrinsics) + else None + ), + "mask": None, # No mask information available + } + + return processed_data + + # cleanup() removed: call cleanup_cuda_memory() directly where needed. diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/app/modules/ui_components.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/app/modules/ui_components.py new file mode 100644 index 0000000000000000000000000000000000000000..3a3762fff3f14284364dfe0b87a5eaf46ec8669d --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/app/modules/ui_components.py @@ -0,0 +1,477 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +UI components module for Depth Anything 3 Gradio app. + +This module contains UI component definitions and layout functions. +""" + +import os +from typing import Any, Dict, List, Tuple +import gradio as gr + +from depth_anything_3.app.modules.utils import get_logo_base64, get_scene_info + + +class UIComponents: + """ + Handles UI component creation and layout for the Gradio app. + """ + + def __init__(self): + """Initialize the UI components handler.""" + + def create_upload_section(self) -> Tuple[gr.Video, gr.Slider, gr.File, gr.Gallery]: + """ + Create the upload section with video, images, and gallery components. + + Returns: + A tuple of Gradio components: (input_video, s_time_interval, input_images, image_gallery). + """ + input_video = gr.Video(label="Upload Video", interactive=True) + s_time_interval = gr.Slider( + minimum=0.1, + maximum=60, + value=10, + step=0.1, + label="Sampling FPS (Frames Per Second)", + interactive=True, + visible=True, + ) + input_images = gr.File(file_count="multiple", label="Upload Images", interactive=True) + image_gallery = gr.Gallery( + label="Preview", + columns=4, + height="300px", + show_download_button=True, + object_fit="contain", + preview=True, + interactive=False, + ) + + return input_video, s_time_interval, input_images, image_gallery + + def create_3d_viewer_section(self) -> gr.Model3D: + """ + Create the 3D viewer component. + + Returns: + 3D model viewer component + """ + return gr.Model3D( + height=520, + zoom_speed=0.5, + pan_speed=0.5, + clear_color=[0.0, 0.0, 0.0, 0.0], + key="persistent_3d_viewer", + elem_id="reconstruction_3d_viewer", + ) + + def create_nvs_video(self) -> Tuple[gr.Video, gr.Markdown]: + """ + Create the 3DGS rendered video display component and info message. + + Returns: + Tuple of (video component, info message component) + """ + with gr.Column(): + gs_info = gr.Markdown( + ( + "‼️ **3D Gaussian Splatting rendering is currently DISABLED.**


" + "To render novel views from 3DGS, " + "enable **Infer 3D Gaussian Splatting** below.
" + "Next, in **Visualization Options**, " + "*optionally* configure the **rendering trajectory** (default: smooth) " + "and **video quality** (default: low), " + "then click **Reconstruct**." + ), + visible=True, + height=520, + ) + gs_video = gr.Video( + height=520, + label="3DGS Rendered NVS Video (depth shown for reference only)", + interactive=False, + visible=False, + ) + return gs_video, gs_info + + def create_depth_section(self) -> Tuple[gr.Button, gr.Dropdown, gr.Button, gr.Image]: + """ + Create the depth visualization section. + + Returns: + A tuple of (prev_depth_btn, depth_view_selector, next_depth_btn, depth_map) + """ + with gr.Row(elem_classes=["navigation-row"]): + prev_depth_btn = gr.Button("◀ Previous", size="sm", scale=1) + depth_view_selector = gr.Dropdown( + choices=["View 1"], + value="View 1", + label="Select View", + scale=2, + interactive=True, + allow_custom_value=True, + ) + next_depth_btn = gr.Button("Next ▶", size="sm", scale=1) + depth_map = gr.Image( + type="numpy", + label="Colorized Depth Map", + format="png", + interactive=False, + ) + + return prev_depth_btn, depth_view_selector, next_depth_btn, depth_map + + def create_measure_section( + self, + ) -> Tuple[gr.Button, gr.Dropdown, gr.Button, gr.Image, gr.Image, gr.Markdown]: + """ + Create the measurement section. + + Returns: + A tuple of (prev_measure_btn, measure_view_selector, next_measure_btn, measure_image, + measure_depth_image, measure_text) + """ + from depth_anything_3.app.css_and_html import MEASURE_INSTRUCTIONS_HTML + + gr.Markdown(MEASURE_INSTRUCTIONS_HTML) + with gr.Row(elem_classes=["navigation-row"]): + prev_measure_btn = gr.Button("◀ Previous", size="sm", scale=1) + measure_view_selector = gr.Dropdown( + choices=["View 1"], + value="View 1", + label="Select View", + scale=2, + interactive=True, + allow_custom_value=True, + ) + next_measure_btn = gr.Button("Next ▶", size="sm", scale=1) + with gr.Row(): + measure_image = gr.Image( + type="numpy", + show_label=False, + format="webp", + interactive=False, + sources=[], + label="RGB Image", + scale=1, + height=275, + ) + measure_depth_image = gr.Image( + type="numpy", + show_label=False, + format="webp", + interactive=False, + sources=[], + label="Depth Visualization (Right Half)", + scale=1, + height=275, + ) + gr.Markdown( + "**Note:** Images have been adjusted to model processing size. " + "Click two points on the RGB image to measure distance." + ) + measure_text = gr.Markdown("") + + return ( + prev_measure_btn, + measure_view_selector, + next_measure_btn, + measure_image, + measure_depth_image, + measure_text, + ) + + def create_inference_control_section(self) -> Tuple[gr.Dropdown, gr.Checkbox, gr.Dropdown]: + """ + Create the inference control section (before inference). + + Returns: + Tuple of (process_res_method_dropdown, infer_gs, ref_view_strategy) + """ + with gr.Row(): + process_res_method_dropdown = gr.Dropdown( + choices=["high_res", "low_res"], + value="low_res", + label="Image Processing Method", + info="low_res for much more images", + scale=1, + ) + # Modify line 220, add color class + infer_gs = gr.Checkbox( + label="Infer 3D Gaussian Splatting", + value=False, + info=( + 'Enable novel view rendering from 3DGS ( requires extra processing time)' + ), + scale=1, + ) + ref_view_strategy = gr.Dropdown( + choices=["saddle_balanced", "saddle_sim_range", "first", "middle"], + value="saddle_balanced", + label="Reference View Strategy", + info="Strategy for selecting reference view from multiple inputs", + scale=1, + ) + + return (process_res_method_dropdown, infer_gs, ref_view_strategy) + + def create_display_control_section( + self, + ) -> Tuple[ + gr.Checkbox, + gr.Checkbox, + gr.Checkbox, + gr.Slider, + gr.Slider, + gr.Dropdown, + gr.Dropdown, + gr.Button, + gr.ClearButton, + ]: + """ + Create the display control section (options for visualization). + + Returns: + Tuple of display control components including buttons + """ + with gr.Column(): + # 3DGS options at the top + with gr.Row(): + gs_trj_mode = gr.Dropdown( + choices=["smooth", "extend"], + value="smooth", + label=("Rendering trajectory for 3DGS viewpoints (requires n_views ≥ 2)"), + info=("'smooth' for view interpolation; 'extend' for longer trajectory"), + visible=False, # initially hidden + ) + gs_video_quality = gr.Dropdown( + choices=["low", "medium", "high"], + value="low", + label=("Video quality for 3DGS rendered outputs"), + info=("'low' for faster loading speed; 'high' for better visual quality"), + visible=False, # initially hidden + ) + + # Reconstruct and Clear buttons (before Visualization Options) + with gr.Row(): + submit_btn = gr.Button("Reconstruct", scale=1, variant="primary") + clear_btn = gr.ClearButton(scale=1) + + gr.Markdown("### Visualization Options: (Click Reconstruct to update)") + show_cam = gr.Checkbox(label="Show Camera", value=True) + filter_black_bg = gr.Checkbox(label="Filter Black Background", value=False) + filter_white_bg = gr.Checkbox(label="Filter White Background", value=False) + save_percentage = gr.Slider( + minimum=0, + maximum=100, + value=10, + step=1, + label="Filter Percentage", + info="Confidence Threshold (%): Higher values filter more points.", + ) + num_max_points = gr.Slider( + minimum=1000, + maximum=100000, + value=1000, + step=1000, + label="Max Points (K points)", + info="Maximum number of points to export to GLB (in thousands)", + ) + + return ( + show_cam, + filter_black_bg, + filter_white_bg, + save_percentage, + num_max_points, + gs_trj_mode, + gs_video_quality, + submit_btn, + clear_btn, + ) + + def create_control_section( + self, + ) -> Tuple[ + gr.Button, + gr.ClearButton, + gr.Dropdown, + gr.Checkbox, + gr.Checkbox, + gr.Checkbox, + gr.Checkbox, + gr.Checkbox, + gr.Dropdown, + gr.Checkbox, + gr.Textbox, + ]: + """ + Create the control section with buttons and options. + + Returns: + Tuple of control components + """ + with gr.Row(): + submit_btn = gr.Button("Reconstruct", scale=1, variant="primary") + clear_btn = gr.ClearButton( + scale=1, + ) + + with gr.Row(): + frame_filter = gr.Dropdown( + choices=["All"], value="All", label="Show Points from Frame" + ) + with gr.Column(): + gr.Markdown("### Visualization Option: (Click Reconstruct to update)") + show_cam = gr.Checkbox(label="Show Camera", value=True) + show_mesh = gr.Checkbox(label="Show Mesh", value=True) + filter_black_bg = gr.Checkbox(label="Filter Black Background", value=False) + filter_white_bg = gr.Checkbox(label="Filter White Background", value=False) + gr.Markdown("### Reconstruction Options: (updated on next run)") + apply_mask_checkbox = gr.Checkbox( + label="Apply mask for predicted ambiguous depth classes & edges", + value=True, + ) + process_res_method_dropdown = gr.Dropdown( + choices=[ + "upper_bound_resize", + "upper_bound_crop", + "lower_bound_resize", + "lower_bound_crop", + ], + value="upper_bound_resize", + label="Image Processing Method", + info="Method for resizing input images", + ) + save_to_gallery_checkbox = gr.Checkbox( + label="Save to Gallery", + value=False, + info="Save current reconstruction results to gallery directory", + ) + gallery_name_input = gr.Textbox( + label="Gallery Name", + placeholder="Enter a name for the gallery folder", + value="", + info="Leave empty for auto-generated name with timestamp", + ) + + return ( + submit_btn, + clear_btn, + frame_filter, + show_cam, + show_mesh, + filter_black_bg, + filter_white_bg, + apply_mask_checkbox, + process_res_method_dropdown, + save_to_gallery_checkbox, + gallery_name_input, + ) + + def create_example_scenes_section(self) -> List[Dict[str, Any]]: + """ + Create the example scenes section. + + Returns: + List of scene information dictionaries + """ + # Get workspace directory from environment variable + workspace_dir = os.environ.get("DA3_WORKSPACE_DIR", "gradio_workspace") + examples_dir = os.path.join(workspace_dir, "examples") + + # Get scene information + scenes = get_scene_info(examples_dir) + + return scenes + + def create_example_scene_grid(self, scenes: List[Dict[str, Any]]) -> List[gr.Image]: + """ + Create the example scene grid. + + Args: + scenes: List of scene information dictionaries + + Returns: + List of scene image components + """ + scene_components = [] + + if scenes: + for i in range(0, len(scenes), 4): # Process 4 scenes per row + with gr.Row(): + for j in range(4): + scene_idx = i + j + if scene_idx < len(scenes): + scene = scenes[scene_idx] + with gr.Column(scale=1, elem_classes=["clickable-thumbnail"]): + # Clickable thumbnail + scene_img = gr.Image( + value=scene["thumbnail"], + height=150, + interactive=False, + show_label=False, + elem_id=f"scene_thumb_{scene['name']}", + sources=[], + ) + scene_components.append(scene_img) + + # Scene name and image count as text below thumbnail + gr.Markdown( + f"**{scene['name']}** \n {scene['num_images']} images", + elem_classes=["scene-info"], + ) + else: + # Empty column to maintain grid structure + with gr.Column(scale=1): + pass + + return scene_components + + def create_header_section(self) -> gr.HTML: + """ + Create the header section with logo and title. + + Returns: + Header HTML component + """ + from depth_anything_3.app.css_and_html import get_header_html + + return gr.HTML(get_header_html(get_logo_base64())) + + def create_description_section(self) -> gr.HTML: + """ + Create the description section. + + Returns: + Description HTML component + """ + from depth_anything_3.app.css_and_html import get_description_html + + return gr.HTML(get_description_html()) + + def create_acknowledgements_section(self) -> gr.HTML: + """ + Create the acknowledgements section. + + Returns: + Acknowledgements HTML component + """ + from depth_anything_3.app.css_and_html import get_acknowledgements_html + + return gr.HTML(get_acknowledgements_html()) diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/app/modules/utils.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/app/modules/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..985abc145753c77143cd87d762ded76ac1dd0755 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/app/modules/utils.py @@ -0,0 +1,207 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Utility functions for Depth Anything 3 Gradio app. + +This module contains helper functions for data processing, visualization, +and file operations. +""" + + +import json +import os +import shutil +from datetime import datetime +from typing import Any, Dict, List, Optional, Tuple +import numpy as np + +def create_depth_visualization(depth: np.ndarray) -> Optional[np.ndarray]: + """ + Create a colored depth visualization. + + Args: + depth: Depth array + + Returns: + Colored depth visualization or None + """ + if depth is None: + return None + + # Normalize depth to 0-1 range + depth_min = depth[depth > 0].min() if (depth > 0).any() else 0 + depth_max = depth.max() + + if depth_max <= depth_min: + return None + + # Normalize depth + depth_norm = (depth - depth_min) / (depth_max - depth_min) + depth_norm = np.clip(depth_norm, 0, 1) + + # Apply colormap (using matplotlib's viridis colormap) + import matplotlib.cm as cm + + # Convert to colored image + depth_colored = cm.viridis(depth_norm)[:, :, :3] # Remove alpha channel + depth_colored = (depth_colored * 255).astype(np.uint8) + + return depth_colored + + +def save_to_gallery_func( + target_dir: str, processed_data: Dict[int, Dict[str, Any]], gallery_name: Optional[str] = None +) -> Tuple[bool, str]: + """ + Save the current reconstruction results to the gallery directory. + + Args: + target_dir: Source directory containing reconstruction results + processed_data: Processed data dictionary + gallery_name: Name for the gallery folder + + Returns: + Tuple of (success, message) + """ + try: + # Get gallery directory from environment variable or use default + gallery_dir = os.environ.get( + "DA3_GALLERY_DIR", + "workspace/gallery", + ) + if not os.path.exists(gallery_dir): + os.makedirs(gallery_dir) + + # Use provided name or create a unique name + if gallery_name is None or gallery_name.strip() == "": + timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") + gallery_name = f"reconstruction_{timestamp}" + + gallery_path = os.path.join(gallery_dir, gallery_name) + + # Check if directory already exists + if os.path.exists(gallery_path): + return False, f"Save failed: folder '{gallery_name}' already exists" + + # Create the gallery directory + os.makedirs(gallery_path, exist_ok=True) + + # Copy GLB file + glb_source = os.path.join(target_dir, "scene.glb") + glb_dest = os.path.join(gallery_path, "scene.glb") + if os.path.exists(glb_source): + shutil.copy2(glb_source, glb_dest) + + # Copy depth visualization images + depth_vis_dir = os.path.join(target_dir, "depth_vis") + if os.path.exists(depth_vis_dir): + gallery_depth_vis = os.path.join(gallery_path, "depth_vis") + shutil.copytree(depth_vis_dir, gallery_depth_vis) + + # Copy original images + images_source = os.path.join(target_dir, "images") + if os.path.exists(images_source): + gallery_images = os.path.join(gallery_path, "images") + shutil.copytree(images_source, gallery_images) + + scene_preview_source = os.path.join(target_dir, "scene.jpg") + scene_preview_dest = os.path.join(gallery_path, "scene.jpg") + shutil.copy2(scene_preview_source, scene_preview_dest) + + # Save metadata + metadata = { + "timestamp": datetime.now().strftime("%Y%m%d_%H%M%S"), + "num_images": len(processed_data) if processed_data else 0, + "gallery_name": gallery_name, + } + + with open(os.path.join(gallery_path, "metadata.json"), "w") as f: + json.dump(metadata, f, indent=2) + + print(f"Saved reconstruction to gallery: {gallery_path}") + return True, f"Save successful: saved to {gallery_path}" + + except Exception as e: + print(f"Error saving to gallery: {e}") + return False, f"Save failed: {str(e)}" + + +def get_scene_info(examples_dir: str) -> List[Dict[str, Any]]: + """ + Get information about scenes in the examples directory. + + Args: + examples_dir: Path to examples directory + + Returns: + List of scene information dictionaries + """ + import glob + + scenes = [] + if not os.path.exists(examples_dir): + return scenes + + for scene_folder in sorted(os.listdir(examples_dir)): + scene_path = os.path.join(examples_dir, scene_folder) + if os.path.isdir(scene_path): + # Find all image files in the scene folder + image_extensions = ["*.jpg", "*.jpeg", "*.png", "*.bmp", "*.tiff", "*.tif"] + image_files = [] + for ext in image_extensions: + image_files.extend(glob.glob(os.path.join(scene_path, ext))) + image_files.extend(glob.glob(os.path.join(scene_path, ext.upper()))) + + if image_files: + # Sort images and get the first one for thumbnail + image_files = sorted(image_files) + first_image = image_files[0] + num_images = len(image_files) + + scenes.append( + { + "name": scene_folder, + "path": scene_path, + "thumbnail": first_image, + "num_images": num_images, + "image_files": image_files, + } + ) + + return scenes + + +# NOTE: cleanup was moved to a single canonical helper in +# `depth_anything_3.utils.memory.cleanup_cuda_memory`. +# Callers should import and call that directly instead of using this module. + + +def get_logo_base64() -> Optional[str]: + """ + Convert WAI logo to base64 for embedding in HTML. + + Returns: + Base64 encoded logo string or None + """ + import base64 + + logo_path = "examples/WAI-Logo/wai_logo.png" + try: + with open(logo_path, "rb") as img_file: + img_data = img_file.read() + base64_str = base64.b64encode(img_data).decode() + return f"data:image/png;base64,{base64_str}" + except FileNotFoundError: + return None diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/app/modules/visualization.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/app/modules/visualization.py new file mode 100644 index 0000000000000000000000000000000000000000..ada49b25532a6ddbeb0e7f99856498e4ce3fb2ad --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/app/modules/visualization.py @@ -0,0 +1,434 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Visualization module for Depth Anything 3 Gradio app. + +This module handles visualization updates, navigation, and measurement functionality. +""" + +import os +from typing import Any, Dict, List, Optional, Tuple +import cv2 +import gradio as gr +import numpy as np + + +class VisualizationHandler: + """ + Handles visualization updates and navigation for the Gradio app. + """ + + def __init__(self): + """Initialize the visualization handler.""" + + def update_view_selectors( + self, processed_data: Optional[Dict[int, Dict[str, Any]]] + ) -> Tuple[gr.Dropdown, gr.Dropdown]: + """ + Update view selector dropdowns based on available views. + + Args: + processed_data: Processed data dictionary + + Returns: + Tuple of (depth_view_selector, measure_view_selector) + """ + if processed_data is None or len(processed_data) == 0: + choices = ["View 1"] + else: + num_views = len(processed_data) + choices = [f"View {i + 1}" for i in range(num_views)] + + return ( + gr.Dropdown(choices=choices, value=choices[0]), # depth_view_selector + gr.Dropdown(choices=choices, value=choices[0]), # measure_view_selector + ) + + def get_view_data_by_index( + self, processed_data: Optional[Dict[int, Dict[str, Any]]], view_index: int + ) -> Optional[Dict[str, Any]]: + """ + Get view data by index, handling bounds. + + Args: + processed_data: Processed data dictionary + view_index: Index of the view to get + + Returns: + View data dictionary or None + """ + if processed_data is None or len(processed_data) == 0: + return None + + view_keys = list(processed_data.keys()) + if view_index < 0 or view_index >= len(view_keys): + view_index = 0 + + return processed_data[view_keys[view_index]] + + def update_depth_view( + self, processed_data: Optional[Dict[int, Dict[str, Any]]], view_index: int + ) -> Optional[str]: + """ + Update depth view for a specific view index. + + Args: + processed_data: Processed data dictionary + view_index: Index of the view to update + + Returns: + Path to depth visualization image or None + """ + view_data = self.get_view_data_by_index(processed_data, view_index) + if view_data is None or view_data.get("depth_image") is None: + return None + + # Return the depth visualization image directly + return view_data["depth_image"] + + def navigate_depth_view( + self, + processed_data: Optional[Dict[int, Dict[str, Any]]], + current_selector_value: str, + direction: int, + ) -> Tuple[str, Optional[str]]: + """ + Navigate depth view (direction: -1 for previous, +1 for next). + + Args: + processed_data: Processed data dictionary + current_selector_value: Current selector value + direction: Direction to navigate (-1 for previous, +1 for next) + + Returns: + Tuple of (new_selector_value, depth_vis) + """ + if processed_data is None or len(processed_data) == 0: + return "View 1", None + + # Parse current view number + try: + current_view = int(current_selector_value.split()[1]) - 1 + except: # noqa + current_view = 0 + + num_views = len(processed_data) + new_view = (current_view + direction) % num_views + + new_selector_value = f"View {new_view + 1}" + depth_vis = self.update_depth_view(processed_data, new_view) + + return new_selector_value, depth_vis + + def update_measure_view( + self, processed_data: Optional[Dict[int, Dict[str, Any]]], view_index: int + ) -> Tuple[Optional[np.ndarray], Optional[np.ndarray], List]: + """ + Update measure view for a specific view index. + + Args: + processed_data: Processed data dictionary + view_index: Index of the view to update + + Returns: + Tuple of (measure_image, depth_right_half, measure_points) + """ + view_data = self.get_view_data_by_index(processed_data, view_index) + if view_data is None: + return None, None, [] # image, depth_right_half, measure_points + + # Get the processed (resized) image + if "image" in view_data and view_data["image"] is not None: + image = view_data["image"].copy() + else: + return None, None, [] + + # Ensure image is in uint8 format + if image.dtype != np.uint8: + if image.max() <= 1.0: + image = (image * 255).astype(np.uint8) + else: + image = image.astype(np.uint8) + + # Extract right half of the depth visualization (pure depth part) + depth_image_path = view_data.get("depth_image", None) + depth_right_half = None + + if depth_image_path and os.path.exists(depth_image_path): + try: + # Load the combined depth visualization image + depth_combined = cv2.imread(depth_image_path) + depth_combined = cv2.cvtColor(depth_combined, cv2.COLOR_BGR2RGB) + if depth_combined is not None: + height, width = depth_combined.shape[:2] + # Extract right half (depth visualization part) + depth_right_half = depth_combined[:, width // 2 :] + except Exception as e: + print(f"Error extracting depth right half: {e}") + + return image, depth_right_half, [] + + def navigate_measure_view( + self, + processed_data: Optional[Dict[int, Dict[str, Any]]], + current_selector_value: str, + direction: int, + ) -> Tuple[str, Optional[np.ndarray], Optional[str], List]: + """ + Navigate measure view (direction: -1 for previous, +1 for next). + + Args: + processed_data: Processed data dictionary + current_selector_value: Current selector value + direction: Direction to navigate (-1 for previous, +1 for next) + + Returns: + Tuple of (new_selector_value, measure_image, depth_image_path, measure_points) + """ + if processed_data is None or len(processed_data) == 0: + return "View 1", None, None, [] + + # Parse current view number + try: + current_view = int(current_selector_value.split()[1]) - 1 + except: # noqa + current_view = 0 + + num_views = len(processed_data) + new_view = (current_view + direction) % num_views + + new_selector_value = f"View {new_view + 1}" + measure_image, depth_right_half, measure_points = self.update_measure_view( + processed_data, new_view + ) + + return new_selector_value, measure_image, depth_right_half, measure_points + + def populate_visualization_tabs( + self, processed_data: Optional[Dict[int, Dict[str, Any]]] + ) -> Tuple[Optional[str], Optional[np.ndarray], Optional[str], List]: + """ + Populate the depth and measure tabs with processed data. + + Args: + processed_data: Processed data dictionary + + Returns: + Tuple of (depth_vis, measure_img, depth_image_path, measure_points) + """ + if processed_data is None or len(processed_data) == 0: + return None, None, None, [] + + # Use update function to get depth visualization + depth_vis = self.update_depth_view(processed_data, 0) + measure_img, depth_right_half, _ = self.update_measure_view(processed_data, 0) + + return depth_vis, measure_img, depth_right_half, [] + + def reset_measure( + self, processed_data: Optional[Dict[int, Dict[str, Any]]] + ) -> Tuple[Optional[np.ndarray], List, str]: + """ + Reset measure points. + + Args: + processed_data: Processed data dictionary + + Returns: + Tuple of (image, measure_points, text) + """ + if processed_data is None or len(processed_data) == 0: + return None, [], "" + + # Return the first view image + first_view = list(processed_data.values())[0] + return first_view["image"], [], "" + + def measure( + self, + processed_data: Optional[Dict[int, Dict[str, Any]]], + measure_points: List, + current_view_selector: str, + event: gr.SelectData, + ) -> List: + """ + Handle measurement on images. + + Args: + processed_data: Processed data dictionary + measure_points: List of current measure points + current_view_selector: Current view selector value + event: Gradio select event + + Returns: + List of [image, depth_right_half, measure_points, text] + """ + try: + print(f"Measure function called with selector: {current_view_selector}") + + if processed_data is None or len(processed_data) == 0: + return [None, [], "No data available"] + + # Use the currently selected view instead of always using the first view + try: + current_view_index = int(current_view_selector.split()[1]) - 1 + except: # noqa + current_view_index = 0 + + print(f"Using view index: {current_view_index}") + + # Get view data safely + if current_view_index < 0 or current_view_index >= len(processed_data): + current_view_index = 0 + + view_keys = list(processed_data.keys()) + current_view = processed_data[view_keys[current_view_index]] + + if current_view is None: + return [None, [], "No view data available"] + + point2d = event.index[0], event.index[1] + print(f"Clicked point: {point2d}") + + measure_points.append(point2d) + + # Get image and depth visualization + image, depth_right_half, _ = self.update_measure_view( + processed_data, current_view_index + ) + if image is None: + return [None, [], "No image available"] + + image = image.copy() + + # Ensure image is in uint8 format for proper cv2 operations + try: + if image.dtype != np.uint8: + if image.max() <= 1.0: + # Image is in [0, 1] range, convert to [0, 255] + image = (image * 255).astype(np.uint8) + else: + # Image is already in [0, 255] range + image = image.astype(np.uint8) + except Exception as e: + print(f"Image conversion error: {e}") + return [None, [], f"Image conversion error: {e}"] + + # Draw circles for points + try: + for p in measure_points: + if 0 <= p[0] < image.shape[1] and 0 <= p[1] < image.shape[0]: + image = cv2.circle(image, p, radius=5, color=(255, 0, 0), thickness=2) + except Exception as e: + print(f"Drawing error: {e}") + return [None, [], f"Drawing error: {e}"] + + # Get depth information from processed_data + depth_text = "" + try: + for i, p in enumerate(measure_points): + if ( + current_view["depth"] is not None + and 0 <= p[1] < current_view["depth"].shape[0] + and 0 <= p[0] < current_view["depth"].shape[1] + ): + d = current_view["depth"][p[1], p[0]] + depth_text += f"- **P{i + 1} depth: {d:.2f}m**\n" + else: + depth_text += f"- **P{i + 1}: Click position ({p[0]}, {p[1]}) - No depth information**\n" # noqa: E501 + except Exception as e: + print(f"Depth text error: {e}") + depth_text = f"Error computing depth: {e}\n" + + if len(measure_points) == 2: + try: + point1, point2 = measure_points + # Draw line + if ( + 0 <= point1[0] < image.shape[1] + and 0 <= point1[1] < image.shape[0] + and 0 <= point2[0] < image.shape[1] + and 0 <= point2[1] < image.shape[0] + ): + image = cv2.line(image, point1, point2, color=(255, 0, 0), thickness=2) + + # Compute 3D distance using depth information and camera intrinsics + distance_text = "- **Distance: Unable to calculate 3D distance**" + if ( + current_view["depth"] is not None + and 0 <= point1[1] < current_view["depth"].shape[0] + and 0 <= point1[0] < current_view["depth"].shape[1] + and 0 <= point2[1] < current_view["depth"].shape[0] + and 0 <= point2[0] < current_view["depth"].shape[1] + ): + try: + # Get depth values at the two points + d1 = current_view["depth"][point1[1], point1[0]] + d2 = current_view["depth"][point2[1], point2[0]] + + # Convert 2D pixel coordinates to 3D world coordinates + if current_view["intrinsics"] is not None: + # Get camera intrinsics + K = current_view["intrinsics"] # 3x3 intrinsic matrix + fx, fy = K[0, 0], K[1, 1] # focal lengths + cx, cy = K[0, 2], K[1, 2] # principal point + + # Convert pixel coordinates to normalized camera coordinates + # Point 1: (u1, v1) -> (x1, y1, z1) + u1, v1 = point1[0], point1[1] + x1 = (u1 - cx) * d1 / fx + y1 = (v1 - cy) * d1 / fy + z1 = d1 + + # Point 2: (u2, v2) -> (x2, y2, z2) + u2, v2 = point2[0], point2[1] + x2 = (u2 - cx) * d2 / fx + y2 = (v2 - cy) * d2 / fy + z2 = d2 + + # Calculate 3D Euclidean distance + p1_3d = np.array([x1, y1, z1]) + p2_3d = np.array([x2, y2, z2]) + distance_3d = np.linalg.norm(p1_3d - p2_3d) + + distance_text = f"- **Distance: {distance_3d:.2f}m**" + else: + # Fallback to simplified calculation if no intrinsics + pixel_distance = np.sqrt( + (point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2 + ) + avg_depth = (d1 + d2) / 2 + scale_factor = avg_depth / 1000 # Rough scaling factor + estimated_3d_distance = pixel_distance * scale_factor + distance_text = f"- **Distance: {estimated_3d_distance:.2f}m (estimated, no intrinsics)**" # noqa: E501 + + except Exception as e: + print(f"Distance computation error: {e}") + distance_text = f"- **Distance computation error: {e}**" + + measure_points = [] + text = depth_text + distance_text + print(f"Measurement complete: {text}") + return [image, depth_right_half, measure_points, text] + except Exception as e: + print(f"Final measurement error: {e}") + return [None, [], f"Measurement error: {e}"] + else: + print(f"Single point measurement: {depth_text}") + return [image, depth_right_half, measure_points, depth_text] + + except Exception as e: + print(f"Overall measure function error: {e}") + return [None, [], f"Measure function error: {e}"] diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/bench/__init__.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/bench/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..664ee41e3fde08213d64dc81e543af3b0b0783ad --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/bench/__init__.py @@ -0,0 +1,45 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Depth Anything 3 Benchmark Evaluation Module. + +This module provides tools for evaluating DepthAnything3 model on various benchmark datasets. +Currently supported datasets: +- DTU (3D Reconstruction) +- DTU-64 (Pose Evaluation Only) +- ETH3D (3D Reconstruction) +- 7Scenes (3D Reconstruction) +- ScanNet++ (3D Reconstruction) +- HiRoom (3D Reconstruction) + +Supported evaluation modes: +- pose: Camera pose estimation evaluation +- recon_unposed: 3D reconstruction with predicted poses +- recon_posed: 3D reconstruction with ground truth poses +""" + +from depth_anything_3.bench.registries import MV_REGISTRY, MONO_REGISTRY + + +def __getattr__(name): + """Lazy import to avoid circular import when running as __main__.""" + if name == "Evaluator": + from depth_anything_3.bench.evaluator import Evaluator + return Evaluator + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + + +__all__ = ["Evaluator", "MV_REGISTRY", "MONO_REGISTRY"] + diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/bench/configs/eval_bench.yaml b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/bench/configs/eval_bench.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1d9924ddfeecb42a5dda47d19f5e86d2bedd8273 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/bench/configs/eval_bench.yaml @@ -0,0 +1,98 @@ +# DepthAnything3 Benchmark Evaluation Configuration +# +# This config can be loaded and overridden via command line. +# Example: python -m depth_anything_3.bench.evaluator --model /path/to/model --work_dir /path/to/workspace +# +# See depth_anything_3.cfg for config utility functions. + +# ============================================================================== +# Model Configuration +# ============================================================================== +model: + # Path to model checkpoint or HuggingFace model ID + path: depth-anything/DA3-GIANT + +# ============================================================================== +# Workspace Configuration +# ============================================================================== +workspace: + # Working directory for outputs (model results, metrics, etc.) + work_dir: ./workspace/evaluation + +# ============================================================================== +# Evaluation Configuration +# ============================================================================== +eval: + # Datasets to evaluate + # Options: dtu, dtu64, eth3d, 7scenes (sevenscenes), scannetpp, hiroom + datasets: + - eth3d + - 7scenes + - scannetpp + - hiroom + - dtu + - dtu64 + + # Evaluation modes + # Options: pose, recon_unposed, recon_posed, view_syn + modes: + - pose + - recon_unposed + - recon_posed + + # Reference view selection strategy for inference + # Options: first, saddle_balanced, auto, mid + ref_view_strategy: "first" + + # Specific scenes to evaluate (null = all scenes) + # Example: [courtyard, relief] for eth3d + scenes: null + + # Maximum number of frames per scene (for sampling) + # If a scene has more frames, randomly sample to this limit. + # Set to -1 to disable sampling. + max_frames: 100 + + # Only run evaluation (skip inference) + eval_only: false + + # Only print saved metrics (skip inference and evaluation) + print_only: false + +# ============================================================================== +# Inference Configuration +# ============================================================================== +inference: + # Number of parallel workers for TSDF fusion + num_fusion_workers: 4 + + # Enable debug mode with verbose output + debug: false + +# ============================================================================== +# Preset Configurations +# ============================================================================== +# These can be activated via command line: --preset full_eval + +presets: + # Full evaluation on all 6 datasets + full_eval: + datasets: [eth3d, 7scenes, scannetpp, hiroom, dtu, dtu64] + modes: [pose, recon_unposed, recon_posed] + + # Pose-only evaluation + pose_only: + datasets: [eth3d, 7scenes, scannetpp, hiroom, dtu64] + modes: [pose] + + # Reconstruction-only evaluation (5 datasets, excluding dtu64) + recon_only: + datasets: [eth3d, 7scenes, scannetpp, hiroom, dtu] + modes: [recon_unposed, recon_posed] + + # Quick test (single scene per dataset) + quick_test: + datasets: [eth3d] + modes: [pose, recon_unposed] + scenes: [courtyard] + diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/bench/dataset.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/bench/dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..2f30a0f96d7414f0ec086e65f37d3fb1ef8ec31e --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/bench/dataset.py @@ -0,0 +1,136 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Base dataset class for benchmark evaluation. + +All dataset implementations should inherit from this class and implement +the required abstract methods. +""" + +import os +import time +from abc import abstractmethod +from typing import Dict as TDict + +import numpy as np +import torch +from addict import Dict + +from depth_anything_3.bench.utils import compute_pose +from depth_anything_3.utils.geometry import as_homogeneous + + +def _wait_for_file_ready(path: str, timeout: float = 3.0, interval: float = 0.2) -> None: + """Wait until file size stabilizes for 2 consecutive checks.""" + last_size = -1 + stable_count = 0 + start = time.time() + while time.time() - start < timeout: + time.sleep(interval) + size = os.path.getsize(path) + if size == last_size and size > 0: + stable_count += 1 + if stable_count >= 2: # Need 2 consecutive stable checks + return + else: + stable_count = 0 + last_size = size + + +class Dataset: + """ + Base class for all benchmark datasets. + + Subclasses must implement: + - SCENES: List of scene identifiers + - data_root: Path to dataset root + - get_data(scene): Return scene data (images, intrinsics, extrinsics, etc.) + - eval3d(scene, fuse_path): Evaluate 3D reconstruction + - fuse3d(scene, result_path, fuse_path, mode): Fuse depth maps into point cloud + + Optional overrides: + - eval_pose(scene, result_path): Evaluate pose estimation (default provided) + """ + + # Subclasses should define these + SCENES: list = [] + data_root: str = "" + + def __init__(self): + pass + + def eval_pose(self, scene: str, result_path: str) -> TDict[str, float]: + """ + Evaluate camera pose estimation accuracy. + + Args: + scene: Scene identifier + result_path: Path to .npz file containing predicted extrinsics + + Returns: + Dict with pose metrics (auc30, auc15, auc05, auc03) + """ + _wait_for_file_ready(result_path) + pred = np.load(result_path) + gt = self.get_data(scene) + return compute_pose( + torch.from_numpy(as_homogeneous(pred["extrinsics"])), + torch.from_numpy(as_homogeneous(gt["extrinsics"])), + ) + + @abstractmethod + def get_data(self, scene: str) -> Dict: + """ + Get scene data including images, camera parameters, and auxiliary info. + + Args: + scene: Scene identifier + + Returns: + Dict with: + - image_files: List[str] - paths to images + - extrinsics: np.ndarray [N, 4, 4] - camera extrinsics (world-to-camera) + - intrinsics: np.ndarray [N, 3, 3] - camera intrinsics + - aux: Dict - auxiliary data (masks, GT paths, etc.) + """ + raise NotImplementedError + + @abstractmethod + def eval3d(self, scene: str, fuse_path: str) -> TDict[str, float]: + """ + Evaluate 3D reconstruction quality against ground truth. + + Args: + scene: Scene identifier + fuse_path: Path to fused point cloud (.ply) + + Returns: + Dict with reconstruction metrics (e.g., acc, comp, overall) + """ + raise NotImplementedError + + @abstractmethod + def fuse3d(self, scene: str, result_path: str, fuse_path: str, mode: str) -> None: + """ + Fuse per-view depth maps into a single point cloud. + + Args: + scene: Scene identifier + result_path: Path to .npz file with predicted depths and poses + fuse_path: Output path for fused point cloud (.ply) + mode: Fusion mode ("recon_unposed" or "recon_posed") + """ + raise NotImplementedError + diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/bench/datasets/__init__.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/bench/datasets/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2e9f464300c07432fc515fd1236a9883f1d8cd69 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/bench/datasets/__init__.py @@ -0,0 +1,21 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Benchmark dataset implementations. + +Datasets are auto-registered via decorators when imported. +Add new dataset files here and they will be automatically discovered. +""" + diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/bench/datasets/dtu.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/bench/datasets/dtu.py new file mode 100644 index 0000000000000000000000000000000000000000..4d07c91577b3e29786471331c55f4609adb6c112 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/bench/datasets/dtu.py @@ -0,0 +1,681 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +DTU Benchmark dataset implementation. + +DTU is a multi-view stereo benchmark for 3D reconstruction evaluation. +Reference: https://roboimagedata.compute.dtu.dk/ + +Note: DepthAnything3 was never trained on any images from DTU. +""" + +import glob +import os +from typing import Dict as TDict, List + +import numpy as np +import open3d as o3d +import torch +import torch.nn.functional as F +from addict import Dict +from PIL import Image +from plyfile import PlyData +from scipy.io import loadmat +from sklearn import neighbors as skln +from tqdm import tqdm + +from depth_anything_3.bench.dataset import Dataset +from depth_anything_3.bench.registries import MONO_REGISTRY, MV_REGISTRY +from depth_anything_3.utils.constants import ( + DTU_DIST_THRESH, + DTU_EVAL_DATA_ROOT, + DTU_MAX_POINTS, + DTU_NUM_CONSIST, + DTU_SCENES, +) +from depth_anything_3.utils.pose_align import align_poses_umeyama + + +@MV_REGISTRY.register(name="dtu") +@MONO_REGISTRY.register(name="dtu") +class DTU(Dataset): + """ + DTU Benchmark dataset wrapper for DepthAnything3 evaluation. + + Supports: + - Camera pose estimation evaluation (AUC metrics) + - 3D reconstruction evaluation (accuracy, completeness, overall) + - Point cloud fusion from depth maps + + The dataset uses MVSNet evaluation protocol: + https://drive.google.com/file/d/1rX0EXlUL4prRxrRu2DgLJv2j7-tpUD4D/view + """ + + data_root = DTU_EVAL_DATA_ROOT + SCENES = DTU_SCENES + + # Evaluation/triangulation hyperparameters from constants + dist_thresh = DTU_DIST_THRESH + num_consist = DTU_NUM_CONSIST + + # ------------------------------ + # Public API + # ------------------------------ + + def read_cam_file(self, filename: str) -> tuple: + """ + Read DTU camera file containing extrinsics and intrinsics. + + Args: + filename: Path to camera text file + + Returns: + Tuple of (intrinsics [3,3], extrinsics [4,4]) + """ + with open(filename) as f: + lines = [line.rstrip() for line in f.readlines()] + extrinsics = np.fromstring(" ".join(lines[1:5]), dtype=np.float32, sep=" ").reshape((4, 4)) + intrinsics = np.fromstring(" ".join(lines[7:10]), dtype=np.float32, sep=" ").reshape((3, 3)) + return intrinsics, extrinsics + + def get_data(self, scene: str) -> Dict: + """ + Collect per-view image paths, intrinsics/extrinsics, and GT masks. + + Args: + scene: Scene identifier (e.g., "scan1") + + Returns: + Dict with: + - image_files: List[str] - paths to images + - extrinsics: np.ndarray [N, 4, 4] + - intrinsics: np.ndarray [N, 3, 3] + - aux.mask_files: List[str] - paths to depth masks + """ + rgb_folder = os.path.join(self.data_root, "Rectified", scene) + camera_folder = os.path.join(self.data_root, "Cameras") + + files = sorted(glob.glob(os.path.join(rgb_folder, "*.png"))) + # Reorder: place index 33 first (reference view convention) + files = [files[33]] + files[:33] + files[34:] + + out = Dict( + { + "image_files": files, + "extrinsics": [], + "intrinsics": [], + "aux": Dict({"mask_files": []}), + } + ) + + for rgb_file in files: + basename = os.path.basename(rgb_file) + file_idx = basename.split("_")[1] + cam_idx = depth_idx = int(file_idx) - 1 + + mask_file = self._depth_mask_path(scene, depth_idx) + proj_mat_filename = os.path.join(camera_folder, f"{cam_idx:0>8}_cam.txt") + + ixt, ext = self.read_cam_file(proj_mat_filename) + out.extrinsics.append(ext) + out.intrinsics.append(ixt) + out.aux.mask_files.append(mask_file) + + out.extrinsics = np.asarray(out.extrinsics, dtype=np.float32) + out.intrinsics = np.asarray(out.intrinsics, dtype=np.float32) + return out + + def get_3dgtpath(self, scene: str) -> str: + """Get path to ground truth point cloud for a scene.""" + scene_id = int(scene[4:]) + return os.path.join(self.data_root, f"Points/stl/stl{scene_id:03}_total.ply") + + def eval3d(self, scene: str, fuse_path: str, use_gpu: bool = False) -> TDict[str, float]: + """ + Evaluate fused point cloud against DTU GT with ObsMask/Plane. + + Args: + scene: Scene identifier + fuse_path: Path to fused point cloud + use_gpu: If True, use GPU-accelerated distance computation (faster but may have minor numerical differences) + + Returns: + Dict with metrics: {"comp": float, "acc": float, "overall": float} + """ + scene_id = int(scene[4:]) + gt_ply = os.path.join(self.data_root, f"Points/stl/stl{scene_id:03}_total.ply") + mask_file = os.path.join( + self.data_root, f"SampleSet/mvs_data/ObsMask/ObsMask{scene_id}_10.mat" + ) + plane_file = os.path.join( + self.data_root, f"SampleSet/mvs_data/ObsMask/Plane{scene_id}.mat" + ) + result = self._evaluate_reconstruction( + scene, fuse_path, gt_ply, mask_file, plane_file, use_gpu=use_gpu + ) + return {"comp": result[0], "acc": result[1], "overall": result[2]} + + def load_masks(self, mask_files: List[str]) -> np.ndarray: + """ + Load DTU depth validity masks. + + Args: + mask_files: List of paths to mask images + + Returns: + Boolean array [N, H, W] indicating valid depth regions + """ + masks = [] + for mask_file in mask_files: + mask = Image.open(mask_file) + mask = np.array(mask, dtype=np.float32) + masks.append(mask > 10) + return np.asarray(masks) + + def fuse3d(self, scene: str, result_path: str, fuse_path: str, mode: str) -> None: + """ + Fuse per-view depths into a point cloud and save to PLY. + + Args: + scene: Scene identifier (e.g., "scan114") + result_path: Path to npz file containing predicted depths/poses + fuse_path: Output path for fused point cloud (.ply) + mode: "recon_unposed" or "recon_posed" + """ + gt_data = self.get_data(scene) + pred_data = Dict({k: v for k, v in np.load(result_path).items()}) + masks = self.load_masks(gt_data.aux.mask_files) + + if mode == "recon_unposed": + depths, intrinsics, extrinsics = self._prep_unposed(pred_data, gt_data, masks) + elif mode == "recon_posed": + depths, intrinsics, extrinsics = self._prep_posed(pred_data, gt_data, masks) + else: + raise ValueError(f"Invalid mode: {mode}") + + proj_mat = self._build_proj_mats(intrinsics, extrinsics) + + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + dtype = torch.float32 + depths_t = torch.from_numpy(depths).to(device=device, dtype=dtype).unsqueeze(1) + proj_t = torch.from_numpy(proj_mat).to(device=device, dtype=dtype) + height, width = depths_t.shape[-2:] + + points: List[np.ndarray] = [] + for idx in range(len(gt_data.image_files)): + if mode == "recon_unposed": + # Simple unfiltered back-projection per frame + cur_p_pcd = self._generate_points_from_depth( + depths_t[idx : idx + 1], proj_t[idx : idx + 1] + ) + mask = (depths_t[idx : idx + 1] > 0.001).squeeze() + cur_p_pcd = cur_p_pcd[:, :, mask] + no_filter_pc = cur_p_pcd.squeeze(0).permute(1, 0).cpu().numpy() + points.append(no_filter_pc) + else: # recon_posed + final_pc = self._fuse_consistent_points(depths_t, proj_t, idx, height, width) + points.append(final_pc) + + # Concatenate and optionally downsample to hard cap + points_np = np.concatenate(points, axis=0) + points_np = self._cap_points(points_np, max_points=DTU_MAX_POINTS) + + os.makedirs(os.path.dirname(fuse_path), exist_ok=True) + pcd = o3d.geometry.PointCloud() + pcd.points = o3d.utility.Vector3dVector(points_np) + o3d.io.write_point_cloud(fuse_path, pcd) + + # ------------------------------ + # Geometry helpers + # ------------------------------ + + def _generate_points_from_depth( + self, depth: torch.Tensor, proj: torch.Tensor + ) -> torch.Tensor: + """ + Back-project depth map into 3D world coordinates. + + Args: + depth: Depth tensor [B, 1, H, W] + proj: Projection matrix [B, 4, 4] = [[K@R, K@t], [0,0,0,1]] + + Returns: + Point cloud tensor [B, 3, H, W] + """ + batch, height, width = depth.shape[0], depth.shape[2], depth.shape[3] + inv_proj = torch.inverse(proj) + rot = inv_proj[:, :3, :3] + trans = inv_proj[:, :3, 3:4] + + y, x = torch.meshgrid( + [ + torch.arange(0, height, dtype=torch.float32, device=depth.device), + torch.arange(0, width, dtype=torch.float32, device=depth.device), + ], + indexing="ij", + ) + y, x = y.contiguous(), x.contiguous() + y, x = y.view(height * width), x.view(height * width) + xyz = torch.stack((x, y, torch.ones_like(x))) + xyz = torch.unsqueeze(xyz, 0).repeat(batch, 1, 1) + rot_xyz = torch.matmul(rot, xyz) + rot_depth_xyz = rot_xyz * depth.view(batch, 1, -1) + proj_xyz = rot_depth_xyz + trans.view(batch, 3, 1) + return proj_xyz.view(batch, 3, height, width) + + def _homo_warping( + self, + src_fea: torch.Tensor, + src_proj: torch.Tensor, + ref_proj: torch.Tensor, + depth_values: torch.Tensor, + ) -> torch.Tensor: + """ + Homography warping for multi-view consistency checking. + + Args: + src_fea: Source features [B, C, H, W] + src_proj: Source projection [B, 4, 4] + ref_proj: Reference projection [B, 4, 4] + depth_values: Depth values [B, Ndepth] or [B, Ndepth, H, W] + + Returns: + Warped features [B, C, H, W] + """ + batch, channels = src_fea.shape[0], src_fea.shape[1] + height, width = src_fea.shape[2], src_fea.shape[3] + + with torch.no_grad(): + proj = torch.matmul(src_proj, torch.inverse(ref_proj)) + rot = proj[:, :3, :3] + trans = proj[:, :3, 3:4] + + y, x = torch.meshgrid( + [ + torch.arange(0, height, dtype=torch.float32, device=src_fea.device), + torch.arange(0, width, dtype=torch.float32, device=src_fea.device), + ], + indexing="ij", + ) + y, x = y.contiguous(), x.contiguous() + y, x = y.view(height * width), x.view(height * width) + xyz = torch.stack((x, y, torch.ones_like(x))) + xyz = torch.unsqueeze(xyz, 0).repeat(batch, 1, 1) + rot_xyz = torch.matmul(rot, xyz) + + rot_depth_xyz = rot_xyz.unsqueeze(2) * depth_values.view(-1, 1, 1, height * width) + proj_xyz = rot_depth_xyz + trans.view(batch, 3, 1, 1) + proj_xy = proj_xyz[:, :2, :, :] / proj_xyz[:, 2:3, :, :] + proj_x_normalized = proj_xy[:, 0, :, :] / ((width - 1) / 2) - 1 + proj_y_normalized = proj_xy[:, 1, :, :] / ((height - 1) / 2) - 1 + grid = torch.stack((proj_x_normalized, proj_y_normalized), dim=3) + + warped_src_fea = F.grid_sample( + src_fea, + grid.view(batch, height, width, 2), + mode="bilinear", + padding_mode="zeros", + align_corners=True, + ) + return warped_src_fea.view(batch, channels, height, width) + + def _filter_depth( + self, + ref_depth: torch.Tensor, + src_depths: torch.Tensor, + ref_proj: torch.Tensor, + src_projs: torch.Tensor, + ) -> tuple: + """ + Compute geometric consistency between reference and source depths. + + Args: + ref_depth: Reference depth [1, 1, H, W] + src_depths: Source depths [B, 1, H, W] + ref_proj: Reference projection [1, 4, 4] + src_projs: Source projections [B, 4, 4] + + Returns: + Tuple of (ref_pc, aligned_pcs, dist) + """ + ref_pc = self._generate_points_from_depth(ref_depth, ref_proj) + src_pcs = self._generate_points_from_depth(src_depths, src_projs) + aligned_pcs = self._homo_warping(src_pcs, src_projs, ref_proj, ref_depth) + x_2 = (ref_pc[:, 0] - aligned_pcs[:, 0]) ** 2 + y_2 = (ref_pc[:, 1] - aligned_pcs[:, 1]) ** 2 + z_2 = (ref_pc[:, 2] - aligned_pcs[:, 2]) ** 2 + dist = torch.sqrt(x_2 + y_2 + z_2).unsqueeze(1) + return ref_pc, aligned_pcs, dist + + def _extract_points( + self, pc: torch.Tensor, mask: torch.Tensor, rgb: np.ndarray = None + ) -> np.ndarray: + """Extract masked points from a dense grid.""" + pc = pc.cpu().numpy() + mask = mask.cpu().numpy().reshape(-1) + pc = pc.reshape(-1, 3) + points = pc[np.where(mask)] + if rgb is not None: + rgb = rgb.reshape(-1, 3) + colors = rgb[np.where(mask)] + return np.concatenate([points, colors], axis=1) + return points + + # ------------------------------ + # 3D Reconstruction Evaluation + # ------------------------------ + + def _evaluate_reconstruction( + self, + scanid: str, + pred_ply: str, + gt_ply: str, + mask_file: str, + plane_file: str, + down_dense: float = 0.2, + patch: int = 60, + max_dist: int = 20, + use_gpu: bool = False, + ) -> tuple: + """ + Compute accuracy, completeness, and overall metrics for one scan. + + Args: + scanid: Scan identifier + pred_ply: Predicted point cloud path or array + gt_ply: Ground truth point cloud path or array + mask_file: ObsMask file path + plane_file: Plane file path + down_dense: Downsample density (min distance between points) + patch: Patch size for boundary + max_dist: Outlier threshold in mm + use_gpu: If True, use GPU-accelerated distance computation + + Returns: + Tuple of (mean_d2s, mean_s2d, overall) + """ + thresh = down_dense + + # Load and downsample predicted point cloud + data_pcd = self._read_ply(pred_ply) if isinstance(pred_ply, str) else pred_ply + # Use fixed seed for reproducibility + shuffle_rng = np.random.default_rng(seed=42) + shuffle_rng.shuffle(data_pcd, axis=0) + + # Downsample point cloud + nn_engine = skln.NearestNeighbors( + n_neighbors=1, radius=thresh, algorithm="kd_tree", n_jobs=-1 + ) + nn_engine.fit(data_pcd) + rnn_idxs = nn_engine.radius_neighbors(data_pcd, radius=thresh, return_distance=False) + mask = np.ones(data_pcd.shape[0], dtype=np.bool_) + for curr, idxs in enumerate(rnn_idxs): + if mask[curr]: + mask[idxs] = 0 + mask[curr] = 1 + data_down = data_pcd[mask] + + # Restrict to observed volume (ObsMask) + obs_mask_file = loadmat(mask_file) + ObsMask, BB, Res = (obs_mask_file[attr] for attr in ["ObsMask", "BB", "Res"]) + BB = BB.astype(np.float32) + + inbound = ((data_down >= BB[:1] - patch) & (data_down < BB[1:] + patch * 2)).sum( + axis=-1 + ) == 3 + data_in = data_down[inbound] + + data_grid = np.around((data_in - BB[:1]) / Res).astype(np.int32) + grid_inbound = ((data_grid >= 0) & (data_grid < np.expand_dims(ObsMask.shape, 0))).sum( + axis=-1 + ) == 3 + data_grid_in = data_grid[grid_inbound] + in_obs = ObsMask[data_grid_in[:, 0], data_grid_in[:, 1], data_grid_in[:, 2]].astype( + np.bool_ + ) + data_in_obs = data_in[grid_inbound][in_obs] + + # Compute accuracy (pred -> GT) and completeness (GT -> pred) + stl = self._read_ply(gt_ply) if isinstance(gt_ply, str) else gt_ply + + if use_gpu and torch.cuda.is_available(): + # GPU-accelerated distance computation + mean_d2s = self._knn_dist_gpu(data_in_obs, stl, max_dist) + else: + # CPU version (original, for exact reproduction) + nn_engine.fit(stl) + dist_d2s, _ = nn_engine.kneighbors(data_in_obs, n_neighbors=1, return_distance=True) + mean_d2s = dist_d2s[dist_d2s < max_dist].mean() + + ground_plane = loadmat(plane_file)["P"] + stl_hom = np.concatenate([stl, np.ones_like(stl[:, :1])], -1) + above = (ground_plane.reshape((1, 4)) * stl_hom).sum(-1) > 0 + stl_above = stl[above] + + if use_gpu and torch.cuda.is_available(): + # GPU-accelerated distance computation + mean_s2d = self._knn_dist_gpu(stl_above, data_in, max_dist) + else: + # CPU version (original, for exact reproduction) + nn_engine.fit(data_in) + dist_s2d, _ = nn_engine.kneighbors(stl_above, n_neighbors=1, return_distance=True) + mean_s2d = dist_s2d[dist_s2d < max_dist].mean() + + overall = (mean_d2s + mean_s2d) / 2 + return mean_d2s, mean_s2d, overall + + def _knn_dist_gpu( + self, + query: np.ndarray, + target: np.ndarray, + max_dist: float, + batch_size: int = 8192, + target_batch_size: int = 50000, + ) -> float: + """ + GPU-accelerated nearest neighbor distance computation. + + Args: + query: Query points [N, 3] + target: Target points [M, 3] + max_dist: Outlier threshold + batch_size: Batch size for query to avoid OOM (tuned for 16GB GPU) + target_batch_size: Batch size for target to avoid OOM + + Returns: + Mean distance (excluding outliers) + """ + device = torch.device("cuda") + + all_min_dists = [] + n_query_batches = (len(query) + batch_size - 1) // batch_size + n_target_batches = (len(target) + target_batch_size - 1) // target_batch_size + + # Pre-load target batches to GPU to avoid repeated transfers + # Memory: ~50000 pts * 3 coords * 4 bytes * n_batches + target_batches = [] + for j in range(0, len(target), target_batch_size): + target_batch = target[j : j + target_batch_size] + target_t = torch.from_numpy(target_batch).float().to(device) + target_batches.append(target_t) + + with tqdm(total=n_query_batches, desc=" GPU KNN", leave=False, ncols=100) as pbar: + for i in range(0, len(query), batch_size): + batch = query[i : i + batch_size] + query_t = torch.from_numpy(batch).float().to(device) + + # Compute distances to all target batches + # Memory peak: query_batch × target_batch_size × 4 bytes + # = 8192 × 50000 × 4 = ~1.6 GB per cdist call + batch_min_dists = [] + for target_t in target_batches: + dists = torch.cdist(query_t, target_t) + batch_min_dists.append(dists.min(dim=1).values) + del dists # Free immediately + + # Get minimum distance across all target batches + min_dists = torch.stack(batch_min_dists, dim=1).min(dim=1).values + all_min_dists.append(min_dists.cpu().numpy()) + + del query_t, min_dists, batch_min_dists + pbar.update(1) + + # Clean up target batches + for target_t in target_batches: + del target_t + torch.cuda.empty_cache() + + all_min_dists = np.concatenate(all_min_dists) + return all_min_dists[all_min_dists < max_dist].mean() + + def _read_ply(self, file: str) -> np.ndarray: + """Read point cloud from PLY file.""" + data = PlyData.read(file) + vertex = data["vertex"] + return np.stack([vertex["x"], vertex["y"], vertex["z"]], axis=-1) + + # ------------------------------ + # Private helpers + # ------------------------------ + + def _depth_mask_path(self, scene: str, depth_idx: int) -> str: + """Get path to depth mask for a scene and frame.""" + return os.path.join( + self.data_root, "depth_raw", "Depths", scene, f"depth_visual_{depth_idx:04d}.png" + ) + + def _prep_unposed( + self, pred_data: Dict, gt_data: Dict, masks: np.ndarray + ) -> tuple: + """ + Prepare depths/intrinsics/extrinsics for recon_unposed mode. + + Applies Umeyama scale, rescales intrinsics if depth resolution differs, + and zeroes invalid-mask depths (nearest interpolation as in paper). + """ + _, _, scale, extrinsics = align_poses_umeyama( + gt_data.extrinsics.copy(), + pred_data.extrinsics.copy(), + ransac=True, + return_aligned=True, + random_state=42, + ) + depths = pred_data.depth * scale + intrinsics = pred_data.intrinsics.copy() + + if depths.shape[-2:] != masks.shape[-2:]: + # When resizing depths to mask size, adjust intrinsics accordingly + sx = masks.shape[-1] / depths.shape[-1] + sy = masks.shape[-2] / depths.shape[-2] + intrinsics[:, 0:1] *= sx + intrinsics[:, 1:2] *= sy + depths = F.interpolate( + torch.from_numpy(depths)[None].float(), + size=(masks.shape[-2], masks.shape[-1]), + mode="nearest", + )[0].numpy() + depths[masks == False] = 0.0 # noqa: E712 + + return depths, intrinsics, extrinsics + + def _prep_posed( + self, pred_data: Dict, gt_data: Dict, masks: np.ndarray + ) -> tuple: + """ + Prepare depths/intrinsics/extrinsics for recon_posed mode. + + Uses GT intrinsics/extrinsics but aligns scale via Umeyama. + Same mask order as other datasets: mask BEFORE scale. + """ + _, _, scale, _ = align_poses_umeyama( + gt_data.extrinsics.copy(), + pred_data.extrinsics.copy(), + ransac=True, + return_aligned=True, + random_state=42, + ) + depths = pred_data.depth.copy() + intrinsics = gt_data.intrinsics.copy() + extrinsics = gt_data.extrinsics.copy() + + if depths.shape[-2:] != masks.shape[-2:]: + depths = F.interpolate( + torch.from_numpy(depths)[None].float(), + size=(masks.shape[-2], masks.shape[-1]), + mode="nearest", + )[0].numpy() + + # Mask BEFORE scale (same as other datasets) + depths[masks == False] = 0.0 # noqa: E712 + depths = depths * scale + + return depths, intrinsics, extrinsics + + def _build_proj_mats( + self, intrinsics: np.ndarray, extrinsics: np.ndarray + ) -> np.ndarray: + """Compute per-view 4x4 projection matrices from K and [R|t].""" + proj_mat_list = [] + for i in range(len(intrinsics)): + proj_mat = np.eye(4, dtype=np.float32) + proj_mat[:3, :4] = np.dot(intrinsics[i], extrinsics[i][:3]) + proj_mat_list.append(proj_mat) + return np.stack(proj_mat_list, axis=0) + + def _fuse_consistent_points( + self, + depths_t: torch.Tensor, + proj_t: torch.Tensor, + idx: int, + H: int, + W: int, + ) -> np.ndarray: + """Fuse points consistent across multiple source views for a reference index.""" + device, dtype = depths_t.device, depths_t.dtype + pc_buff = torch.zeros((3, H, W), device=device, dtype=dtype) + val_cnt = torch.zeros((1, H, W), device=device, dtype=dtype) + + j = 0 + batch_size = 20 + tot_frame = depths_t.shape[0] + while True: + ref_pc, pcs, dist = self._filter_depth( + ref_depth=depths_t[idx : idx + 1], + src_depths=depths_t[j : min(j + batch_size, tot_frame)], + ref_proj=proj_t[idx : idx + 1], + src_projs=proj_t[j : min(j + batch_size, tot_frame)], + ) + masks = (dist < self.dist_thresh).float() + masked_pc = pcs * masks + pc_buff += masked_pc.sum(dim=0, keepdim=False) + val_cnt += masks.sum(dim=0, keepdim=False) + j += batch_size + if j >= tot_frame: + break + + final_mask = (val_cnt >= self.num_consist).squeeze(0) + avg_points = torch.div(pc_buff, val_cnt).permute(1, 2, 0) + final_pc = self._extract_points(avg_points, final_mask) + return final_pc + + def _cap_points(self, points: np.ndarray, max_points: int) -> np.ndarray: + """Downsample points if exceeding max count.""" + if len(points) <= max_points: + return points + # Use fixed seed for reproducibility + rng = np.random.default_rng(seed=42) + random_idx = rng.choice(len(points), max_points, replace=False) + return points[random_idx] + diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/bench/datasets/dtu64.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/bench/datasets/dtu64.py new file mode 100644 index 0000000000000000000000000000000000000000..36ebb63223e1140dff9ff8caaee26cfcefe1200f --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/bench/datasets/dtu64.py @@ -0,0 +1,182 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +DTU-64 Dataset implementation for POSE EVALUATION ONLY. + +This is a subset of DTU with 64 images per scene, specifically designed for +camera pose estimation evaluation. It does NOT support 3D reconstruction. + +Note: GT depth loading is not implemented as it's not needed for pose evaluation. +""" + +import glob +import os +from typing import Dict as TDict + +import numpy as np +from addict import Dict + +from depth_anything_3.bench.dataset import Dataset +from depth_anything_3.bench.registries import MONO_REGISTRY, MV_REGISTRY +from depth_anything_3.utils.constants import ( + DTU64_CAMERA_ROOT, + DTU64_EVAL_DATA_ROOT, + DTU64_SCENES, +) + + +@MV_REGISTRY.register(name="dtu64") +@MONO_REGISTRY.register(name="dtu64") +class DTU64(Dataset): + """ + DTU-64 Dataset wrapper for DepthAnything3 POSE EVALUATION ONLY. + + This dataset is a subset of DTU with 64 images per scene. + It is specifically designed for camera pose estimation evaluation + and does NOT support 3D reconstruction evaluation. + + Dataset structure: + DTU/scans/ + ├── {scene}/ + │ └── image/ # RGB images (64 per scene) + └── Cameras/ + └── {idx}_cam.txt # Camera parameters + + Supported modes: + - pose: Camera pose estimation evaluation + + NOT supported: + - recon_unposed: 3D reconstruction (no GT depth available) + - recon_posed: 3D reconstruction (no GT depth available) + """ + + data_root = DTU64_EVAL_DATA_ROOT + camera_root = DTU64_CAMERA_ROOT + SCENES = DTU64_SCENES + + def __init__(self): + super().__init__() + self._scene_cache = {} + + # ------------------------------ + # Camera file parsing + # ------------------------------ + + def read_cam_file(self, filename: str) -> tuple: + """ + Read DTU camera file containing extrinsics and intrinsics. + + Args: + filename: Path to camera text file + + Returns: + Tuple of (intrinsics [3,3], extrinsics [4,4]) + """ + with open(filename) as f: + lines = [line.rstrip() for line in f.readlines()] + # extrinsics: line [1,5), 4x4 matrix + extrinsics = np.fromstring(" ".join(lines[1:5]), dtype=np.float32, sep=" ").reshape((4, 4)) + # intrinsics: line [7-10), 3x3 matrix + intrinsics = np.fromstring(" ".join(lines[7:10]), dtype=np.float32, sep=" ").reshape((3, 3)) + return intrinsics, extrinsics + + # ------------------------------ + # Public API + # ------------------------------ + + def get_data(self, scene: str) -> Dict: + """ + Collect per-view image paths, intrinsics/extrinsics for a scene. + + Args: + scene: Scene identifier (e.g., "scan105") + + Returns: + Dict with: + - image_files: List[str] - paths to images (64 per scene) + - extrinsics: np.ndarray [N, 4, 4] - world-to-camera transforms + - intrinsics: np.ndarray [N, 3, 3] - camera intrinsics + - aux: Dict (empty for this dataset) + """ + if scene in self._scene_cache: + return self._scene_cache[scene] + + rgb_folder = os.path.join(self.data_root, scene, "image") + + # Get all PNG files sorted + files = sorted(glob.glob(os.path.join(rgb_folder, "*.png"))) + + # Reorder: place index 33 first (reference view convention) + if len(files) > 33: + files = [files[33]] + files[:33] + files[34:] + + out = Dict({ + "image_files": [], + "extrinsics": [], + "intrinsics": [], + "aux": Dict({}), + }) + + for rgb_file in files: + basename = os.path.basename(rgb_file) + # File naming: "00000033.png" -> cam_idx = 33 + file_idx = basename.split(".")[0] + cam_idx = int(file_idx) + + # Camera file path + cam_file = os.path.join(self.camera_root, f"{cam_idx:0>8}_cam.txt") + + if not os.path.exists(cam_file): + print(f"[DTU-64] Warning: Camera file not found: {cam_file}") + continue + + intrinsics, extrinsics = self.read_cam_file(cam_file) + + out.image_files.append(rgb_file) + out.extrinsics.append(extrinsics) + out.intrinsics.append(intrinsics) + + out.extrinsics = np.asarray(out.extrinsics, dtype=np.float32) + out.intrinsics = np.asarray(out.intrinsics, dtype=np.float32) + + print(f"[DTU-64] {scene}: {len(out.image_files)} images (pose evaluation only)") + + self._scene_cache[scene] = out + return out + + def eval3d(self, scene: str, fuse_path: str) -> TDict[str, float]: + """ + NOT SUPPORTED for DTU-64. + + DTU-64 is only for pose evaluation, not 3D reconstruction. + """ + raise NotImplementedError( + "DTU-64 dataset is for POSE EVALUATION ONLY. " + "3D reconstruction evaluation is not supported. " + "Use the standard 'dtu' dataset for 3D reconstruction evaluation." + ) + + def fuse3d(self, scene: str, result_path: str, fuse_path: str, mode: str) -> None: + """ + NOT SUPPORTED for DTU-64. + + DTU-64 is only for pose evaluation, not 3D reconstruction. + """ + raise NotImplementedError( + "DTU-64 dataset is for POSE EVALUATION ONLY. " + "3D reconstruction (fuse3d) is not supported. " + "Use the standard 'dtu' dataset for 3D reconstruction." + ) + diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/bench/datasets/eth3d.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/bench/datasets/eth3d.py new file mode 100644 index 0000000000000000000000000000000000000000..b39069517cca9dadafd54d881e8c119c944af526 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/bench/datasets/eth3d.py @@ -0,0 +1,594 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +ETH3D Benchmark dataset implementation. + +ETH3D is a multi-view stereo benchmark with high-resolution images and +accurate ground truth geometry from laser scanning. +Reference: https://www.eth3d.net/ + +Evaluation metrics: +- 3D reconstruction: Accuracy, Completeness, F-score +- Camera pose estimation: AUC metrics +""" + +import glob +import os +from typing import Dict as TDict, List, Optional + +import cv2 +import numpy as np +import open3d as o3d +import torch +import torch.nn.functional as F +from addict import Dict +from PIL import Image + +from depth_anything_3.bench.dataset import Dataset, _wait_for_file_ready +from depth_anything_3.bench.registries import MONO_REGISTRY, MV_REGISTRY +from depth_anything_3.bench.utils import ( + create_tsdf_volume, + evaluate_3d_reconstruction, + fuse_depth_to_tsdf, + quat2rotmat, + sample_points_from_mesh, +) +from depth_anything_3.utils.constants import ( + ETH3D_DOWN_SAMPLE, + ETH3D_EVAL_DATA_ROOT, + ETH3D_EVAL_THRESHOLD, + ETH3D_FILTER_KEYS, + ETH3D_MAX_DEPTH, + ETH3D_SAMPLING_NUMBER, + ETH3D_SCENES, + ETH3D_SDF_TRUNC, + ETH3D_VOXEL_LENGTH, +) +from depth_anything_3.utils.pose_align import align_poses_umeyama + + +@MV_REGISTRY.register(name="eth3d") +@MONO_REGISTRY.register(name="eth3d") +class ETH3D(Dataset): + """ + ETH3D Benchmark dataset wrapper for DepthAnything3 evaluation. + + Supports: + - Camera pose estimation evaluation (AUC metrics) + - 3D reconstruction evaluation (Accuracy, Completeness, F-score) + - TSDF-based point cloud fusion + + Dataset structure: + eth3d/multiview/ + ├── scene_name/ + │ ├── images/ # RGB images + │ ├── dslr_calibration_jpg/ + │ │ ├── cameras.txt # Camera intrinsics + │ │ └── images.txt # Camera poses + │ ├── combined_mesh.ply # Ground truth mesh + │ └── ground_truth_depth/ # GT depth maps (optional) + """ + + data_root = ETH3D_EVAL_DATA_ROOT + SCENES = ETH3D_SCENES + + # Evaluation hyperparameters from constants + max_depth = ETH3D_MAX_DEPTH + sampling_number = ETH3D_SAMPLING_NUMBER + voxel_length = ETH3D_VOXEL_LENGTH + sdf_trunc = ETH3D_SDF_TRUNC + eval_threshold = ETH3D_EVAL_THRESHOLD + down_sample = ETH3D_DOWN_SAMPLE + + def __init__(self): + super().__init__() + # Pre-load scene data for efficiency + self._scene_cache = {} + + # ------------------------------ + # Camera file parsing + # ------------------------------ + + def _parse_cameras_txt(self, filepath: str) -> dict: + """ + Parse COLMAP-style cameras.txt file. + + Returns: + Dict mapping camera_id to intrinsic parameters + """ + camera_dict = {} + with open(filepath) as f: + lines = f.readlines() + for line in lines[3:]: # Skip header + line = line.strip() + if not line or line.startswith("#"): + continue + parts = line.split() + if len(parts) < 8: + continue + cam_id = parts[0] + # Format: ID, MODEL, WIDTH, HEIGHT, fx, fy, cx, cy, [distortion params...] + camera_dict[cam_id] = { + "width": float(parts[2]), + "height": float(parts[3]), + "fx": float(parts[4]), + "fy": float(parts[5]), + "cx": float(parts[6]), + "cy": float(parts[7]), + } + return camera_dict + + def _parse_images_txt(self, filepath: str) -> dict: + """ + Parse COLMAP-style images.txt file. + + Returns: + Dict mapping image path to pose parameters + """ + pose_dict = {} + with open(filepath) as f: + lines = f.readlines() + for idx, line in enumerate(lines[4:]): # Skip header + line = line.strip() + if not line or line.startswith("#"): + continue + # Every other line contains pose info + if idx % 2 == 0: + parts = line.split() + if len(parts) < 10: + continue + # Format: IMAGE_ID, QW, QX, QY, QZ, TX, TY, TZ, CAMERA_ID, NAME + image_id = parts[0] + qw, qx, qy, qz = float(parts[1]), float(parts[2]), float(parts[3]), float(parts[4]) + tx, ty, tz = float(parts[5]), float(parts[6]), float(parts[7]) + camera_id = parts[8] + name = parts[9] + pose_dict[name] = { + "image_id": image_id, + "quat": [qw, qx, qy, qz], + "trans": [tx, ty, tz], + "camera_id": camera_id, + } + return pose_dict + + def _should_filter_image(self, scene: str, image_name: str) -> bool: + """Check if image should be filtered out based on known problematic views.""" + filter_keys = ETH3D_FILTER_KEYS.get(scene, []) + for key in filter_keys: + if image_name.endswith(key): + return True + return False + + # ------------------------------ + # Public API + # ------------------------------ + + def get_data(self, scene: str) -> Dict: + """ + Collect per-view image paths, intrinsics/extrinsics for a scene. + + Args: + scene: Scene identifier (e.g., "courtyard") + + Returns: + Dict with: + - image_files: List[str] - paths to images + - extrinsics: np.ndarray [N, 4, 4] - world-to-camera transforms + - intrinsics: np.ndarray [N, 3, 3] - camera intrinsics + - aux: Dict with gt_mesh_path + """ + # Check cache + if scene in self._scene_cache: + return self._scene_cache[scene] + + scene_dir = os.path.join(self.data_root, scene) + + # Parse camera files + cameras_file = os.path.join(scene_dir, "dslr_calibration_jpg", "cameras.txt") + images_file = os.path.join(scene_dir, "dslr_calibration_jpg", "images.txt") + camera_dict = self._parse_cameras_txt(cameras_file) + pose_dict = self._parse_images_txt(images_file) + + # Ground truth mesh path + gt_mesh_path = os.path.join(scene_dir, "combined_mesh.ply") + + out = Dict({ + "image_files": [], + "extrinsics": [], + "intrinsics": [], + "aux": Dict({ + "gt_mesh_path": gt_mesh_path, + "heights": [], + "widths": [], + }), + }) + + # Process each image (preserve original order from images.txt) + filtered_count = 0 + for image_name, pose_info in pose_dict.items(): + # Filter problematic views + if self._should_filter_image(scene, image_name): + filtered_count += 1 + continue + + image_path = os.path.join(scene_dir, "images", image_name) + if not os.path.exists(image_path): + continue + + cam_info = camera_dict.get(pose_info["camera_id"]) + if cam_info is None: + continue + + # Build intrinsics matrix + ixt = np.array([ + [cam_info["fx"], 0, cam_info["cx"]], + [0, cam_info["fy"], cam_info["cy"]], + [0, 0, 1], + ], dtype=np.float32) + + # Build extrinsics matrix (world-to-camera) + # COLMAP format: world point -> camera point + rot = quat2rotmat(pose_info["quat"]) + ext = np.eye(4, dtype=np.float32) + ext[:3, :3] = rot + ext[:3, 3] = pose_info["trans"] + + out.image_files.append(image_path) + out.extrinsics.append(ext) + out.intrinsics.append(ixt) + out.aux.heights.append(cam_info["height"]) + out.aux.widths.append(cam_info["width"]) + + out.extrinsics = np.asarray(out.extrinsics, dtype=np.float32) + out.intrinsics = np.asarray(out.intrinsics, dtype=np.float32) + + # Print scene info + total_images = len(pose_dict) + used_images = len(out.image_files) + print(f"[ETH3D] {scene}: {used_images}/{total_images} images " + f"(filtered {filtered_count}, missing {total_images - used_images - filtered_count})") + + if used_images < 3: + print(f"[ETH3D] ⚠️ WARNING: {scene} has only {used_images} images - evaluation may fail!") + + # Cache result + self._scene_cache[scene] = out + return out + + def eval3d(self, scene: str, fuse_path: str) -> TDict[str, float]: + """ + Evaluate fused point cloud against ETH3D ground truth mesh. + + Args: + scene: Scene identifier + fuse_path: Path to fused point cloud (.ply) + + Returns: + Dict with metrics: acc, comp, overall, precision, recall, fscore + """ + gt_data = self.get_data(scene) + gt_mesh_path = gt_data.aux.gt_mesh_path + + # Load and sample ground truth mesh + gt_mesh = o3d.io.read_triangle_mesh(gt_mesh_path) + gt_pcd = sample_points_from_mesh(gt_mesh, self.sampling_number) + + # Load predicted point cloud + pred_pcd = o3d.io.read_point_cloud(fuse_path) + + # Evaluate using shared utility function + metrics = evaluate_3d_reconstruction( + pred_pcd, + gt_pcd, + threshold=self.eval_threshold, + down_sample=self.down_sample, + ) + + return metrics + + def _load_gt_meta(self, result_path: str) -> Dict: + """ + Load saved GT meta (extrinsics, intrinsics, image_files) for fusion. + + This is needed when frames are sampled, so fuse3d uses the correct + (sampled) GT instead of full dataset GT. + + Args: + result_path: Path to npz file (used to derive gt_meta.npz path) + + Returns: + Dict with GT data, or None if gt_meta.npz doesn't exist + """ + # gt_meta.npz is in the same exports/ directory as results.npz + export_dir = os.path.dirname(result_path) # exports/mini_npz/ + gt_meta_path = os.path.join(os.path.dirname(export_dir), "gt_meta.npz") + + if os.path.exists(gt_meta_path): + data = np.load(gt_meta_path, allow_pickle=True) + return Dict({ + "extrinsics": data["extrinsics"], + "intrinsics": data["intrinsics"], + "image_files": data["image_files"] if "image_files" in data else None, + }) + return None + + def fuse3d(self, scene: str, result_path: str, fuse_path: str, mode: str) -> None: + """ + Fuse per-view depths into a point cloud using TSDF fusion. + + Pipeline: + 1. Load original images (keep original size) + 2. Resize depth to original image size (nearest interpolation) + 3. Adjust intrinsics to original image size + 4. Apply scale alignment and mask invalid depths + 5. TSDF fusion + + Args: + scene: Scene identifier + result_path: Path to npz file with predicted depths/poses + fuse_path: Output path for fused point cloud (.ply) + mode: "recon_unposed" or "recon_posed" + """ + # Try to load saved GT meta (handles frame sampling) + gt_meta = self._load_gt_meta(result_path) + if gt_meta is not None: + gt_data = gt_meta + else: + gt_data = self.get_data(scene) + _wait_for_file_ready(result_path) + pred_data = Dict({k: v for k, v in np.load(result_path).items()}) + + # Load original images (keep original size) + images = [] + orig_sizes = [] # (H, W) for each image + for img_path in gt_data.image_files: + img = cv2.imread(img_path) + img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) + images.append(img) + orig_sizes.append((img.shape[0], img.shape[1])) + + # Prepare depths, intrinsics, extrinsics with resize to original size + if mode == "recon_unposed": + depths, intrinsics, extrinsics = self._prep_unposed( + pred_data, gt_data, orig_sizes, scene=scene + ) + elif mode == "recon_posed": + depths, intrinsics, extrinsics = self._prep_posed( + pred_data, gt_data, orig_sizes, scene=scene + ) + else: + raise ValueError(f"Invalid mode: {mode}") + + images = np.stack(images, axis=0) + + # Create TSDF volume and fuse + volume = create_tsdf_volume( + voxel_length=self.voxel_length, + sdf_trunc=self.sdf_trunc, + ) + mesh = fuse_depth_to_tsdf( + volume, depths, images, intrinsics, extrinsics, max_depth=self.max_depth + ) + + # Sample points from mesh + pcd = sample_points_from_mesh(mesh, self.sampling_number) + + # Save point cloud + os.makedirs(os.path.dirname(fuse_path), exist_ok=True) + o3d.io.write_point_cloud(fuse_path, pcd) + + # ------------------------------ + # Private helpers + # ------------------------------ + + def _prep_unposed( + self, pred_data: Dict, gt_data: Dict, orig_sizes: list, scene: str = None + ) -> tuple: + """ + Prepare depths/intrinsics/extrinsics for recon_unposed mode. + + Pipeline: + 1. Umeyama scale alignment + 2. Load GT mask for each frame + 3. Resize depth to original image size (nearest) + 4. Apply GT mask BEFORE scale + 5. Apply scale + 6. Adjust intrinsics to original image size + """ + # Scale alignment with fixed random_state for reproducibility + _, _, scale, extrinsics = align_poses_umeyama( + gt_data.extrinsics.copy(), + pred_data.extrinsics.copy(), + return_aligned=True, + ransac=True, + random_state=42, + ) + + # Get model output size + model_h, model_w = pred_data.depth.shape[1], pred_data.depth.shape[2] + + # Process each frame + depths_out = [] + intrinsics_out = [] + for i in range(len(pred_data.depth)): + orig_h, orig_w = orig_sizes[i] + image_name = os.path.basename(gt_data.image_files[i]) + + # Resize depth to original image size (nearest interpolation) + depth = cv2.resize( + pred_data.depth[i], + (orig_w, orig_h), + interpolation=cv2.INTER_NEAREST, + ) + + # Load GT mask (apply BEFORE scale) + gt_zero_mask = None + if scene is not None: + gt_zero_mask = self._load_gt_mask(scene, image_name, (orig_h, orig_w)) + + # Mask invalid depths BEFORE scale + depth = self._mask_invalid_depth(depth, gt_zero_mask) + + # Apply scale AFTER mask + depth = depth * scale + + # Adjust intrinsics to original image size + h_ratio = orig_h / model_h + w_ratio = orig_w / model_w + ixt = pred_data.intrinsics[i].copy() + ixt[0, :] *= w_ratio # fx, 0, cx + ixt[1, :] *= h_ratio # 0, fy, cy + + depths_out.append(depth) + intrinsics_out.append(ixt) + + return np.stack(depths_out), np.stack(intrinsics_out), extrinsics + + def _prep_posed( + self, pred_data: Dict, gt_data: Dict, orig_sizes: list, scene: str = None + ) -> tuple: + """ + Prepare depths/intrinsics/extrinsics for recon_posed mode. + + Uses GT intrinsics/extrinsics but aligns depth scale via Umeyama. + Depth is resized to original image size. + """ + # Scale alignment with fixed random_state for reproducibility + _, _, scale, _ = align_poses_umeyama( + gt_data.extrinsics.copy(), + pred_data.extrinsics.copy(), + return_aligned=True, + ransac=True, + random_state=42, + ) + + # Process each frame + depths_out = [] + for i in range(len(pred_data.depth)): + orig_h, orig_w = orig_sizes[i] + image_name = os.path.basename(gt_data.image_files[i]) + + # Resize depth to original image size (nearest interpolation) + depth = cv2.resize( + pred_data.depth[i], + (orig_w, orig_h), + interpolation=cv2.INTER_NEAREST, + ) + + # Load GT mask (apply BEFORE scale) + gt_zero_mask = None + if scene is not None: + gt_zero_mask = self._load_gt_mask(scene, image_name, (orig_h, orig_w)) + + # Mask invalid depths BEFORE scale + depth = self._mask_invalid_depth(depth, gt_zero_mask) + + # Apply scale AFTER mask + depth = depth * scale + + depths_out.append(depth) + + # Use GT intrinsics and extrinsics (already at original image size) + return np.stack(depths_out), gt_data.intrinsics.copy(), gt_data.extrinsics.copy() + + def _load_gt_mask(self, scene: str, image_name: str, shape: tuple) -> np.ndarray: + """ + Load GT mask for masking invalid regions. + + GT mask marks occluded or invalid regions that should be excluded + from depth fusion and evaluation. + + Args: + scene: Scene identifier + image_name: Image filename (e.g., "DSC_0307.JPG") + shape: (height, width) of the image + + Returns: + Boolean mask where True = valid region to keep + """ + h, w = shape + + # GT mask file path + gt_mask_path = os.path.join( + self.data_root, scene, "masks_for_images", "dslr_images", + image_name.replace(".JPG", ".png") + ) + + # GT depth file path (used to determine valid depth regions) + gt_depth_path = os.path.join( + self.data_root, scene, "ground_truth_depth", "dslr_images", image_name + ) + + # Load GT depth + if os.path.exists(gt_depth_path): + gt_depth = np.fromfile(gt_depth_path, dtype=np.float32).reshape(h, w) + else: + gt_depth = np.ones((h, w), dtype=np.float32) + + # Load GT mask + if os.path.exists(gt_mask_path): + gt_mask = cv2.imread(gt_mask_path, cv2.IMREAD_GRAYSCALE) + gt_mask = np.asarray(gt_mask) + else: + gt_mask = np.zeros((h, w), dtype=np.uint8) + + # Compute zero_mask + # gt_mask == 1 means occluded/invalid region + invalid_mask_from_gt = gt_mask == 1 + gt_depth_copy = gt_depth.copy() + gt_depth_copy[gt_mask == 1] = 0 + + invalid_mask_from_gt_depth = np.logical_or(gt_depth_copy == 0, gt_depth_copy == np.inf) + + # zero_mask: valid region that should be kept + zero_mask = np.logical_and( + np.logical_not(invalid_mask_from_gt), + np.logical_not(invalid_mask_from_gt_depth) + ) + + return zero_mask + + def _mask_invalid_depth( + self, depth: np.ndarray, gt_zero_mask: np.ndarray = None + ) -> np.ndarray: + """ + Mask invalid depth values by setting them to 0. + + Logic: + 1. Apply GT mask (if provided) - marks occluded/invalid regions + 2. Mask pred invalid values (nan, inf) + + Args: + depth: Depth map to mask + gt_zero_mask: Optional GT mask (True = valid region) + + Returns: + Masked depth map with invalid regions set to 0 + """ + depth = depth.copy() + + # Apply GT mask first (before scale) + if gt_zero_mask is not None: + # Also mask out invalid pred depth + pred_invalid = np.isnan(depth) | np.isinf(depth) + combined_mask = np.logical_and(gt_zero_mask, np.logical_not(pred_invalid)) + depth = depth * combined_mask.astype(np.float32) + else: + # Fallback: only mask pred invalid values + invalid_mask = np.isnan(depth) | np.isinf(depth) | (depth <= 0) + depth[invalid_mask] = 0.0 + + return depth + diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/bench/datasets/hiroom.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/bench/datasets/hiroom.py new file mode 100644 index 0000000000000000000000000000000000000000..45619f76a4d7409bf5e9674815a10d0bd02085f5 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/bench/datasets/hiroom.py @@ -0,0 +1,440 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +HiRoom Dataset implementation. + +HiRoom is an indoor RGB-D dataset containing ground truth camera poses, +depth maps, and fused point clouds. + +Evaluation metrics: +- 3D reconstruction: Accuracy, Completeness, F-score +- Camera pose estimation: AUC metrics +""" + +import os +from typing import Dict as TDict, List + +import cv2 +import numpy as np +import open3d as o3d +from addict import Dict + +from depth_anything_3.bench.dataset import Dataset, _wait_for_file_ready +from depth_anything_3.bench.registries import MONO_REGISTRY, MV_REGISTRY +from depth_anything_3.bench.utils import ( + create_tsdf_volume, + evaluate_3d_reconstruction, + fuse_depth_to_tsdf, + sample_points_from_mesh, +) +from depth_anything_3.utils.constants import ( + HIROOM_DOWN_SAMPLE, + HIROOM_EVAL_DATA_ROOT, + HIROOM_EVAL_THRESHOLD, + HIROOM_GT_ROOT_PATH, + HIROOM_MAX_DEPTH, + HIROOM_SAMPLING_NUMBER, + HIROOM_SCENE_LIST_PATH, + HIROOM_SDF_TRUNC, + HIROOM_VOXEL_LENGTH, +) +from depth_anything_3.utils.pose_align import align_poses_umeyama + + +def _load_scene_list() -> List[str]: + """Load scene list from file.""" + if os.path.exists(HIROOM_SCENE_LIST_PATH): + with open(HIROOM_SCENE_LIST_PATH, "r") as f: + return f.read().splitlines() + return [] + + +@MV_REGISTRY.register(name="hiroom") +@MONO_REGISTRY.register(name="hiroom") +class HiRoomDataset(Dataset): + """ + HiRoom Dataset wrapper for DepthAnything3 evaluation. + + Supports: + - Camera pose estimation evaluation (AUC metrics) + - 3D reconstruction evaluation (Accuracy, Completeness, F-score) + - TSDF-based point cloud fusion + + Dataset structure: + HiRoom/ + ├── {scene_path}/ + │ ├── image/ # RGB images + │ ├── depth/ # GT depth maps + │ ├── pose/ # Camera poses (.npy) + │ ├── cam_K.npy # Camera intrinsics + │ └── aliasing_mask/ # Aliasing masks + + fused_pcd/ + └── {scene_name}.ply # Ground truth fused point cloud + """ + + data_root = HIROOM_EVAL_DATA_ROOT + gt_root_path = HIROOM_GT_ROOT_PATH + SCENES = _load_scene_list() + + # Evaluation hyperparameters from constants + max_depth = HIROOM_MAX_DEPTH + sampling_number = HIROOM_SAMPLING_NUMBER + voxel_length = HIROOM_VOXEL_LENGTH + sdf_trunc = HIROOM_SDF_TRUNC + eval_threshold = HIROOM_EVAL_THRESHOLD + down_sample = HIROOM_DOWN_SAMPLE + + def __init__(self): + super().__init__() + self._scene_cache = {} + + # ------------------------------ + # Public API + # ------------------------------ + + def get_data(self, scene: str) -> Dict: + """ + Collect per-view image paths, intrinsics/extrinsics for a scene. + + Args: + scene: Scene path (e.g., "xxx/yyy/zzz") + + Returns: + Dict with: + - image_files: List[str] - paths to images + - extrinsics: np.ndarray [N, 4, 4] - world-to-camera transforms + - intrinsics: np.ndarray [N, 3, 3] - camera intrinsics + - aux: Dict with gt_pcd_path, gt_depth_files, aliasing_mask_files + """ + if scene in self._scene_cache: + return self._scene_cache[scene] + + scene_dir = os.path.join(self.data_root, scene) + image_dir = os.path.join(scene_dir, "image") + + # Get scene name for GT point cloud + scene_name = "-".join(scene.split("/")[-3:]) + gt_pcd_path = os.path.join(self.gt_root_path, f"{scene_name}.ply") + + # Load shared camera intrinsics + intrin_path = os.path.join(scene_dir, "cam_K.npy") + ixt_shared = np.load(intrin_path).astype(np.float32) + + # Get all image names sorted + image_names = sorted(os.listdir(image_dir)) + + out = Dict({ + "image_files": [], + "extrinsics": [], + "intrinsics": [], + "aux": Dict({ + "gt_pcd_path": gt_pcd_path, + "gt_depth_files": [], + "aliasing_mask_files": [], + }), + }) + + for img_name in image_names: + img_path = os.path.join(image_dir, img_name) + frame_name = img_name.split(".")[0] + + # Depth and pose paths + depth_path = os.path.join(scene_dir, "depth", f"{frame_name}.png") + pose_path = os.path.join(scene_dir, "pose", f"{frame_name}.npy") + aliasing_mask_path = os.path.join(scene_dir, "aliasing_mask", f"{frame_name}.png") + + if not os.path.exists(pose_path): + continue + + # Load extrinsics (world-to-camera) + ext = np.load(pose_path).astype(np.float32) + + out.image_files.append(img_path) + out.extrinsics.append(ext) + out.intrinsics.append(ixt_shared.copy()) + out.aux.gt_depth_files.append(depth_path) + out.aux.aliasing_mask_files.append(aliasing_mask_path) + + out.extrinsics = np.asarray(out.extrinsics, dtype=np.float32) + out.intrinsics = np.asarray(out.intrinsics, dtype=np.float32) + + print(f"[HiRoom] {scene}: {len(out.image_files)} images") + + self._scene_cache[scene] = out + return out + + def eval3d(self, scene: str, fuse_path: str) -> TDict[str, float]: + """ + Evaluate fused point cloud against HiRoom ground truth point cloud. + + Args: + scene: Scene identifier + fuse_path: Path to fused point cloud (.ply) + + Returns: + Dict with metrics: acc, comp, overall, precision, recall, fscore + """ + gt_data = self.get_data(scene) + gt_pcd_path = gt_data.aux.gt_pcd_path + + # Load ground truth point cloud + gt_pcd = o3d.io.read_point_cloud(gt_pcd_path) + + # Load predicted point cloud + pred_pcd = o3d.io.read_point_cloud(fuse_path) + + # Evaluate using shared utility function + metrics = evaluate_3d_reconstruction( + pred_pcd, + gt_pcd, + threshold=self.eval_threshold, + down_sample=self.down_sample, + ) + + return metrics + + def _load_gt_meta(self, result_path: str) -> Dict: + """Load saved GT meta for fusion.""" + export_dir = os.path.dirname(result_path) + gt_meta_path = os.path.join(os.path.dirname(export_dir), "gt_meta.npz") + + if os.path.exists(gt_meta_path): + data = np.load(gt_meta_path, allow_pickle=True) + image_files = list(data["image_files"]) + return Dict({ + "extrinsics": data["extrinsics"], + "intrinsics": data["intrinsics"], + "image_files": image_files, + }) + return None + + def fuse3d(self, scene: str, result_path: str, fuse_path: str, mode: str) -> None: + """ + Fuse per-view depths into a point cloud using TSDF fusion. + + Args: + scene: Scene identifier + result_path: Path to npz file with predicted depths/poses + fuse_path: Output path for fused point cloud (.ply) + mode: "recon_unposed" or "recon_posed" + """ + # Get full GT data + full_gt_data = self.get_data(scene) + + # Try to load saved GT meta (handles frame sampling) + gt_meta = self._load_gt_meta(result_path) + if gt_meta is not None: + gt_data = gt_meta + image_indices = [ + full_gt_data.image_files.index(f) + for f in gt_data.image_files + if f in full_gt_data.image_files + ] + else: + gt_data = full_gt_data + image_indices = list(range(len(full_gt_data.image_files))) + + _wait_for_file_ready(result_path) + pred_data = Dict({k: v for k, v in np.load(result_path).items()}) + + # Load images + images = [] + orig_sizes = [] + for img_idx in image_indices: + img_path = full_gt_data.image_files[img_idx] + img = cv2.imread(img_path) + img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) + images.append(img) + orig_sizes.append((img.shape[0], img.shape[1])) + + images = np.stack(images, axis=0) + + # Prepare depths, intrinsics, extrinsics + if mode == "recon_unposed": + depths, intrinsics, extrinsics = self._prep_unposed( + pred_data, gt_data, full_gt_data, image_indices, orig_sizes, scene=scene + ) + elif mode == "recon_posed": + depths, intrinsics, extrinsics = self._prep_posed( + pred_data, gt_data, full_gt_data, image_indices, orig_sizes, scene=scene + ) + else: + raise ValueError(f"Invalid mode: {mode}") + + # Create TSDF volume and fuse + volume = create_tsdf_volume( + voxel_length=self.voxel_length, + sdf_trunc=self.sdf_trunc, + ) + mesh = fuse_depth_to_tsdf( + volume, depths, images, intrinsics, extrinsics, max_depth=self.max_depth + ) + + # Sample points from mesh + pcd = sample_points_from_mesh(mesh, self.sampling_number) + + # Save point cloud + os.makedirs(os.path.dirname(fuse_path), exist_ok=True) + o3d.io.write_point_cloud(fuse_path, pcd) + + # ------------------------------ + # Private helpers + # ------------------------------ + + def _prep_unposed( + self, pred_data: Dict, gt_data: Dict, full_gt_data: Dict, + image_indices: list, orig_sizes: list, scene: str = None + ) -> tuple: + """Prepare depths/intrinsics/extrinsics for recon_unposed mode.""" + # Scale alignment with fixed random_state for reproducibility + _, _, scale, extrinsics = align_poses_umeyama( + gt_data.extrinsics.copy(), + pred_data.extrinsics.copy(), + return_aligned=True, + ransac=True, + random_state=42, + ) + + model_h, model_w = pred_data.depth.shape[1], pred_data.depth.shape[2] + + depths_out = [] + intrinsics_out = [] + for i in range(len(pred_data.depth)): + orig_h, orig_w = orig_sizes[i] + img_idx = image_indices[i] + + # Resize depth to original image size + depth = cv2.resize( + pred_data.depth[i], + (orig_w, orig_h), + interpolation=cv2.INTER_NEAREST, + ) + + # Load GT mask + gt_zero_mask = self._load_gt_mask( + full_gt_data.aux.gt_depth_files[img_idx], + full_gt_data.aux.aliasing_mask_files[img_idx], + ) + + # Mask invalid depths BEFORE scale + depth = self._mask_invalid_depth(depth, gt_zero_mask) + + # Apply scale AFTER mask + depth = depth * scale + + # Adjust intrinsics to original image size + h_ratio = orig_h / model_h + w_ratio = orig_w / model_w + ixt = pred_data.intrinsics[i].copy() + ixt[0, :] *= w_ratio + ixt[1, :] *= h_ratio + + depths_out.append(depth) + intrinsics_out.append(ixt) + + return np.stack(depths_out), np.stack(intrinsics_out), extrinsics + + def _prep_posed( + self, pred_data: Dict, gt_data: Dict, full_gt_data: Dict, + image_indices: list, orig_sizes: list, scene: str = None + ) -> tuple: + """Prepare depths/intrinsics/extrinsics for recon_posed mode.""" + # Scale alignment + _, _, scale, _ = align_poses_umeyama( + gt_data.extrinsics.copy(), + pred_data.extrinsics.copy(), + return_aligned=True, + ransac=True, + random_state=42, + ) + + depths_out = [] + for i in range(len(pred_data.depth)): + orig_h, orig_w = orig_sizes[i] + img_idx = image_indices[i] + + # Resize depth to original image size + depth = cv2.resize( + pred_data.depth[i], + (orig_w, orig_h), + interpolation=cv2.INTER_NEAREST, + ) + + # Load GT mask + gt_zero_mask = self._load_gt_mask( + full_gt_data.aux.gt_depth_files[img_idx], + full_gt_data.aux.aliasing_mask_files[img_idx], + ) + + # Mask invalid depths BEFORE scale + depth = self._mask_invalid_depth(depth, gt_zero_mask) + + # Apply scale AFTER mask + depth = depth * scale + + depths_out.append(depth) + + # Use GT intrinsics and extrinsics + gt_intrinsics = np.stack([full_gt_data.intrinsics[idx] for idx in image_indices]) + gt_extrinsics = np.stack([full_gt_data.extrinsics[idx] for idx in image_indices]) + + return np.stack(depths_out), gt_intrinsics, gt_extrinsics + + def _load_gt_mask(self, gt_depth_path: str, aliasing_mask_path: str) -> np.ndarray: + """ + Load GT depth and aliasing mask to create valid mask. + + For HiRoom: + - GT depth is stored as 16-bit PNG, scaled to 100m range + - Aliasing mask marks regions to exclude + + Returns: + Boolean mask where True = valid region to keep + """ + # Load GT depth + if os.path.exists(gt_depth_path): + gt_depth = cv2.imread(gt_depth_path, -1) / 65535.0 * 100.0 + else: + return None + + # Load aliasing mask + aliasing_mask = None + if os.path.exists(aliasing_mask_path): + aliasing_mask = cv2.imread(aliasing_mask_path, -1) > 0 + + # Valid mask: depth > 0 and not in aliasing region + valid_mask = gt_depth > 0 + if aliasing_mask is not None: + valid_mask = np.logical_and(valid_mask, np.logical_not(aliasing_mask)) + + return valid_mask + + def _mask_invalid_depth( + self, depth: np.ndarray, gt_zero_mask: np.ndarray = None + ) -> np.ndarray: + """Mask invalid depth values by setting them to 0.""" + depth = depth.copy() + + if gt_zero_mask is not None: + pred_invalid = np.isnan(depth) | np.isinf(depth) + combined_mask = np.logical_and(gt_zero_mask, np.logical_not(pred_invalid)) + depth = depth * combined_mask.astype(np.float32) + else: + invalid_mask = np.isnan(depth) | np.isinf(depth) | (depth <= 0) + depth[invalid_mask] = 0.0 + + return depth + diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/bench/datasets/scannetpp.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/bench/datasets/scannetpp.py new file mode 100644 index 0000000000000000000000000000000000000000..f841ad11c701a93792ef8814f8093c8a60110d74 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/bench/datasets/scannetpp.py @@ -0,0 +1,591 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +ScanNet++ Benchmark dataset implementation. + +ScanNet++ is a high-quality indoor RGB-D dataset with iPhone and DSLR images, +ground truth camera poses from COLMAP, and high-resolution 3D meshes. +Reference: https://kaldir.vc.in.tum.de/scannetpp/ + +Evaluation metrics: +- 3D reconstruction: Accuracy, Completeness, F-score +- Camera pose estimation: AUC metrics +""" + +import os +from typing import Dict as TDict + +import cv2 +import imageio +import numpy as np +import open3d as o3d +from addict import Dict + +from depth_anything_3.bench.dataset import Dataset, _wait_for_file_ready +from depth_anything_3.bench.registries import MONO_REGISTRY, MV_REGISTRY +from depth_anything_3.bench.utils import ( + create_tsdf_volume, + fuse_depth_to_tsdf, + nn_correspondance, + sample_points_from_mesh, +) +from depth_anything_3.utils.constants import ( + SCANNETPP_DOWN_SAMPLE, + SCANNETPP_EVAL_DATA_ROOT, + SCANNETPP_EVAL_THRESHOLD, + SCANNETPP_INPUT_H, + SCANNETPP_INPUT_W, + SCANNETPP_MAX_DEPTH, + SCANNETPP_SAMPLING_NUMBER, + SCANNETPP_SCENES, + SCANNETPP_SDF_TRUNC, + SCANNETPP_VOXEL_LENGTH, +) +from depth_anything_3.utils.pose_align import align_poses_umeyama +from depth_anything_3.utils.read_write_model import read_model + + +@MV_REGISTRY.register(name="scannetpp") +@MONO_REGISTRY.register(name="scannetpp") +class ScanNetPP(Dataset): + """ + ScanNet++ Benchmark dataset wrapper for DepthAnything3 evaluation. + + Supports: + - Camera pose estimation evaluation (AUC metrics) + - 3D reconstruction evaluation (Accuracy, Completeness, F-score) + - TSDF-based point cloud fusion + + Dataset structure: + scannetpp/data/ + ├── {scene_id}/ + │ ├── merge_dslr_iphone/ + │ │ ├── colmap/sparse_render_rgb/ # COLMAP reconstruction + │ │ ├── images/ # RGB images + │ │ └── render_depth/ # GT depth maps + │ └── scans/ + │ └── mesh_aligned_0.05.ply # Ground truth mesh + """ + + data_root = SCANNETPP_EVAL_DATA_ROOT + SCENES = SCANNETPP_SCENES + + # Input resolution after undistortion and resize + input_h = SCANNETPP_INPUT_H + input_w = SCANNETPP_INPUT_W + + # Evaluation hyperparameters from constants + max_depth = SCANNETPP_MAX_DEPTH + sampling_number = SCANNETPP_SAMPLING_NUMBER + voxel_length = SCANNETPP_VOXEL_LENGTH + sdf_trunc = SCANNETPP_SDF_TRUNC + eval_threshold = SCANNETPP_EVAL_THRESHOLD + down_sample = SCANNETPP_DOWN_SAMPLE + + def __init__(self): + super().__init__() + self._scene_cache = {} + + # ------------------------------ + # Public API + # ------------------------------ + + def get_data(self, scene: str) -> Dict: + """ + Collect per-view image paths, intrinsics/extrinsics for a scene. + + Only uses iPhone images (not DSLR). + + Args: + scene: Scene identifier (e.g., "09c1414f1b") + + Returns: + Dict with: + - image_files: List[str] - paths to images + - extrinsics: np.ndarray [N, 4, 4] - world-to-camera transforms + - intrinsics: np.ndarray [N, 3, 3] - camera intrinsics + - aux: Dict with gt_mesh_path, dist, roi, cam_hw, etc. + """ + if scene in self._scene_cache: + return self._scene_cache[scene] + + input_path = os.path.join(self.data_root, scene, "merge_dslr_iphone") + colmap_path = os.path.join(input_path, "colmap/sparse_render_rgb") + image_path = os.path.join(input_path, "images") + depth_path_dir = os.path.join(input_path, "render_depth") + + # Read COLMAP model + cams, images, points3d = read_model(colmap_path) + + # Map image names to IDs + name2id = {image.name: k for k, image in images.items()} + names = sorted([image.name for k, image in images.items()]) + # Only use iPhone images + names = [name for name in names if "iphone" in name] + + gt_mesh_path = os.path.join( + input_path.replace("merge_dslr_iphone", "scans"), "mesh_aligned_0.05.ply" + ) + + out = Dict({ + "image_files": [], + "extrinsics": [], + "intrinsics": [], + "aux": Dict({ + "gt_mesh_path": gt_mesh_path, + "dist_list": [], + "roi_list": [], + "cam_hw_list": [], + "ixt_raw_list": [], + "gt_depth_files": [], + }), + }) + + for name in names: + image = images[name2id[name]] + img_path = os.path.join(image_path, name) + + if not os.path.exists(img_path): + continue + + # Build extrinsics (world-to-camera) + ext = np.eye(4, dtype=np.float32) + ext[:3, :3] = image.qvec2rotmat() + ext[:3, 3] = image.tvec + + # Get camera parameters + cam_id = image.camera_id + camera = cams[cam_id] + cam_height, cam_width = camera.height, camera.width + + # Build intrinsics + ixt = np.eye(3, dtype=np.float32) + ixt[0, 0], ixt[1, 1], ixt[0, 2], ixt[1, 2] = camera.params[:4] + ixt[:2, 2] -= 0.5 # COLMAP convention adjustment + ixt_raw = ixt.copy() + + # Handle distortion (OPENCV model) + dist = np.zeros(5, dtype=np.float32) + roi = (0, 0, cam_width, cam_height) + if camera.model == "OPENCV": + dist[:4] = camera.params[4:] + ixt, roi = cv2.getOptimalNewCameraMatrix( + ixt, dist, (cam_width, cam_height), 1, (cam_width, cam_height) + ) + + # Depth file path + frame_name = os.path.basename(name)[:-4] # Remove .jpg + depth_file = os.path.join(depth_path_dir, f"{frame_name}.png") + + out.image_files.append(img_path) + out.extrinsics.append(ext) + out.intrinsics.append(ixt) + out.aux.dist_list.append(dist) + out.aux.roi_list.append(roi) + out.aux.cam_hw_list.append((cam_height, cam_width)) + out.aux.ixt_raw_list.append(ixt_raw) + out.aux.gt_depth_files.append(depth_file) + + out.extrinsics = np.asarray(out.extrinsics, dtype=np.float32) + out.intrinsics = np.asarray(out.intrinsics, dtype=np.float32) + + print(f"[ScanNet++] {scene}: {len(out.image_files)} images") + + self._scene_cache[scene] = out + return out + + def load_image(self, img_path: str, idx: int, aux: Dict) -> np.ndarray: + """ + Load and preprocess image with undistortion and cropping. + + Args: + img_path: Path to image file + idx: Index of the image in the dataset + aux: Auxiliary data from get_data + + Returns: + Preprocessed RGB image + """ + image = imageio.imread(img_path).astype(np.uint8) + ixt_raw = aux.ixt_raw_list[idx] + ixt = aux.intrinsics[idx] if hasattr(aux, 'intrinsics') else None + dist = aux.dist_list[idx] + roi = aux.roi_list[idx] + + # Undistort using raw intrinsics + # Use the stored intrinsics from get_data for newCameraMatrix + stored_ixt = self._scene_cache.get(aux.scene, {}).get('intrinsics', [None])[idx] if hasattr(aux, 'scene') else None + if stored_ixt is None: + # Recompute optimal camera matrix for undistortion + cam_h, cam_w = aux.cam_hw_list[idx] + ixt_for_undistort = ixt_raw.copy() + ixt_for_undistort, _ = cv2.getOptimalNewCameraMatrix( + ixt_raw, dist, (cam_w, cam_h), 1, (cam_w, cam_h) + ) + else: + ixt_for_undistort = stored_ixt + + image = cv2.undistort(image, ixt_raw, dist, newCameraMatrix=ixt_for_undistort) + + # Crop to ROI + x, y, w, h = roi + image = image[y:y+h, x:x+w] + + # Resize to target resolution + image = cv2.resize(image, (self.input_w, self.input_h), interpolation=cv2.INTER_AREA) + + return image + + def eval3d(self, scene: str, fuse_path: str) -> TDict[str, float]: + """ + Evaluate fused point cloud against ScanNet++ ground truth mesh. + + Uses AABB cropping to only evaluate points within GT bounding box. + + Args: + scene: Scene identifier + fuse_path: Path to fused point cloud (.ply) + + Returns: + Dict with metrics: acc, comp, overall, precision, recall, fscore + """ + gt_data = self.get_data(scene) + gt_mesh_path = gt_data.aux.gt_mesh_path + + # Load ground truth mesh and sample points + gt_mesh = o3d.io.read_triangle_mesh(gt_mesh_path) + gt_pcd = sample_points_from_mesh(gt_mesh, self.sampling_number) + + # Load predicted point cloud + pred_pcd = o3d.io.read_point_cloud(fuse_path) + + # Crop prediction to GT bounding box (with 0.1m margin) + aabb = gt_pcd.get_axis_aligned_bounding_box() + points = np.asarray(pred_pcd.points) + inside_mask = ( + (points[:, 0] >= aabb.min_bound[0] - 0.1) & + (points[:, 0] <= aabb.max_bound[0] + 0.1) & + (points[:, 1] >= aabb.min_bound[1] - 0.1) & + (points[:, 1] <= aabb.max_bound[1] + 0.1) & + (points[:, 2] >= aabb.min_bound[2] - 0.1) & + (points[:, 2] <= aabb.max_bound[2] + 0.1) + ) + pred_pcd = pred_pcd.select_by_index(inside_mask.nonzero()[0]) + + # Downsample + if self.down_sample > 0: + pred_pcd = pred_pcd.voxel_down_sample(self.down_sample) + gt_pcd = gt_pcd.voxel_down_sample(self.down_sample) + + verts_pred = np.asarray(pred_pcd.points) + verts_gt = np.asarray(gt_pcd.points) + + if len(verts_pred) == 0 or len(verts_gt) == 0: + return { + "acc": float("inf"), + "comp": float("inf"), + "overall": float("inf"), + "precision": 0.0, + "recall": 0.0, + "fscore": 0.0, + } + + # Compute distances + dist_pred_to_gt = nn_correspondance(verts_gt, verts_pred) + dist_gt_to_pred = nn_correspondance(verts_pred, verts_gt) + + # Compute metrics + accuracy = float(np.mean(dist_pred_to_gt)) + completeness = float(np.mean(dist_gt_to_pred)) + overall = (accuracy + completeness) / 2 + + precision = float(np.mean((dist_pred_to_gt < self.eval_threshold).astype(float))) + recall = float(np.mean((dist_gt_to_pred < self.eval_threshold).astype(float))) + + if precision + recall > 0: + fscore = 2 * precision * recall / (precision + recall) + else: + fscore = 0.0 + + return { + "acc": accuracy, + "comp": completeness, + "overall": overall, + "precision": precision, + "recall": recall, + "fscore": fscore, + } + + def _load_gt_meta(self, result_path: str) -> Dict: + """Load saved GT meta for fusion.""" + export_dir = os.path.dirname(result_path) + gt_meta_path = os.path.join(os.path.dirname(export_dir), "gt_meta.npz") + + if os.path.exists(gt_meta_path): + data = np.load(gt_meta_path, allow_pickle=True) + image_files = list(data["image_files"]) + + # Reconstruct aux data from image files + return Dict({ + "extrinsics": data["extrinsics"], + "intrinsics": data["intrinsics"], + "image_files": image_files, + }) + return None + + def fuse3d(self, scene: str, result_path: str, fuse_path: str, mode: str) -> None: + """ + Fuse per-view depths into a point cloud using TSDF fusion. + + Args: + scene: Scene identifier + result_path: Path to npz file with predicted depths/poses + fuse_path: Output path for fused point cloud (.ply) + mode: "recon_unposed" or "recon_posed" + """ + # Get GT data + full_gt_data = self.get_data(scene) + + # Try to load saved GT meta (handles frame sampling) + gt_meta = self._load_gt_meta(result_path) + if gt_meta is not None: + gt_data = gt_meta + # Need to rebuild aux from full GT data based on image indices + image_indices = [ + full_gt_data.image_files.index(f) + for f in gt_data.image_files + if f in full_gt_data.image_files + ] + else: + gt_data = full_gt_data + image_indices = list(range(len(full_gt_data.image_files))) + + _wait_for_file_ready(result_path) + pred_data = Dict({k: v for k, v in np.load(result_path).items()}) + + # Load and preprocess images + images = [] + for idx, img_idx in enumerate(image_indices): + img_path = full_gt_data.image_files[img_idx] + image = imageio.imread(img_path).astype(np.uint8) + + # Undistort and crop + ixt_raw = full_gt_data.aux.ixt_raw_list[img_idx] + ixt = full_gt_data.intrinsics[img_idx] + dist = full_gt_data.aux.dist_list[img_idx] + roi = full_gt_data.aux.roi_list[img_idx] + + image = cv2.undistort(image, ixt_raw, dist, newCameraMatrix=ixt) + x, y, w, h = roi + image = image[y:y+h, x:x+w] + image = cv2.resize(image, (self.input_w, self.input_h), interpolation=cv2.INTER_AREA) + + images.append(image) + + images = np.stack(images, axis=0) + + # Prepare depths, intrinsics, extrinsics + if mode == "recon_unposed": + depths, intrinsics, extrinsics = self._prep_unposed( + pred_data, gt_data, full_gt_data, image_indices, scene=scene + ) + elif mode == "recon_posed": + depths, intrinsics, extrinsics = self._prep_posed( + pred_data, gt_data, full_gt_data, image_indices, scene=scene + ) + else: + raise ValueError(f"Invalid mode: {mode}") + + # Create TSDF volume and fuse + volume = create_tsdf_volume( + voxel_length=self.voxel_length, + sdf_trunc=self.sdf_trunc, + ) + mesh = fuse_depth_to_tsdf( + volume, depths, images, intrinsics, extrinsics, max_depth=self.max_depth + ) + + # Sample points from mesh + pcd = sample_points_from_mesh(mesh, self.sampling_number) + + # Save point cloud + os.makedirs(os.path.dirname(fuse_path), exist_ok=True) + o3d.io.write_point_cloud(fuse_path, pcd) + + # ------------------------------ + # Private helpers + # ------------------------------ + + def _prep_unposed( + self, pred_data: Dict, gt_data: Dict, full_gt_data: Dict, + image_indices: list, scene: str = None + ) -> tuple: + """Prepare depths/intrinsics/extrinsics for recon_unposed mode.""" + # Scale alignment with fixed random_state for reproducibility + _, _, scale, extrinsics = align_poses_umeyama( + gt_data.extrinsics.copy(), + pred_data.extrinsics.copy(), + return_aligned=True, + ransac=True, + random_state=42, + ) + + model_h, model_w = pred_data.depth.shape[1], pred_data.depth.shape[2] + + depths_out = [] + intrinsics_out = [] + for i in range(len(pred_data.depth)): + img_idx = image_indices[i] + + # Get original image size (after undistort+crop, before resize to input_h/w) + orig_h, orig_w = full_gt_data.aux.cam_hw_list[img_idx] + + # Step 1: nearest resize to original image size + depth = cv2.resize( + pred_data.depth[i], + (orig_w, orig_h), + interpolation=cv2.INTER_NEAREST, + ) + + # Step 2: linear resize to target resolution + depth = cv2.resize( + depth, + (self.input_w, self.input_h), + interpolation=cv2.INTER_LINEAR, + ).astype(np.float32) + + # Load GT depth for masking + gt_zero_mask = self._load_gt_mask(full_gt_data.aux.gt_depth_files[img_idx]) + + # Mask invalid depths BEFORE scale + depth = self._mask_invalid_depth(depth, gt_zero_mask) + + # Apply scale AFTER mask + depth = depth * scale + + # Adjust intrinsics to target resolution + h_ratio = self.input_h / model_h + w_ratio = self.input_w / model_w + ixt = pred_data.intrinsics[i].copy() + ixt[0, :] *= w_ratio + ixt[1, :] *= h_ratio + + depths_out.append(depth) + intrinsics_out.append(ixt) + + return np.stack(depths_out), np.stack(intrinsics_out), extrinsics + + def _prep_posed( + self, pred_data: Dict, gt_data: Dict, full_gt_data: Dict, + image_indices: list, scene: str = None + ) -> tuple: + """Prepare depths/intrinsics/extrinsics for recon_posed mode.""" + # Scale alignment + _, _, scale, _ = align_poses_umeyama( + gt_data.extrinsics.copy(), + pred_data.extrinsics.copy(), + return_aligned=True, + ransac=True, + random_state=42, + ) + + depths_out = [] + intrinsics_out = [] + extrinsics_out = [] + + for i in range(len(pred_data.depth)): + img_idx = image_indices[i] + + # Get original image size (after undistort+crop, before resize to input_h/w) + orig_h, orig_w = full_gt_data.aux.cam_hw_list[img_idx] + + # Step 1: nearest resize to original image size + depth = cv2.resize( + pred_data.depth[i], + (orig_w, orig_h), + interpolation=cv2.INTER_NEAREST, + ) + + # Step 2: linear resize to target resolution + depth = cv2.resize( + depth, + (self.input_w, self.input_h), + interpolation=cv2.INTER_LINEAR, + ).astype(np.float32) + + # Load GT depth for masking + gt_zero_mask = self._load_gt_mask(full_gt_data.aux.gt_depth_files[img_idx]) + + # Mask invalid depths BEFORE scale + depth = self._mask_invalid_depth(depth, gt_zero_mask) + + # Apply scale AFTER mask + depth = depth * scale + + depths_out.append(depth) + + # Get GT intrinsics and scale to target resolution + ixt = full_gt_data.intrinsics[img_idx].copy() + cam_h, cam_w = full_gt_data.aux.cam_hw_list[img_idx] + ixt[:2, 2] += 0.5 # Undo COLMAP convention + ixt[0, :] *= self.input_w / cam_w + ixt[1, :] *= self.input_h / cam_h + intrinsics_out.append(ixt) + + extrinsics_out.append(full_gt_data.extrinsics[img_idx]) + + return np.stack(depths_out), np.stack(intrinsics_out), np.stack(extrinsics_out) + + def _load_gt_mask(self, gt_depth_path: str) -> np.ndarray: + """ + Load GT depth and create valid mask. + + For ScanNet++, GT depth is stored as 16-bit PNG in millimeters. + + Returns: + Boolean mask where True = valid region to keep + """ + if not os.path.exists(gt_depth_path): + return None + + gt_depth = imageio.imread(gt_depth_path) / 1000.0 # mm to meters + + # Resize to target resolution + gt_depth = cv2.resize( + gt_depth, + (self.input_w, self.input_h), + interpolation=cv2.INTER_LINEAR, + ).astype(np.float32) + + # Valid mask: depth > 0 and not inf + valid_mask = np.logical_and(gt_depth > 0, gt_depth != np.inf) + return valid_mask + + def _mask_invalid_depth( + self, depth: np.ndarray, gt_zero_mask: np.ndarray = None + ) -> np.ndarray: + """Mask invalid depth values by setting them to 0.""" + depth = depth.copy() + + if gt_zero_mask is not None: + pred_invalid = np.isnan(depth) | np.isinf(depth) + combined_mask = np.logical_and(gt_zero_mask, np.logical_not(pred_invalid)) + depth = depth * combined_mask.astype(np.float32) + else: + invalid_mask = np.isnan(depth) | np.isinf(depth) | (depth <= 0) + depth[invalid_mask] = 0.0 + + return depth + diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/bench/datasets/sevenscenes.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/bench/datasets/sevenscenes.py new file mode 100644 index 0000000000000000000000000000000000000000..cce82b385d4460f948d240f3c0991b7570d2177a --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/bench/datasets/sevenscenes.py @@ -0,0 +1,449 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +7Scenes Benchmark dataset implementation. + +7Scenes is an indoor RGB-D dataset with ground truth camera poses and 3D meshes. +Reference: https://www.microsoft.com/en-us/research/project/rgb-d-dataset-7-scenes/ + +Evaluation metrics: +- 3D reconstruction: Accuracy, Completeness, F-score +- Camera pose estimation: AUC metrics +""" + +import os +from typing import Dict as TDict + +import cv2 +import numpy as np +import open3d as o3d +from addict import Dict + +from depth_anything_3.bench.dataset import Dataset, _wait_for_file_ready +from depth_anything_3.bench.registries import MONO_REGISTRY, MV_REGISTRY +from depth_anything_3.bench.utils import ( + create_tsdf_volume, + evaluate_3d_reconstruction, + fuse_depth_to_tsdf, + sample_points_from_mesh, +) +from depth_anything_3.utils.constants import ( + SEVENSCENES_CX, + SEVENSCENES_CY, + SEVENSCENES_DOWN_SAMPLE, + SEVENSCENES_EVAL_DATA_ROOT, + SEVENSCENES_EVAL_THRESHOLD, + SEVENSCENES_FX, + SEVENSCENES_FY, + SEVENSCENES_MAX_DEPTH, + SEVENSCENES_SAMPLING_NUMBER, + SEVENSCENES_SCENES, + SEVENSCENES_SDF_TRUNC, + SEVENSCENES_VOXEL_LENGTH, +) +from depth_anything_3.utils.pose_align import align_poses_umeyama + + +@MV_REGISTRY.register(name="7scenes") +@MONO_REGISTRY.register(name="7scenes") +class SevenScenes(Dataset): + """ + 7Scenes Benchmark dataset wrapper for DepthAnything3 evaluation. + + Supports: + - Camera pose estimation evaluation (AUC metrics) + - 3D reconstruction evaluation (Accuracy, Completeness, F-score) + - TSDF-based point cloud fusion + + Dataset structure: + 7scenes/ + ├── 7Scenes/ + │ ├── {scene}/ + │ │ └── seq-01/ (or seq-02 for stairs) + │ │ ├── frame-XXXXXX.color.png + │ │ ├── frame-XXXXXX.depth.png + │ │ └── frame-XXXXXX.pose.txt + │ └── meshes/ + │ └── {scene}.ply # Ground truth mesh + """ + + data_root = SEVENSCENES_EVAL_DATA_ROOT + SCENES = SEVENSCENES_SCENES + + # Evaluation hyperparameters from constants + max_depth = SEVENSCENES_MAX_DEPTH + sampling_number = SEVENSCENES_SAMPLING_NUMBER + voxel_length = SEVENSCENES_VOXEL_LENGTH + sdf_trunc = SEVENSCENES_SDF_TRUNC + eval_threshold = SEVENSCENES_EVAL_THRESHOLD + down_sample = SEVENSCENES_DOWN_SAMPLE + + # Fixed camera intrinsics for all 7Scenes images + fx = SEVENSCENES_FX + fy = SEVENSCENES_FY + cx = SEVENSCENES_CX + cy = SEVENSCENES_CY + + def __init__(self): + super().__init__() + self._scene_cache = {} + + # ------------------------------ + # Public API + # ------------------------------ + + def get_data(self, scene: str) -> Dict: + """ + Collect per-view image paths, intrinsics/extrinsics for a scene. + + Args: + scene: Scene identifier (e.g., "chess") + + Returns: + Dict with: + - image_files: List[str] - paths to images + - extrinsics: np.ndarray [N, 4, 4] - world-to-camera transforms + - intrinsics: np.ndarray [N, 3, 3] - camera intrinsics + - aux: Dict with gt_mesh_path, gt_depth_files + """ + if scene in self._scene_cache: + return self._scene_cache[scene] + + # Different sequence for stairs scene + if scene == "stairs": + data_folder = os.path.join(self.data_root, "7Scenes", scene, "seq-02") + n_imgs = 500 + else: + data_folder = os.path.join(self.data_root, "7Scenes", scene, "seq-01") + n_imgs = 1000 + + gt_mesh_path = os.path.join(self.data_root, "7Scenes", "meshes", f"{scene}.ply") + + # Fixed intrinsics for all images + ixt = np.array([ + [self.fx, 0, self.cx], + [0, self.fy, self.cy], + [0, 0, 1], + ], dtype=np.float32) + + out = Dict({ + "image_files": [], + "extrinsics": [], + "intrinsics": [], + "aux": Dict({ + "gt_mesh_path": gt_mesh_path, + "gt_depth_files": [], + }), + }) + + for i in range(0, n_imgs, 1): + img_path = os.path.join(data_folder, f"frame-{i:06d}.color.png") + pose_path = os.path.join(data_folder, f"frame-{i:06d}.pose.txt") + depth_path = os.path.join(data_folder, f"frame-{i:06d}.depth.png") + + if not os.path.exists(img_path) or not os.path.exists(pose_path): + continue + + # Load camera-to-world pose and convert to world-to-camera (extrinsic) + c2w = np.loadtxt(pose_path) + ext = np.linalg.inv(c2w).astype(np.float32) + + out.image_files.append(img_path) + out.extrinsics.append(ext) + out.intrinsics.append(ixt.copy()) + out.aux.gt_depth_files.append(depth_path) + + out.extrinsics = np.asarray(out.extrinsics, dtype=np.float32) + out.intrinsics = np.asarray(out.intrinsics, dtype=np.float32) + + print(f"[7Scenes] {scene}: {len(out.image_files)} images") + + self._scene_cache[scene] = out + return out + + def eval3d(self, scene: str, fuse_path: str) -> TDict[str, float]: + """ + Evaluate fused point cloud against 7Scenes ground truth mesh. + + Args: + scene: Scene identifier + fuse_path: Path to fused point cloud (.ply) + + Returns: + Dict with metrics: acc, comp, overall, precision, recall, fscore + """ + gt_data = self.get_data(scene) + gt_mesh_path = gt_data.aux.gt_mesh_path + + # Load and sample ground truth mesh + gt_mesh = o3d.io.read_triangle_mesh(gt_mesh_path) + gt_pcd = sample_points_from_mesh(gt_mesh, self.sampling_number) + + # Load predicted point cloud + pred_pcd = o3d.io.read_point_cloud(fuse_path) + + # Evaluate using shared utility function + metrics = evaluate_3d_reconstruction( + pred_pcd, + gt_pcd, + threshold=self.eval_threshold, + down_sample=self.down_sample, + ) + + return metrics + + def _load_gt_meta(self, result_path: str) -> Dict: + """ + Load saved GT meta (extrinsics, intrinsics, image_files) for fusion. + + This is needed when frames are sampled, so fuse3d uses the correct + (sampled) GT instead of full dataset GT. + + Args: + result_path: Path to npz file (used to derive gt_meta.npz path) + + Returns: + Dict with GT data, or None if gt_meta.npz doesn't exist + """ + export_dir = os.path.dirname(result_path) # exports/mini_npz/ + gt_meta_path = os.path.join(os.path.dirname(export_dir), "gt_meta.npz") + + if os.path.exists(gt_meta_path): + data = np.load(gt_meta_path, allow_pickle=True) + # Build aux with gt_depth_files derived from image_files + image_files = list(data["image_files"]) + gt_depth_files = [ + img_path.replace("color", "depth").replace(".color.", ".depth.") + for img_path in image_files + ] + return Dict({ + "extrinsics": data["extrinsics"], + "intrinsics": data["intrinsics"], + "image_files": image_files, + "aux": Dict({"gt_depth_files": gt_depth_files}), + }) + return None + + def fuse3d(self, scene: str, result_path: str, fuse_path: str, mode: str) -> None: + """ + Fuse per-view depths into a point cloud using TSDF fusion. + + Args: + scene: Scene identifier + result_path: Path to npz file with predicted depths/poses + fuse_path: Output path for fused point cloud (.ply) + mode: "recon_unposed" or "recon_posed" + """ + # Try to load saved GT meta (handles frame sampling) + gt_meta = self._load_gt_meta(result_path) + if gt_meta is not None: + gt_data = gt_meta + else: + gt_data = self.get_data(scene) + _wait_for_file_ready(result_path) + pred_data = Dict({k: v for k, v in np.load(result_path).items()}) + + # Load original images (keep original size) + images = [] + orig_sizes = [] + for img_path in gt_data.image_files: + img = cv2.imread(img_path) + img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) + images.append(img) + orig_sizes.append((img.shape[0], img.shape[1])) + + # Prepare depths, intrinsics, extrinsics + if mode == "recon_unposed": + depths, intrinsics, extrinsics = self._prep_unposed( + pred_data, gt_data, orig_sizes, scene=scene + ) + elif mode == "recon_posed": + depths, intrinsics, extrinsics = self._prep_posed( + pred_data, gt_data, orig_sizes, scene=scene + ) + else: + raise ValueError(f"Invalid mode: {mode}") + + images = np.stack(images, axis=0) + + # Create TSDF volume and fuse + volume = create_tsdf_volume( + voxel_length=self.voxel_length, + sdf_trunc=self.sdf_trunc, + ) + mesh = fuse_depth_to_tsdf( + volume, depths, images, intrinsics, extrinsics, max_depth=self.max_depth + ) + + # Sample points from mesh + pcd = sample_points_from_mesh(mesh, self.sampling_number) + + # Save point cloud + os.makedirs(os.path.dirname(fuse_path), exist_ok=True) + o3d.io.write_point_cloud(fuse_path, pcd) + + # ------------------------------ + # Private helpers + # ------------------------------ + + def _prep_unposed( + self, pred_data: Dict, gt_data: Dict, orig_sizes: list, scene: str + ) -> tuple: + """ + Prepare depths/intrinsics/extrinsics for recon_unposed mode. + + Similar to ETH3D but uses GT depth for masking instead of separate mask files. + """ + # Scale alignment with fixed random_state for reproducibility + _, _, scale, extrinsics = align_poses_umeyama( + gt_data.extrinsics.copy(), + pred_data.extrinsics.copy(), + return_aligned=True, + ransac=True, + random_state=42, + ) + + model_h, model_w = pred_data.depth.shape[1], pred_data.depth.shape[2] + + depths_out = [] + intrinsics_out = [] + for i in range(len(pred_data.depth)): + orig_h, orig_w = orig_sizes[i] + + # Resize depth to original image size (nearest interpolation) + depth = cv2.resize( + pred_data.depth[i], + (orig_w, orig_h), + interpolation=cv2.INTER_NEAREST, + ) + + # Load GT depth for masking + gt_zero_mask = self._load_gt_mask(gt_data.aux.gt_depth_files[i]) + + # Mask invalid depths BEFORE scale + depth = self._mask_invalid_depth(depth, gt_zero_mask) + + # Apply scale AFTER mask + depth = depth * scale + + # Adjust intrinsics to original image size + h_ratio = orig_h / model_h + w_ratio = orig_w / model_w + ixt = pred_data.intrinsics[i].copy() + ixt[0, :] *= w_ratio + ixt[1, :] *= h_ratio + + depths_out.append(depth) + intrinsics_out.append(ixt) + + return np.stack(depths_out), np.stack(intrinsics_out), extrinsics + + def _prep_posed( + self, pred_data: Dict, gt_data: Dict, orig_sizes: list, scene: str + ) -> tuple: + """ + Prepare depths/intrinsics/extrinsics for recon_posed mode. + Uses GT intrinsics/extrinsics but aligns depth scale via Umeyama. + """ + # Scale alignment with fixed random_state + _, _, scale, _ = align_poses_umeyama( + gt_data.extrinsics.copy(), + pred_data.extrinsics.copy(), + return_aligned=True, + ransac=True, + random_state=42, + ) + + model_h, model_w = pred_data.depth.shape[1], pred_data.depth.shape[2] + + depths_out = [] + for i in range(len(pred_data.depth)): + orig_h, orig_w = orig_sizes[i] + + # Resize depth to original image size + depth = cv2.resize( + pred_data.depth[i], + (orig_w, orig_h), + interpolation=cv2.INTER_NEAREST, + ) + + # Load GT depth for masking + gt_zero_mask = self._load_gt_mask(gt_data.aux.gt_depth_files[i]) + + # Mask invalid depths BEFORE scale + depth = self._mask_invalid_depth(depth, gt_zero_mask) + + # Apply scale AFTER mask + depth = depth * scale + + depths_out.append(depth) + + # Use GT intrinsics and extrinsics + return np.stack(depths_out), gt_data.intrinsics.copy(), gt_data.extrinsics.copy() + + def _load_gt_mask(self, gt_depth_path: str) -> np.ndarray: + """ + Load GT depth and create valid mask. + + For 7Scenes, GT depth is stored as 16-bit PNG in millimeters. + Value 65535 indicates invalid depth. + + Returns: + Boolean mask where True = valid region to keep + """ + if not os.path.exists(gt_depth_path): + return None + + gt_depth = cv2.imread(gt_depth_path, -1) + if gt_depth is None: + return None + + # 65535 is invalid depth marker in 7Scenes + gt_depth[gt_depth == 65535] = 0 + # Convert to meters + gt_depth = gt_depth / 1000.0 + + # Valid mask: depth > 0 + valid_mask = gt_depth > 0 + return valid_mask + + def _mask_invalid_depth( + self, depth: np.ndarray, gt_zero_mask: np.ndarray = None + ) -> np.ndarray: + """ + Mask invalid depth values by setting them to 0. + + Args: + depth: Depth map to mask + gt_zero_mask: Optional GT mask (True = valid region) + + Returns: + Masked depth map with invalid regions set to 0 + """ + depth = depth.copy() + + if gt_zero_mask is not None: + # Also mask out invalid pred depth + pred_invalid = np.isnan(depth) | np.isinf(depth) + combined_mask = np.logical_and(gt_zero_mask, np.logical_not(pred_invalid)) + depth = depth * combined_mask.astype(np.float32) + else: + # Fallback: only mask pred invalid values + invalid_mask = np.isnan(depth) | np.isinf(depth) | (depth <= 0) + depth[invalid_mask] = 0.0 + + return depth + + diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/bench/evaluator.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/bench/evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..18b6ae43e85bf4b25de5b65d74ed6a83729e7d8e --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/bench/evaluator.py @@ -0,0 +1,746 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Main Evaluator class for DepthAnything3 benchmark evaluation. + +Supports multiple datasets and evaluation modes: +- pose: Camera pose estimation (AUC metrics) +- recon_unposed: 3D reconstruction with predicted poses +- recon_posed: 3D reconstruction with GT poses +- view_syn: Novel view synthesis (TODO) +""" + +import json +import os +import random +from typing import Dict as TDict, Iterable, List + +import numpy as np +import torch +from addict import Dict +from tqdm import tqdm + +from depth_anything_3.bench.print_metrics import MetricsPrinter +from depth_anything_3.utils.parallel_utils import parallel_execution +from depth_anything_3.bench.registries import MV_REGISTRY +from depth_anything_3.utils.constants import EVAL_REF_VIEW_STRATEGY + + +class Evaluator: + """ + Main evaluation orchestrator for DepthAnything3 benchmarks. + + Usage: + evaluator = Evaluator( + work_dir="./eval_workspace", + datas=["dtu"], + modes=["pose", "recon_unposed", "recon_posed"], + ) + api = DepthAnything3.from_pretrained("...") + evaluator.infer(api) + metrics = evaluator.eval() + evaluator.print_metrics() + """ + + VALID_MODES = {"pose", "recon_unposed", "recon_posed", "view_syn"} + + def __init__( + self, + work_dir: str = "./eval_workspace", + datas: List[str] = ("dtu",), + modes: List[str] = ("recon_unposed",), + ref_view_strategy: str = EVAL_REF_VIEW_STRATEGY, + scenes: List[str] = None, + debug: bool = False, + num_fusion_workers: int = 4, + max_frames: int = 100, + gpu_id: int = 0, + total_gpus: int = 1, + ): + """ + Initialize the evaluator. + + Args: + work_dir: Base directory for model outputs and metric files + datas: List of dataset names (must be registered in MV_REGISTRY) + modes: List of evaluation modes to run + ref_view_strategy: Reference view selection strategy for inference + ("first", "saddle_balanced", etc.) + scenes: Specific scenes to evaluate (None = all scenes) + debug: Enable verbose debug output + num_fusion_workers: Number of parallel workers for TSDF fusion (default: 4) + max_frames: Maximum number of frames per scene (default: 100). + If a scene has more frames, randomly sample to this limit. + Set to -1 to disable sampling. + gpu_id: GPU index for multi-GPU (0-indexed) + total_gpus: Total number of GPUs for task distribution + """ + self.work_dir = work_dir + self.datas = list(datas) + self.modes = set(modes) + self.ref_view_strategy = ref_view_strategy + self.scenes_filter = scenes + self.debug = debug + self.num_fusion_workers = num_fusion_workers + self.max_frames = max_frames + self.gpu_id = gpu_id + self.total_gpus = total_gpus + + # Validate modes + unknown = self.modes - self.VALID_MODES + if unknown: + raise ValueError(f"Unknown modes: {unknown}. Valid: {sorted(self.VALID_MODES)}") + + os.makedirs(self.work_dir, exist_ok=True) + + # Initialize datasets + self.datasets = Dict() + for data in self.datas: + if not MV_REGISTRY.has(data): + available = list(MV_REGISTRY.all().keys()) + raise ValueError(f"Dataset '{data}' not found. Available: {available}") + self.datasets[data] = MV_REGISTRY.get(data)() + + # Initialize metrics printer + self._printer = MetricsPrinter() + + # -------------------- Public APIs -------------------- # + + def all(self, api) -> TDict[str, dict]: + """ + Run complete evaluation pipeline: inference + evaluation. + + Args: + api: DepthAnything3 API instance + + Returns: + Combined metrics dictionary + """ + self.infer(api) + return self.eval() + + def _get_scenes(self, dataset) -> List[str]: + """Get list of scenes to evaluate, optionally filtered.""" + all_scenes = dataset.SCENES + if self.scenes_filter: + scenes = [s for s in all_scenes if s in self.scenes_filter] + if self.debug: + print(f"[DEBUG] Filtered scenes: {scenes} (from {len(all_scenes)} total)") + return scenes + return all_scenes + + def infer(self, api, model_path: str = None) -> None: + """ + Run inference according to requested modes. + + - Unposed export if 'pose' or 'recon_unposed' is in modes + - Posed export if 'recon_posed' or 'view_syn' is in modes + + Multi-GPU: Use --gpu_id and --total_gpus to distribute tasks. + Example: Launch 4 processes with gpu_id=0,1,2,3 and total_gpus=4 + + Args: + api: DepthAnything3 API instance + model_path: Model path (unused, kept for API compatibility) + """ + need_unposed = {"pose", "recon_unposed"} & self.modes + need_posed = {"recon_posed", "view_syn"} & self.modes + export_format = "mini_npz-glb" if self.debug else "mini_npz" + + # Collect all tasks + all_tasks = [] + for data in self.datas: + dataset = self.datasets[data] + for scene in self._get_scenes(dataset): + all_tasks.append((data, scene)) + + # Distribute tasks across GPUs + if self.total_gpus > 1: + tasks = [t for i, t in enumerate(all_tasks) if i % self.total_gpus == self.gpu_id] + print(f"[INFO] GPU {self.gpu_id}/{self.total_gpus}: {len(tasks)}/{len(all_tasks)} tasks") + else: + tasks = all_tasks + print(f"[INFO] Total inference tasks: {len(tasks)}") + + for data, scene in tqdm(tasks, desc=f"Inference (GPU {self.gpu_id})"): + dataset = self.datasets[data] + scene_data = dataset.get_data(scene) + scene_data = self._sample_frames(scene_data, scene) + + if need_unposed: + export_dir = self._export_dir(data, scene, posed=False) + api.inference( + scene_data.image_files, + export_dir=export_dir, + export_format=export_format, + ref_view_strategy=self.ref_view_strategy, + ) + self._save_gt_meta(export_dir, scene_data) + + if need_posed: + export_dir = self._export_dir(data, scene, posed=True) + api.inference( + scene_data.image_files, + scene_data.extrinsics, + scene_data.intrinsics, + export_dir=export_dir, + export_format=export_format, + ref_view_strategy=self.ref_view_strategy, + ) + self._save_gt_meta(export_dir, scene_data) + + def eval(self) -> TDict[str, dict]: + """ + Evaluate for all configured modes and write JSON files. + + Evaluation order by mode (all datasets per mode): + 1. pose - all datasets + 2. recon_unposed - all datasets + 3. recon_posed - all datasets + + Returns: + Summary mapping: {"_": metrics_dict} + """ + summary: TDict[str, dict] = {} + + # Evaluate by mode (all datasets per mode) + if "pose" in self.modes: + print(f"\n{'='*60}") + print(f"📊 Evaluating POSE for all datasets...") + print(f"{'='*60}") + for data, result in self._eval_pose(): + summary[f"{data}_pose"] = result + + if "recon_unposed" in self.modes: + print(f"\n{'='*60}") + print(f"📊 Evaluating RECON_UNPOSED for all datasets...") + print(f"{'='*60}") + for data, result in self._eval_reconstruction("recon_unposed"): + summary[f"{data}_recon_unposed"] = result + + if "recon_posed" in self.modes: + print(f"\n{'='*60}") + print(f"📊 Evaluating RECON_POSED for all datasets...") + print(f"{'='*60}") + for data, result in self._eval_reconstruction("recon_posed"): + summary[f"{data}_recon_posed"] = result + + if "view_syn" in self.modes: + # TODO: Add view synthesis metrics here when available + pass + + return summary + + def print_metrics(self, metrics: TDict[str, dict] = None) -> None: + """ + Print evaluation metrics in a beautiful tabular format. + + Args: + metrics: Metrics dictionary. If None, loads from saved JSON files. + """ + if metrics is None: + metrics = self._load_metrics() + + self._printer.print_results(metrics) + + # -------------------- Evaluation Methods -------------------- # + + def _eval_pose(self) -> Iterable[tuple]: + """Compute pose-estimation metrics for each dataset and scene.""" + os.makedirs(self._metric_dir, exist_ok=True) + + for data in tqdm(self.datas, desc="Datasets (pose eval)"): + dataset = self.datasets[data] + dataset_results = Dict() + scenes = self._get_scenes(dataset) + + for scene in tqdm(scenes, desc=f"{data} scenes", leave=False): + export_dir = self._export_dir(data, scene, posed=False) + result_path = os.path.join(export_dir, "exports", "mini_npz", "results.npz") + + # Check if result file exists and is valid + if not os.path.exists(result_path): + print(f"\n[ERROR] Result file not found: {result_path}") + print(f"[ERROR] CWD: {os.getcwd()}") + print(f"[ERROR] Please run inference first (remove --eval_only)") + continue + + try: + # Use saved GT meta (handles frame sampling correctly) + gt_meta = self._load_gt_meta(export_dir) + if gt_meta is not None: + result = self._compute_pose_with_gt(result_path, gt_meta) + else: + # Fallback to dataset GT (no sampling was done) + result = dataset.eval_pose(scene, result_path) + dataset_results[scene] = self._to_float_dict(result) + except Exception as e: + print(f"\n[ERROR] Failed to evaluate pose for {data}/{scene}: {e}") + print(f"[ERROR] File path: {os.path.abspath(result_path)}") + if self.debug: + import traceback + traceback.print_exc() + continue + + if not dataset_results: + print(f"[WARNING] No valid results for {data}") + continue + + dataset_results["mean"] = self._mean_of_dicts(dataset_results.values()) + out_path = os.path.join(self._metric_dir, f"{data}_pose.json") + self._dump_json(out_path, dataset_results) + yield data, dataset_results + + def _eval_reconstruction(self, mode: str) -> Iterable[tuple]: + """ + Compute reconstruction metrics for each dataset and scene. + + Args: + mode: "recon_unposed" or "recon_posed" + """ + assert mode in {"recon_unposed", "recon_posed"} + os.makedirs(self._metric_dir, exist_ok=True) + + posed_flag = mode == "recon_posed" + + # Filter out datasets that don't support reconstruction (e.g., dtu64) + recon_datas = [d for d in self.datas if d != "dtu64"] + + for data in tqdm(recon_datas, desc=f"Datasets ({mode} eval)"): + dataset = self.datasets[data] + dataset_results = Dict() + scenes = self._get_scenes(dataset) + + # Prepare paths for all scenes + scene_list = [] + result_paths = [] + fuse_paths = [] + for scene in scenes: + export_dir = self._export_dir(data, scene, posed=posed_flag) + result_path = os.path.join(export_dir, "exports", "mini_npz", "results.npz") + fuse_path = os.path.join(export_dir, "exports", "fuse", "pcd.ply") + scene_list.append(scene) + result_paths.append(result_path) + fuse_paths.append(fuse_path) + + # Parallel fusion (default 4 workers) + # DTU uses CUDA operations in fusion, which doesn't work well with ThreadPool + use_sequential = (data == "dtu") + parallel_execution( + scene_list, + result_paths, + fuse_paths, + action=lambda s, rp, fp: dataset.fuse3d(s, rp, fp, mode), + num_processes=self.num_fusion_workers, + print_progress=True, + desc=f"{data} fusion", + sequential=use_sequential, + ) + + # Sequential evaluation (fast, no need to parallelize) + for scene, fuse_path in zip(scene_list, fuse_paths): + # DTU supports CPU-based evaluation + if data == "dtu" and hasattr(dataset, "eval3d"): + result = dataset.eval3d(scene, fuse_path) + else: + result = dataset.eval3d(scene, fuse_path) + dataset_results[scene] = self._to_float_dict(result) + print(f" {mode} | {data} | {scene}: {result}") + + dataset_results["mean"] = self._mean_of_dicts(dataset_results.values()) + out_path = os.path.join(self._metric_dir, f"{data}_{mode}.json") + self._dump_json(out_path, dataset_results) + yield data, dataset_results + + # -------------------- Helpers -------------------- # + + def _save_gt_meta(self, export_dir: str, scene_data: Dict) -> None: + """ + Save GT extrinsics/intrinsics/image_files for evaluation. + + This is needed when frames are sampled, so eval_pose and fuse3d can use + the correct (sampled) GT instead of full dataset GT. + + Args: + export_dir: Export directory for the scene + scene_data: Sampled scene data + """ + meta_path = os.path.join(export_dir, "exports", "gt_meta.npz") + os.makedirs(os.path.dirname(meta_path), exist_ok=True) + np.savez_compressed( + meta_path, + extrinsics=scene_data.extrinsics, + intrinsics=scene_data.intrinsics, + image_files=np.array(scene_data.image_files, dtype=object), + ) + + def _load_gt_meta(self, export_dir: str) -> Dict: + """ + Load saved GT extrinsics/intrinsics for evaluation. + + Returns: + Dict with extrinsics and intrinsics, or None if not found + """ + meta_path = os.path.join(export_dir, "exports", "gt_meta.npz") + if os.path.exists(meta_path): + data = np.load(meta_path) + return Dict({ + "extrinsics": data["extrinsics"], + "intrinsics": data["intrinsics"], + }) + return None + + def _compute_pose_with_gt(self, result_path: str, gt_meta: Dict) -> TDict[str, float]: + """ + Compute pose metrics using saved GT meta (handles frame sampling). + + Args: + result_path: Path to npz with predicted extrinsics + gt_meta: Dict with GT extrinsics from saved meta + + Returns: + Dict with pose metrics + """ + from depth_anything_3.bench.dataset import _wait_for_file_ready + from depth_anything_3.bench.utils import compute_pose + from depth_anything_3.utils.geometry import as_homogeneous + + _wait_for_file_ready(result_path) + pred = np.load(result_path) + return compute_pose( + torch.from_numpy(as_homogeneous(pred["extrinsics"])), + torch.from_numpy(as_homogeneous(gt_meta["extrinsics"])), + ) + + def _sample_frames(self, scene_data: Dict, scene: str) -> Dict: + """ + Sample frames if scene has more than max_frames. + + Uses fixed random seed (42) for reproducibility. + + Args: + scene_data: Scene data dict with image_files, extrinsics, intrinsics, aux + scene: Scene name (for logging) + + Returns: + Sampled scene_data if num_frames > max_frames, otherwise original + """ + if self.max_frames <= 0: + return scene_data + + num_frames = len(scene_data.image_files) + if num_frames <= self.max_frames: + return scene_data + + # Sample with fixed seed for reproducibility + random.seed(42) + indices = list(range(num_frames)) + random.shuffle(indices) + sampled_indices = sorted(indices[:self.max_frames]) + + print(f" [Sampling] {scene}: {num_frames} -> {self.max_frames} frames") + + # Create new scene_data with sampled frames + sampled = Dict() + sampled.image_files = [scene_data.image_files[i] for i in sampled_indices] + sampled.extrinsics = scene_data.extrinsics[sampled_indices] + sampled.intrinsics = scene_data.intrinsics[sampled_indices] + + # Copy aux data, sampling lists if needed + sampled.aux = Dict() + for key, val in scene_data.aux.items(): + if isinstance(val, list) and len(val) == num_frames: + sampled.aux[key] = [val[i] for i in sampled_indices] + elif isinstance(val, np.ndarray) and len(val) == num_frames: + sampled.aux[key] = val[sampled_indices] + else: + sampled.aux[key] = val + + return sampled + + @property + def _metric_dir(self) -> str: + """Directory for storing metric JSON files.""" + return os.path.join(self.work_dir, "metric_results") + + def _export_dir(self, data: str, scene: str, posed: bool) -> str: + """ + Get export directory path. + + Structure: .../model_results/{data}/{scene}/{posed|unposed} + """ + suffix = "posed" if posed else "unposed" + export_dir = os.path.join(self.work_dir, "model_results", data, scene, suffix) + os.makedirs(export_dir, exist_ok=True) + return export_dir + + @staticmethod + def _to_float_dict(d: TDict[str, float]) -> dict: + """Convert numpy scalars to plain Python floats for JSON safety.""" + return {k: float(v) for k, v in d.items()} + + @staticmethod + def _mean_of_dicts(dicts: Iterable[dict]) -> dict: + """Compute elementwise mean across a list of homogeneous metric dicts.""" + dicts = list(dicts) + if not dicts: + return {} + keys = dicts[0].keys() + return {k: float(np.mean([d[k] for d in dicts]).item()) for k in keys} + + @staticmethod + def _dump_json(path: str, obj: dict, indent: int = 4) -> None: + """Write JSON with UTF-8 and pretty indentation.""" + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "w", encoding="utf-8") as f: + json.dump(obj, f, indent=indent, ensure_ascii=False) + + def _load_metrics(self) -> TDict[str, dict]: + """Load evaluation metrics from JSON files.""" + metrics = {} + metric_dir = self._metric_dir + + if not os.path.exists(metric_dir): + return metrics + + for filename in os.listdir(metric_dir): + if filename.endswith(".json"): + filepath = os.path.join(metric_dir, filename) + try: + with open(filepath, encoding="utf-8") as f: + data = json.load(f) + key = filename[:-5] # Remove .json extension + metrics[key] = data + except Exception as e: + print(f"Warning: Failed to read metrics file: {filename} - {e}") + + return metrics + + +# -------------------- CLI Entry Point -------------------- # + + +if __name__ == "__main__": + import sys + from omegaconf import OmegaConf + from depth_anything_3.cfg import load_config + + # Get default config path (relative to this file) + _default_config = os.path.join( + os.path.dirname(__file__), "configs", "eval_bench.yaml" + ) + + # Check for help flag first (we need to handle this before OmegaConf) + if "--help" in sys.argv or "-h" in sys.argv: + pass # Will handle after config loading + + # Set up argv for OmegaConf processing + argv = sys.argv[1:] + + # Check if user provides custom config + config_path = _default_config + if "--config" in argv: + config_idx = argv.index("--config") + if config_idx + 1 < len(argv): + config_path = argv[config_idx + 1] + # Remove --config and its value + argv = argv[:config_idx] + argv[config_idx + 2:] + + # Print help if requested + if "--help" in sys.argv or "-h" in sys.argv: + print(""" +DepthAnything3 Benchmark Evaluation + +Usage: + python -m depth_anything_3.bench.evaluator [OPTIONS] [KEY=VALUE ...] + +Configuration: + --config PATH Config YAML file (default: bench/configs/eval_bench.yaml) + +Config Overrides (using dotlist notation): + model.path=VALUE Model path or HuggingFace ID + workspace.work_dir=VALUE Working directory for outputs + eval.datasets=[dataset1,dataset2] Datasets to evaluate (eth3d,7scenes,scannetpp,hiroom,dtu,dtu64) + eval.modes=[mode1,mode2] Evaluation modes (pose,recon_unposed,recon_posed) + eval.scenes=[scene1,scene2] Specific scenes to evaluate (null=all) + eval.max_frames=VALUE Max frames per scene (-1=no limit, default: 100) + eval.ref_view_strategy=VALUE Reference view strategy (default: first) + eval.eval_only=VALUE Only run evaluation (skip inference) (true/false) + eval.print_only=VALUE Only print saved metrics (true/false) + inference.num_fusion_workers=VALUE Number of parallel workers (default: 4) + inference.debug=VALUE Enable debug mode (true/false) + +Special Flags: + --help, -h Show this help message + +Multi-GPU: + Use CUDA_VISIBLE_DEVICES to specify GPUs (auto-detected and distributed) + +Examples: + # Use default config + python -m depth_anything_3.bench.evaluator + + # Override model path + python -m depth_anything_3.bench.evaluator model.path=depth-anything/DA3-LARGE + + # Evaluate specific datasets and modes + python -m depth_anything_3.bench.evaluator \\ + eval.datasets=[eth3d,hiroom] \\ + eval.modes=[pose] + + # Use custom config with overrides + python -m depth_anything_3.bench.evaluator \\ + --config my_config.yaml \\ + model.path=/path/to/model \\ + eval.max_frames=50 + + # Multi-GPU inference (auto-distributed) + CUDA_VISIBLE_DEVICES=0,1,2,3 python -m depth_anything_3.bench.evaluator + + # Debug specific scenes + python -m depth_anything_3.bench.evaluator \\ + eval.datasets=[eth3d] \\ + eval.scenes=[courtyard] \\ + inference.debug=true + + # Only evaluate (skip inference) + python -m depth_anything_3.bench.evaluator eval.eval_only=true + + # Only print saved metrics + python -m depth_anything_3.bench.evaluator eval.print_only=true + + """) + sys.exit(0) + + # Load config with CLI overrides using OmegaConf dotlist + # Example: python evaluator.py model.path=/path/to/model eval.datasets=[eth3d,dtu] + config = load_config(config_path, argv=argv) + + # Extract config values + work_dir = config.workspace.work_dir + model_path = config.model.path + datasets = config.eval.datasets + modes = config.eval.modes + ref_view_strategy = config.eval.ref_view_strategy + scenes = config.eval.scenes + max_frames = config.eval.max_frames + eval_only = config.eval.eval_only + print_only = config.eval.print_only + debug = config.inference.debug + num_fusion_workers = config.inference.num_fusion_workers + + # GPU settings (not in config, always from environment) + gpu_id = 0 + total_gpus = 1 + + # Override dataset scenes if specified + if scenes: + print(f"[INFO] Running on specific scenes: {scenes}") + + evaluator = Evaluator( + work_dir=work_dir, + datas=datasets, + modes=modes, + ref_view_strategy=ref_view_strategy, + scenes=scenes, + debug=debug, + num_fusion_workers=num_fusion_workers, + max_frames=max_frames, + gpu_id=gpu_id, + total_gpus=total_gpus, + ) + + if print_only: + evaluator.print_metrics() + elif eval_only: + metrics = evaluator.eval() + evaluator.print_metrics(metrics) + else: + # Parse CUDA_VISIBLE_DEVICES to get GPU list + # If not set, use all available GPUs + cuda_devices = os.environ.get("CUDA_VISIBLE_DEVICES") + if cuda_devices is not None and cuda_devices.strip(): + gpu_list = [g.strip() for g in cuda_devices.split(",") if g.strip()] + else: + # CUDA_VISIBLE_DEVICES not set, use all available GPUs + num_available = torch.cuda.device_count() + gpu_list = [str(i) for i in range(num_available)] if num_available > 0 else ["0"] + + # Auto multi-GPU: if multiple GPUs and not a worker process + is_worker = os.environ.get("_DA3_WORKER") == "1" + + if len(gpu_list) > 1 and not is_worker: + # Launch worker processes + import subprocess + + num_gpus = len(gpu_list) + print(f"[INFO] Detected {num_gpus} GPUs: {gpu_list}") + print(f"[INFO] Launching {num_gpus} workers...") + + # Build base command + base_cmd = [sys.executable, "-m", "depth_anything_3.bench.evaluator"] + # Pass config via dotlist instead of CLI args + if config_path != _default_config: + base_cmd += ["--config", config_path] + base_cmd += [f"model.path={model_path}"] + base_cmd += [f"workspace.work_dir={work_dir}"] + base_cmd += [f"eval.datasets=[{','.join(datasets)}]"] + base_cmd += [f"eval.modes=[{','.join(modes)}]"] + if scenes: + base_cmd += [f"eval.scenes=[{','.join(scenes)}]"] + base_cmd += [f"eval.max_frames={max_frames}"] + base_cmd += [f"eval.ref_view_strategy={ref_view_strategy}"] + base_cmd += [f"inference.debug={str(debug).lower()}"] + base_cmd += [f"inference.num_fusion_workers={num_fusion_workers}"] + + # Launch workers + processes = [] + for idx, gpu_id in enumerate(gpu_list): + env = os.environ.copy() + env["CUDA_VISIBLE_DEVICES"] = gpu_id + env["_DA3_WORKER"] = "1" # Mark as worker process + + cmd = base_cmd.copy() + # GPU-specific worker config + cmd += [f"gpu_id={idx}", f"total_gpus={num_gpus}"] + + print(f"[INFO] Starting worker {idx} on GPU {gpu_id}") + p = subprocess.Popen(cmd, env=env) + processes.append(p) + + # Wait for all workers + for p in processes: + p.wait() + + print(f"[INFO] All {num_gpus} workers completed") + + # Run evaluation after all inference is done + metrics = evaluator.eval() + evaluator.print_metrics(metrics) + else: + # Single GPU or worker process + from depth_anything_3.api import DepthAnything3 + + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + api = DepthAnything3.from_pretrained(model_path) + api = api.to(device) + + evaluator.infer(api, model_path=model_path) + + # Only run eval if single GPU mode (workers don't eval) + if not is_worker: + metrics = evaluator.eval() + evaluator.print_metrics(metrics) + diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/bench/print_metrics.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/bench/print_metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..9964f3bf74fdf91a15ea0ccedb30995ae79b7281 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/bench/print_metrics.py @@ -0,0 +1,618 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Beautiful metrics printing utilities for benchmark evaluation. + +Provides colorized, well-formatted tabular output for evaluation results. +Supports highlighting best/worst values and grouping by dataset/mode. +""" + +import argparse +import json +import os +import re +from typing import Dict as TDict, List, Optional + + +# ANSI color codes for terminal output +class Colors: + """ANSI escape codes for terminal colors.""" + + RESET = "\033[0m" + BOLD = "\033[1m" + RED = "\033[31m" + GREEN = "\033[32m" + YELLOW = "\033[33m" + BLUE = "\033[34m" + MAGENTA = "\033[35m" + CYAN = "\033[36m" + WHITE = "\033[37m" + + # Bold variants + BOLD_RED = "\033[1;31m" + BOLD_GREEN = "\033[1;32m" + BOLD_YELLOW = "\033[1;33m" + BOLD_BLUE = "\033[1;34m" + BOLD_MAGENTA = "\033[1;35m" + BOLD_CYAN = "\033[1;36m" + + # Background + BG_DARK = "\033[48;5;236m" + + +def strip_ansi(text: str) -> str: + """Remove ANSI escape sequences from string for length calculation.""" + ansi_escape = re.compile(r"\x1b\[[0-9;]*m") + return ansi_escape.sub("", text) + + +def colorize_value( + value: str, + is_best: bool = False, + is_worst: bool = False, + lower_is_better: bool = False, +) -> str: + """ + Apply color to a metric value based on whether it's best/worst. + + Args: + value: String representation of the value + is_best: Whether this is the best value in its column + is_worst: Whether this is the worst value in its column + lower_is_better: If True, lower values are better (e.g., error metrics) + + Returns: + Colorized string + """ + if lower_is_better: + # For metrics like error/distance, lower is better + if is_best: + return f"{Colors.BOLD_GREEN}{value}{Colors.RESET}" + elif is_worst: + return f"{Colors.BOLD_RED}{value}{Colors.RESET}" + else: + # For metrics like accuracy/AUC, higher is better + if is_best: + return f"{Colors.BOLD_GREEN}{value}{Colors.RESET}" + elif is_worst: + return f"{Colors.BOLD_RED}{value}{Colors.RESET}" + return value + + +class MetricsPrinter: + """ + Beautiful tabular metrics printer with color support. + + Features: + - Colorized best/worst values + - Grouped by dataset and evaluation mode + - Automatic column width calculation + - Support for multiple input directories comparison + """ + + # Metrics where lower values are better + LOWER_IS_BETTER = {"comp", "acc", "overall", "error", "loss", "rmse", "mae"} + + def __init__(self, use_color: bool = True): + """ + Initialize the printer. + + Args: + use_color: Whether to use ANSI colors in output + """ + self.use_color = use_color + + def print_results(self, metrics: TDict[str, dict], summary_only: bool = True) -> None: + """ + Print evaluation metrics in a beautiful tabular format. + + Args: + metrics: Dictionary mapping "dataset_mode" to metric results + summary_only: If True, only print summary table. If False, print per-dataset details too. + """ + if not metrics: + print(f"\n{Colors.BOLD_RED}❌ No evaluation metrics found{Colors.RESET}") + return + + if not summary_only: + self._print_header() + grouped = self._group_by_dataset(metrics) + + for dataset, modes_data in grouped.items(): + self._print_dataset_section(dataset, modes_data) + + # Print summary table with average metrics across datasets + self._print_summary(metrics) + + self._print_footer() + + def print_comparison( + self, + metrics_list: List[TDict[str, dict]], + labels: List[str], + ) -> None: + """ + Print comparison table for multiple evaluation runs. + + Args: + metrics_list: List of metrics dictionaries + labels: Labels for each metrics dictionary + """ + if not metrics_list or not all(metrics_list): + print(f"\n{Colors.BOLD_RED}❌ No metrics to compare{Colors.RESET}") + return + + # Collect all datasets and modes + all_keys = set() + for metrics in metrics_list: + all_keys.update(metrics.keys()) + + self._print_header("COMPARISON") + + for key in sorted(all_keys): + parts = key.rsplit("_", 1) + if len(parts) == 2: + dataset, mode = parts[0], parts[1] + else: + dataset, mode = key, "unknown" + + print(f"\n{Colors.BOLD_CYAN}📊 {dataset.upper()} - {mode.upper()}{Colors.RESET}") + print("-" * 100) + + # Collect metrics from all runs + all_metric_names = set() + for metrics in metrics_list: + if key in metrics and "mean" in metrics[key]: + all_metric_names.update(metrics[key]["mean"].keys()) + + if not all_metric_names: + continue + + # Build comparison table + metric_width = max(15, max(len(m) for m in all_metric_names) + 2) + label_width = max(15, max(len(l) for l in labels) + 2) + + # Header + header = f"{'Metric':<{metric_width}}" + for label in labels: + header += f"{label:<{label_width}}" + print(header) + print("-" * len(strip_ansi(header))) + + # Collect values for highlighting + for metric_name in sorted(all_metric_names): + values = [] + for metrics in metrics_list: + if key in metrics and "mean" in metrics[key]: + val = metrics[key]["mean"].get(metric_name) + values.append(val if val is not None else float("nan")) + else: + values.append(float("nan")) + + # Find best/worst + valid_values = [v for v in values if not (v != v)] # Filter NaN + if valid_values: + lower_better = any( + lb in metric_name.lower() for lb in self.LOWER_IS_BETTER + ) + best_val = min(valid_values) if lower_better else max(valid_values) + worst_val = max(valid_values) if lower_better else min(valid_values) + else: + best_val = worst_val = None + + # Print row + row = f"{metric_name:<{metric_width}}" + for val in values: + if val != val: # NaN check + val_str = "N/A" + else: + val_str = f"{val:.4f}" + if self.use_color and len(valid_values) > 1: + lower_better = any( + lb in metric_name.lower() for lb in self.LOWER_IS_BETTER + ) + is_best = abs(val - best_val) < 1e-8 if best_val else False + is_worst = abs(val - worst_val) < 1e-8 if worst_val else False + val_str_padded = f"{val_str:<{label_width}}" + val_str = colorize_value( + val_str_padded, is_best, is_worst, lower_better + ) + row += val_str + continue + row += f"{val_str:<{label_width}}" + print(row) + + self._print_footer() + + def _print_header(self, title: str = "EVALUATION RESULTS") -> None: + """Print report header.""" + width = 100 + print() + print("=" * width) + print(f"{Colors.BOLD_CYAN}📊 DEPTH ANYTHING 3 {title}{Colors.RESET}") + print("=" * width) + + def _print_footer(self) -> None: + """Print report footer.""" + width = 100 + print() + print("=" * width) + print(f"{Colors.BOLD_GREEN}✅ Evaluation Complete{Colors.RESET}") + print("=" * width) + print() + + def _group_by_dataset(self, metrics: TDict[str, dict]) -> TDict[str, dict]: + """Group metrics by dataset.""" + grouped = {} + for key, data in metrics.items(): + if not isinstance(data, dict) or "mean" not in data: + continue + # Parse key format: "dataset_mode" (e.g., "dtu_recon_unposed") + parts = key.split("_", 1) + if len(parts) == 2: + dataset, mode = parts + if dataset not in grouped: + grouped[dataset] = {} + grouped[dataset][mode] = data + return grouped + + def _print_dataset_section(self, dataset: str, modes_data: TDict[str, dict]) -> None: + """Print metrics section for a single dataset.""" + print(f"\n{Colors.BOLD_MAGENTA}🔍 {dataset.upper()}{Colors.RESET}") + print("-" * 100) + + # Collect all unique metrics across all modes + all_metrics = set() + for mode_data in modes_data.values(): + all_metrics.update(mode_data["mean"].keys()) + all_metrics = sorted(list(all_metrics)) + + if not all_metrics: + print(" No metrics available") + return + + # Calculate column widths + metric_width = max(18, max(len(m) for m in all_metrics) + 2) + mode_width = 18 + modes = list(modes_data.keys()) + + # Print header + header = f"{'Metric':<{metric_width}}" + for mode in modes: + header += f"{mode.upper():<{mode_width}}" + print(f"{Colors.BOLD}{header}{Colors.RESET}") + print("-" * len(header)) + + # Print each metric row + for metric in all_metrics: + row = f"{metric:<{metric_width}}" + + # Collect values for this metric across modes + values = [] + for mode in modes: + if metric in modes_data[mode]["mean"]: + values.append(modes_data[mode]["mean"][metric]) + else: + values.append(None) + + # Find best/worst values + valid_values = [v for v in values if v is not None] + if valid_values: + lower_better = any(lb in metric.lower() for lb in self.LOWER_IS_BETTER) + best_val = min(valid_values) if lower_better else max(valid_values) + worst_val = max(valid_values) if lower_better else min(valid_values) + else: + best_val = worst_val = None + + # Format each value + for val in values: + if val is None: + row += f"{'N/A':<{mode_width}}" + else: + val_str = f"{val:.4f}" + if self.use_color and len(valid_values) > 1: + is_best = abs(val - best_val) < 1e-8 if best_val else False + is_worst = abs(val - worst_val) < 1e-8 if worst_val else False + lower_better = any( + lb in metric.lower() for lb in self.LOWER_IS_BETTER + ) + # Pad before colorizing to maintain alignment + val_str_padded = f"{val_str:<{mode_width}}" + row += colorize_value( + val_str_padded, is_best, is_worst, lower_better + ) + else: + row += f"{val_str:<{mode_width}}" + print(row) + + # Show scene counts + scene_info = [] + for mode, mode_data in modes_data.items(): + scene_count = len([k for k in mode_data.keys() if k != "mean"]) + scene_info.append(f"{mode}: {scene_count} scenes") + print(f"\n{Colors.CYAN}📈 {' | '.join(scene_info)}{Colors.RESET}") + + def _print_summary(self, metrics: TDict[str, dict]) -> None: + """ + Print summary table with key metrics across all datasets. + + Format: One row per metric, datasets as columns. + Order: HiRoom, ETH3D, DTU, 7Scenes, ScanNet++, (DTU-64 for pose only) + """ + print(f"\n{Colors.BOLD_CYAN}{'=' * 120}{Colors.RESET}") + print(f"{Colors.BOLD_CYAN}📊 SUMMARY{Colors.RESET}") + print(f"{Colors.BOLD_CYAN}{'=' * 120}{Colors.RESET}") + + # Dataset display order and names + DATASET_ORDER = ["hiroom", "eth3d", "dtu", "7scenes", "scannetpp", "dtu64"] + DATASET_DISPLAY = { + "hiroom": "HiRoom", + "eth3d": "ETH3D", + "dtu": "DTU", + "7scenes": "7Scenes", + "scannetpp": "ScanNet++", + "dtu64": "DTU-64", + } + + # Collect all metrics into a structured dict + # metric_data[dataset][mode] = {"Auc_3": x, "Auc_30": x, "fscore": x, "overall": x} + metric_data = {} + for key, data in metrics.items(): + if not isinstance(data, dict) or "mean" not in data: + continue + parts = key.split("_", 1) + if len(parts) != 2: + continue + dataset, mode = parts + dataset_lower = dataset.lower() + if dataset_lower not in metric_data: + metric_data[dataset_lower] = {} + metric_data[dataset_lower][mode] = data["mean"] + + col_width = 12 + + def fmt_val(val): + """Format value or return N/A.""" + if val is None: + return "N/A" + return f"{val:.4f}" + + def get_metric(dataset, mode, metric_name): + """Get metric value or None.""" + if dataset not in metric_data: + return None + if mode not in metric_data[dataset]: + return None + return metric_data[dataset][mode].get(metric_name) + + # ============ POSE METRICS ============ + print(f"\n{Colors.BOLD_MAGENTA}🎯 POSE ESTIMATION{Colors.RESET}") + + # Pose: show all datasets except DTU (keep DTU-64 only) + # Order: HiRoom, ETH3D, DTU-64, 7Scenes, ScanNet++ + pose_datasets = ["hiroom", "eth3d", "dtu64", "7scenes", "scannetpp"] + + # Header: Avg first, then datasets + header = f"{'Metric':<15}{'Avg':<{col_width}}" + for ds in pose_datasets: + header += f"{DATASET_DISPLAY[ds]:<{col_width}}" + print("-" * len(strip_ansi(header))) + print(f"{Colors.BOLD}{header}{Colors.RESET}") + print("-" * len(strip_ansi(header))) + + # Helper to get metric with fallback names + def get_pose_metric(dataset, metric_name): + """Get pose metric with fallback for different naming conventions.""" + # Try different naming conventions + names = { + "Auc3": ["Auc_3", "auc03", "auc_3", "AUC_3", "Auc3", "auc3"], + "Auc30": ["Auc_30", "auc30", "auc_30", "AUC_30", "Auc30"], + } + for name in names.get(metric_name, [metric_name]): + val = get_metric(dataset, "pose", name) + if val is not None: + return val + return None + + # Auc3 row + values = [] + for ds in pose_datasets: + val = get_pose_metric(ds, "Auc3") + if val is not None: + values.append(val) + avg = sum(values) / len(values) if values else None + row = f"{'Auc3':<15}{Colors.BOLD_GREEN}{fmt_val(avg):<{col_width}}{Colors.RESET}" + for ds in pose_datasets: + val = get_pose_metric(ds, "Auc3") + row += f"{fmt_val(val):<{col_width}}" + print(row) + + # Auc30 row + values = [] + for ds in pose_datasets: + val = get_pose_metric(ds, "Auc30") + if val is not None: + values.append(val) + avg = sum(values) / len(values) if values else None + row = f"{'Auc30':<15}{Colors.BOLD_GREEN}{fmt_val(avg):<{col_width}}{Colors.RESET}" + for ds in pose_datasets: + val = get_pose_metric(ds, "Auc30") + row += f"{fmt_val(val):<{col_width}}" + print(row) + + # ============ RECON_UNPOSED METRICS ============ + print(f"\n{Colors.BOLD_MAGENTA}🏗️ RECON_UNPOSED (Pred Pose){Colors.RESET}") + + # For recon, exclude dtu64 from columns + recon_datasets = ["hiroom", "eth3d", "dtu", "7scenes", "scannetpp"] + avg_datasets = ["hiroom", "eth3d", "7scenes", "scannetpp"] # Exclude DTU from avg + + # Header: Avg first, then datasets + header = f"{'Metric':<15}{'Avg*':<{col_width}}" + for ds in recon_datasets: + header += f"{DATASET_DISPLAY[ds]:<{col_width}}" + print("-" * len(strip_ansi(header))) + print(f"{Colors.BOLD}{header}{Colors.RESET}") + print("-" * len(strip_ansi(header))) + + # F-score row (only metric for avg) + values = [] + for ds in recon_datasets: + val = get_metric(ds, "recon_unposed", "fscore") + if val is not None and ds in avg_datasets: + values.append(val) + avg = sum(values) / len(values) if values else None + row = f"{'F-score':<15}{Colors.BOLD_GREEN}{fmt_val(avg):<{col_width}}{Colors.RESET}" + for ds in recon_datasets: + val = get_metric(ds, "recon_unposed", "fscore") + row += f"{fmt_val(val):<{col_width}}" + print(row) + + # Overall row (avg over 4 datasets excluding DTU) + values = [] + for ds in recon_datasets: + val = get_metric(ds, "recon_unposed", "overall") + if val is not None and ds in avg_datasets: + values.append(val) + avg = sum(values) / len(values) if values else None + row = f"{'Overall':<15}{Colors.BOLD_GREEN}{fmt_val(avg):<{col_width}}{Colors.RESET}" + for ds in recon_datasets: + val = get_metric(ds, "recon_unposed", "overall") + row += f"{fmt_val(val):<{col_width}}" + print(row) + + # ============ RECON_POSED METRICS ============ + print(f"\n{Colors.BOLD_MAGENTA}🏗️ RECON_POSED (GT Pose){Colors.RESET}") + + # Header: Avg first, then datasets + header = f"{'Metric':<15}{'Avg*':<{col_width}}" + for ds in recon_datasets: + header += f"{DATASET_DISPLAY[ds]:<{col_width}}" + print("-" * len(strip_ansi(header))) + print(f"{Colors.BOLD}{header}{Colors.RESET}") + print("-" * len(strip_ansi(header))) + + # F-score row (only metric for avg) + values = [] + for ds in recon_datasets: + val = get_metric(ds, "recon_posed", "fscore") + if val is not None and ds in avg_datasets: + values.append(val) + avg = sum(values) / len(values) if values else None + row = f"{'F-score':<15}{Colors.BOLD_GREEN}{fmt_val(avg):<{col_width}}{Colors.RESET}" + for ds in recon_datasets: + val = get_metric(ds, "recon_posed", "fscore") + row += f"{fmt_val(val):<{col_width}}" + print(row) + + # Overall row (avg over 4 datasets excluding DTU) + values = [] + for ds in recon_datasets: + val = get_metric(ds, "recon_posed", "overall") + if val is not None and ds in avg_datasets: + values.append(val) + avg = sum(values) / len(values) if values else None + row = f"{'Overall':<15}{Colors.BOLD_GREEN}{fmt_val(avg):<{col_width}}{Colors.RESET}" + for ds in recon_datasets: + val = get_metric(ds, "recon_posed", "overall") + row += f"{fmt_val(val):<{col_width}}" + print(row) + + print(f"\n{Colors.CYAN}* Avg F-score / Overall = average over HiRoom, ETH3D, 7Scenes, ScanNet++ (4 datasets){Colors.RESET}") + + +def load_metrics_from_dir(metric_dir: str) -> TDict[str, dict]: + """ + Load all metrics JSON files from a directory. + + Args: + metric_dir: Path to directory containing metric JSON files + + Returns: + Dictionary mapping filename (without .json) to metric data + """ + metrics = {} + if not os.path.exists(metric_dir): + return metrics + + for filename in os.listdir(metric_dir): + if filename.endswith(".json"): + filepath = os.path.join(metric_dir, filename) + try: + with open(filepath, encoding="utf-8") as f: + content = f.read() + # Handle trailing commas in JSON + content = re.sub(r",\s*([\]\}])", r"\1", content) + data = json.loads(content) + key = filename[:-5] + metrics[key] = data + except Exception as e: + print(f"Warning: Failed to load {filename}: {e}") + + return metrics + + +def main(): + """Command-line interface for metrics printing.""" + parser = argparse.ArgumentParser( + description="Print DepthAnything3 benchmark evaluation metrics." + ) + parser.add_argument( + "--input_dir", + type=str, + default="./eval_workspace/metric_results", + help="Directory containing metric JSON files (comma-separated for comparison)", + ) + parser.add_argument( + "--no_color", + action="store_true", + help="Disable colored output", + ) + parser.add_argument( + "--key", + type=str, + default=None, + help="Specific metric key to highlight", + ) + args = parser.parse_args() + + # Support multiple directories for comparison + input_dirs = [d.strip() for d in args.input_dir.split(",") if d.strip()] + + printer = MetricsPrinter(use_color=not args.no_color) + + if len(input_dirs) == 1: + # Single directory - simple print + metrics = load_metrics_from_dir(input_dirs[0]) + printer.print_results(metrics) + else: + # Multiple directories - comparison mode + metrics_list = [] + labels = [] + for d in input_dirs: + metrics = load_metrics_from_dir(d) + if metrics: + metrics_list.append(metrics) + labels.append(os.path.basename(d.rstrip("/"))) + + if metrics_list: + printer.print_comparison(metrics_list, labels) + else: + print("No metrics found in specified directories") + + +if __name__ == "__main__": + main() + diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/bench/registries.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/bench/registries.py new file mode 100644 index 0000000000000000000000000000000000000000..0744661e3dcf7664fc70df5956add84f472109c4 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/bench/registries.py @@ -0,0 +1,85 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Auto-loading registry system for benchmark datasets. + +This module provides registry classes that automatically discover and import +dataset implementations from the datasets subpackage on first access. +""" + +import importlib +import pkgutil +import threading + +from depth_anything_3.utils.registry import Registry + +__all__ = ["METRIC_REGISTRY", "MONO_REGISTRY", "MV_REGISTRY", "NVS_REGISTRY"] + +# ---- Lazy import: Only scan and import all datasets submodules on first registry access ---- +_loaded = False +_lock = threading.Lock() + + +def _import_all_datasets_once(): + """ + Scan and import all .py submodules under depth_anything_3.bench.datasets + (skip files/packages starting with underscore), to trigger @REGISTRY.register(...) in each module. + """ + global _loaded + if _loaded: + return + + with _lock: + if _loaded: + return + + pkg_name = "depth_anything_3.bench.datasets" + pkg = importlib.import_module(pkg_name) + pkg_paths = list(getattr(pkg, "__path__", [])) + + for finder, name, ispkg in pkgutil.walk_packages(pkg_paths, prefix=pkg_name + "."): + base = name.rsplit(".", 1)[-1] + if base.startswith("_"): + continue + try: + importlib.import_module(name) + except Exception as e: + print(f"[datasets auto-import] Failed to import {name}: {e}") + + _loaded = True + + +class AutoRegistry(Registry): + """Registry that ensures all datasets are auto-discovered and imported on first use.""" + + def get(self, name): + _import_all_datasets_once() + return super().get(name) + + def all(self): + _import_all_datasets_once() + return super().all() + + def has(self, name): + _import_all_datasets_once() + return name in self._map + + +# Four auto-lazy registry instances for different evaluation types +METRIC_REGISTRY = AutoRegistry() # For metric depth evaluation +MONO_REGISTRY = AutoRegistry() # For monocular depth evaluation +MV_REGISTRY = AutoRegistry() # For multi-view evaluation +NVS_REGISTRY = AutoRegistry() # For novel view synthesis evaluation + diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/bench/utils.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/bench/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ca654773122c247e15d4a99a0beb5d0e80ac8e20 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/bench/utils.py @@ -0,0 +1,525 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Utility functions for benchmark evaluation. + +Contains: +- Pose evaluation metrics (AUC) and helper functions +- 3D reconstruction evaluation metrics (Acc/Comp/F-score) +- Geometry utilities (quaternion conversion, etc.) +""" + +from typing import Dict as TDict, Optional, Tuple, Union + +import numpy as np +import open3d as o3d +import torch +from addict import Dict +from scipy.spatial import KDTree + +from depth_anything_3.utils.geometry import mat_to_quat + + +# ============================================================================= +# Geometry Utilities +# ============================================================================= + + +def quat2rotmat(qvec: list) -> np.ndarray: + """ + Convert quaternion (WXYZ order) to rotation matrix. + + Args: + qvec: Quaternion as [w, x, y, z] + + Returns: + 3x3 rotation matrix + """ + rotmat = np.array( + [ + 1 - 2 * qvec[2] ** 2 - 2 * qvec[3] ** 2, + 2 * qvec[1] * qvec[2] - 2 * qvec[0] * qvec[3], + 2 * qvec[3] * qvec[1] + 2 * qvec[0] * qvec[2], + 2 * qvec[1] * qvec[2] + 2 * qvec[0] * qvec[3], + 1 - 2 * qvec[1] ** 2 - 2 * qvec[3] ** 2, + 2 * qvec[2] * qvec[3] - 2 * qvec[0] * qvec[1], + 2 * qvec[3] * qvec[1] - 2 * qvec[0] * qvec[2], + 2 * qvec[2] * qvec[3] + 2 * qvec[0] * qvec[1], + 1 - 2 * qvec[1] ** 2 - 2 * qvec[2] ** 2, + ] + ) + rotmat = rotmat.reshape(3, 3) + return rotmat + + +# ============================================================================= +# 3D Reconstruction Evaluation +# ============================================================================= + + +def nn_correspondance(verts1: np.ndarray, verts2: np.ndarray) -> np.ndarray: + """ + Compute nearest neighbor distances from verts2 to verts1 using KDTree. + + Args: + verts1: Reference point cloud [N, 3] + verts2: Query point cloud [M, 3] + + Returns: + Distance array [M,] - distance from each point in verts2 to nearest in verts1 + """ + if len(verts1) == 0 or len(verts2) == 0: + return np.array([]) + + kdtree = KDTree(verts1) + distances, _ = kdtree.query(verts2) + return distances.reshape(-1) + + +def evaluate_3d_reconstruction( + pcd_pred: Union[o3d.geometry.PointCloud, np.ndarray], + pcd_trgt: Union[o3d.geometry.PointCloud, np.ndarray], + threshold: float = 0.05, + down_sample: Optional[float] = None, +) -> TDict[str, float]: + """ + Evaluate 3D reconstruction quality using standard metrics. + + This function computes: + - Accuracy: Mean distance from predicted points to GT surface + - Completeness: Mean distance from GT points to predicted surface + - Overall: Average of accuracy and completeness + - Precision: Fraction of predicted points within threshold of GT + - Recall: Fraction of GT points within threshold of prediction + - F-score: Harmonic mean of precision and recall + + Args: + pcd_pred: Predicted point cloud (Open3D or numpy array) + pcd_trgt: Ground truth point cloud (Open3D or numpy array) + threshold: Distance threshold for precision/recall (meters) + down_sample: Voxel size for downsampling (None to skip) + + Returns: + Dict with metrics: acc, comp, overall, precision, recall, fscore + """ + # Convert to Open3D if needed + if isinstance(pcd_pred, np.ndarray): + pcd_pred_o3d = o3d.geometry.PointCloud() + pcd_pred_o3d.points = o3d.utility.Vector3dVector(pcd_pred) + pcd_pred = pcd_pred_o3d + if isinstance(pcd_trgt, np.ndarray): + pcd_trgt_o3d = o3d.geometry.PointCloud() + pcd_trgt_o3d.points = o3d.utility.Vector3dVector(pcd_trgt) + pcd_trgt = pcd_trgt_o3d + + # Downsample if requested + if down_sample is not None and down_sample > 0: + pcd_pred = pcd_pred.voxel_down_sample(down_sample) + pcd_trgt = pcd_trgt.voxel_down_sample(down_sample) + + verts_pred = np.asarray(pcd_pred.points) + verts_trgt = np.asarray(pcd_trgt.points) + + # Handle empty point clouds + if len(verts_pred) == 0 or len(verts_trgt) == 0: + return { + "acc": float("inf"), + "comp": float("inf"), + "overall": float("inf"), + "precision": 0.0, + "recall": 0.0, + "fscore": 0.0, + } + + # Compute distances + dist_pred_to_gt = nn_correspondance(verts_trgt, verts_pred) # Accuracy + dist_gt_to_pred = nn_correspondance(verts_pred, verts_trgt) # Completeness + + # Compute metrics + accuracy = float(np.mean(dist_pred_to_gt)) + completeness = float(np.mean(dist_gt_to_pred)) + overall = (accuracy + completeness) / 2 + + precision = float(np.mean((dist_pred_to_gt < threshold).astype(float))) + recall = float(np.mean((dist_gt_to_pred < threshold).astype(float))) + + if precision + recall > 0: + fscore = 2 * precision * recall / (precision + recall) + else: + fscore = 0.0 + + return { + "acc": accuracy, + "comp": completeness, + "overall": overall, + "precision": precision, + "recall": recall, + "fscore": fscore, + } + + +def create_tsdf_volume( + voxel_length: float = 4.0 / 512.0, + sdf_trunc: float = 0.04, + color_type: str = "RGB8", +) -> o3d.pipelines.integration.ScalableTSDFVolume: + """ + Create a scalable TSDF volume for depth fusion. + + Args: + voxel_length: Size of each voxel + sdf_trunc: Truncation distance for SDF + color_type: Color integration type ("RGB8" or "Gray32") + + Returns: + Initialized ScalableTSDFVolume + """ + if color_type == "RGB8": + color_enum = o3d.pipelines.integration.TSDFVolumeColorType.RGB8 + else: + color_enum = o3d.pipelines.integration.TSDFVolumeColorType.Gray32 + + volume = o3d.pipelines.integration.ScalableTSDFVolume( + voxel_length=voxel_length, + sdf_trunc=sdf_trunc, + color_type=color_enum, + ) + return volume + + +def fuse_depth_to_tsdf( + volume: o3d.pipelines.integration.ScalableTSDFVolume, + depths: np.ndarray, + images: np.ndarray, + intrinsics: np.ndarray, + extrinsics: np.ndarray, + max_depth: float = 10.0, +) -> o3d.geometry.TriangleMesh: + """ + Fuse multiple depth maps into TSDF volume and extract mesh. + + Args: + volume: TSDF volume to integrate into + depths: Depth maps [N, H, W] + images: RGB images [N, H, W, 3] + intrinsics: Camera intrinsics [N, 3, 3] + extrinsics: Camera extrinsics (world-to-camera) [N, 4, 4] + max_depth: Maximum depth for truncation + + Returns: + Extracted triangle mesh + """ + for i in range(len(depths)): + depth = depths[i] + image = images[i] + ixt = intrinsics[i] + ext = extrinsics[i] + + h, w = depth.shape[:2] + + # Create RGBD image + depth_o3d = o3d.geometry.Image(depth.astype(np.float32)) + color_o3d = o3d.geometry.Image(image.astype(np.uint8)) + rgbd = o3d.geometry.RGBDImage.create_from_color_and_depth( + color_o3d, + depth_o3d, + depth_trunc=max_depth, + convert_rgb_to_intensity=False, + depth_scale=1.0, + ) + + # Create camera intrinsics + ixt_o3d = o3d.camera.PinholeCameraIntrinsic( + w, h, ixt[0, 0], ixt[1, 1], ixt[0, 2], ixt[1, 2] + ) + + # Integrate into volume + volume.integrate(rgbd, ixt_o3d, ext) + + # Extract mesh + mesh = volume.extract_triangle_mesh() + return mesh + + +def sample_points_from_mesh( + mesh: o3d.geometry.TriangleMesh, + num_points: int = 1000000, +) -> o3d.geometry.PointCloud: + """ + Uniformly sample points from a triangle mesh. + + Args: + mesh: Input triangle mesh + num_points: Number of points to sample + + Returns: + Sampled point cloud + """ + try: + pcd = mesh.sample_points_uniformly(number_of_points=num_points) + # Clamp colors to valid range [0, 1] for Open3D PLY export + if pcd.has_colors(): + colors = np.asarray(pcd.colors) + colors = np.clip(colors, 0.0, 1.0) + pcd.colors = o3d.utility.Vector3dVector(colors) + except Exception: + # Fallback: create random points if mesh is invalid (with fixed seed for reproducibility) + rng = np.random.default_rng(seed=42) + points = rng.uniform(-1, 1, size=(num_points, 3)) + pcd = o3d.geometry.PointCloud() + pcd.points = o3d.utility.Vector3dVector(points) + return pcd + + +# ============================================================================= +# Pose Evaluation +# ============================================================================= + + +def build_pair_index(N: int, B: int = 1): + """ + Build indices for all possible pairs of frames. + + Args: + N: Number of frames + B: Batch size + + Returns: + i1, i2: Indices for all possible pairs + """ + i1_, i2_ = torch.combinations(torch.arange(N), 2, with_replacement=False).unbind(-1) + i1, i2 = ((i[None] + torch.arange(B)[:, None] * N).reshape(-1) for i in [i1_, i2_]) + return i1, i2 + + +def compute_pose(pred_se3: torch.Tensor, gt_se3: torch.Tensor) -> Dict: + """ + Compute pose estimation metrics between predicted and ground truth trajectories. + + Args: + pred_se3: Predicted SE(3) transformations [N, 4, 4] + gt_se3: Ground truth SE(3) transformations [N, 4, 4] + + Returns: + Dict with AUC metrics at different thresholds (auc30, auc15, auc05, auc03) + """ + pred_se3 = align_to_first_camera(pred_se3) + gt_se3 = align_to_first_camera(gt_se3) + + rel_rangle_deg, rel_tangle_deg = se3_to_relative_pose_error(pred_se3, gt_se3, len(pred_se3)) + rError = rel_rangle_deg.cpu().numpy() + tError = rel_tangle_deg.cpu().numpy() + + output = Dict() + output.auc30, _ = calculate_auc_np(rError, tError, max_threshold=30) + output.auc15, _ = calculate_auc_np(rError, tError, max_threshold=15) + output.auc05, _ = calculate_auc_np(rError, tError, max_threshold=5) + output.auc03, _ = calculate_auc_np(rError, tError, max_threshold=3) + return output + + +def align_to_first_camera(camera_poses: torch.Tensor) -> torch.Tensor: + """ + Align all camera poses to the first camera's coordinate frame. + + Args: + camera_poses: Camera poses as SE3 transformations [N, 4, 4] + + Returns: + Aligned camera poses [N, 4, 4] + """ + first_cam_extrinsic_inv = closed_form_inverse_se3(camera_poses[0][None]) + aligned_poses = torch.matmul(camera_poses, first_cam_extrinsic_inv) + return aligned_poses + + +def rotation_angle( + rot_gt: torch.Tensor, rot_pred: torch.Tensor, batch_size: int = None, eps: float = 1e-15 +) -> torch.Tensor: + """ + Calculate rotation angle error between ground truth and predicted rotations. + + Args: + rot_gt: Ground truth rotation matrices + rot_pred: Predicted rotation matrices + batch_size: Batch size for reshaping the result + eps: Small value to avoid numerical issues + + Returns: + Rotation angle error in degrees + """ + q_pred = mat_to_quat(rot_pred) + q_gt = mat_to_quat(rot_gt) + + loss_q = (1 - (q_pred * q_gt).sum(dim=1) ** 2).clamp(min=eps) + err_q = torch.arccos(1 - 2 * loss_q) + + rel_rangle_deg = err_q * 180 / np.pi + + if batch_size is not None: + rel_rangle_deg = rel_rangle_deg.reshape(batch_size, -1) + + return rel_rangle_deg + + +def translation_angle( + tvec_gt: torch.Tensor, + tvec_pred: torch.Tensor, + batch_size: int = None, + ambiguity: bool = True, +) -> torch.Tensor: + """ + Calculate translation angle error between ground truth and predicted translations. + + Args: + tvec_gt: Ground truth translation vectors + tvec_pred: Predicted translation vectors + batch_size: Batch size for reshaping the result + ambiguity: Whether to handle direction ambiguity + + Returns: + Translation angle error in degrees + """ + rel_tangle_deg = compare_translation_by_angle(tvec_gt, tvec_pred) + rel_tangle_deg = rel_tangle_deg * 180.0 / np.pi + + if ambiguity: + rel_tangle_deg = torch.min(rel_tangle_deg, (180 - rel_tangle_deg).abs()) + + if batch_size is not None: + rel_tangle_deg = rel_tangle_deg.reshape(batch_size, -1) + + return rel_tangle_deg + + +def compare_translation_by_angle( + t_gt: torch.Tensor, t: torch.Tensor, eps: float = 1e-15, default_err: float = 1e6 +) -> torch.Tensor: + """ + Normalize the translation vectors and compute the angle between them. + + Args: + t_gt: Ground truth translation vectors + t: Predicted translation vectors + eps: Small value to avoid division by zero + default_err: Default error value for invalid cases + + Returns: + Angular error between translation vectors in radians + """ + t_norm = torch.norm(t, dim=1, keepdim=True) + t = t / (t_norm + eps) + + t_gt_norm = torch.norm(t_gt, dim=1, keepdim=True) + t_gt = t_gt / (t_gt_norm + eps) + + loss_t = torch.clamp_min(1.0 - torch.sum(t * t_gt, dim=1) ** 2, eps) + err_t = torch.acos(torch.sqrt(1 - loss_t)) + + err_t[torch.isnan(err_t) | torch.isinf(err_t)] = default_err + return err_t + + +def calculate_auc_np( + r_error: np.ndarray, t_error: np.ndarray, max_threshold: int = 30 +) -> tuple: + """ + Calculate the Area Under the Curve (AUC) for the given error arrays. + + Args: + r_error: Rotation error values in degrees + t_error: Translation error values in degrees + max_threshold: Maximum threshold value for binning + + Returns: + Tuple of (AUC value, normalized histogram) + """ + error_matrix = np.concatenate((r_error[:, None], t_error[:, None]), axis=1) + max_errors = np.max(error_matrix, axis=1) + bins = np.arange(max_threshold + 1) + histogram, _ = np.histogram(max_errors, bins=bins) + num_pairs = float(len(max_errors)) + normalized_histogram = histogram.astype(float) / num_pairs + return np.mean(np.cumsum(normalized_histogram)), normalized_histogram + + +def se3_to_relative_pose_error( + pred_se3: torch.Tensor, gt_se3: torch.Tensor, num_frames: int +) -> tuple: + """ + Compute rotation and translation errors between predicted and ground truth poses. + + Args: + pred_se3: Predicted SE(3) transformations + gt_se3: Ground truth SE(3) transformations + num_frames: Number of frames + + Returns: + Tuple of (rotation angle errors, translation angle errors) in degrees + """ + pair_idx_i1, pair_idx_i2 = build_pair_index(num_frames) + + # Compute relative camera poses between pairs using closed-form inverse + relative_pose_gt = closed_form_inverse_se3(gt_se3[pair_idx_i1]).bmm(gt_se3[pair_idx_i2]) + relative_pose_pred = closed_form_inverse_se3(pred_se3[pair_idx_i1]).bmm(pred_se3[pair_idx_i2]) + + # Compute the difference in rotation and translation + rel_rangle_deg = rotation_angle(relative_pose_gt[:, :3, :3], relative_pose_pred[:, :3, :3]) + rel_tangle_deg = translation_angle(relative_pose_gt[:, :3, 3], relative_pose_pred[:, :3, 3]) + + return rel_rangle_deg, rel_tangle_deg + + +def closed_form_inverse_se3( + se3: torch.Tensor, R: torch.Tensor = None, T: torch.Tensor = None +) -> torch.Tensor: + """ + Compute the inverse of each 4x4 (or 3x4) SE3 matrix in a batch. + + Uses closed-form solution instead of torch.inverse() for numerical stability. + + Args: + se3: Nx4x4 or Nx3x4 tensor of SE3 matrices + R: Optional Nx3x3 rotation matrices + T: Optional Nx3x1 translation vectors + + Returns: + Inverted SE3 matrices with same shape as input + """ + is_numpy = isinstance(se3, np.ndarray) + + if se3.shape[-2:] != (4, 4) and se3.shape[-2:] != (3, 4): + raise ValueError(f"se3 must be of shape (N,4,4), got {se3.shape}.") + + if R is None: + R = se3[:, :3, :3] + if T is None: + T = se3[:, :3, 3:] + + if is_numpy: + R_transposed = np.transpose(R, (0, 2, 1)) + top_right = -np.matmul(R_transposed, T) + inverted_matrix = np.tile(np.eye(4), (len(R), 1, 1)) + else: + R_transposed = R.transpose(1, 2) + top_right = -torch.bmm(R_transposed, T) + inverted_matrix = torch.eye(4, 4)[None].repeat(len(R), 1, 1) + inverted_matrix = inverted_matrix.to(R.dtype).to(R.device) + + inverted_matrix[:, :3, :3] = R_transposed + inverted_matrix[:, :3, 3:] = top_right + + return inverted_matrix + diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/cfg.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/cfg.py new file mode 100644 index 0000000000000000000000000000000000000000..4607ff8c0983b67e6ccd2d80b78a163c4e487250 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/cfg.py @@ -0,0 +1,144 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Configuration utility functions +""" + +import importlib +from pathlib import Path +from typing import Any, Callable, List, Union +from omegaconf import DictConfig, ListConfig, OmegaConf + +try: + OmegaConf.register_new_resolver("eval", eval) +except Exception as e: + # if eval is not available, we can just pass + print(f"Error registering eval resolver: {e}") + + +def load_config(path: str, argv: List[str] = None) -> Union[DictConfig, ListConfig]: + """ + Load a configuration. Will resolve inheritance. + Supports both file paths and module paths (e.g., depth_anything_3.configs.giant). + """ + # Check if path is a module path (contains dots but no slashes and doesn't end with .yaml) + if "." in path and "/" not in path and not path.endswith(".yaml"): + # It's a module path, load from package resources + path_parts = path.split(".")[1:] + config_path = Path(__file__).resolve().parent + for part in path_parts: + config_path = config_path.joinpath(part) + config_path = config_path.with_suffix(".yaml") + config = OmegaConf.load(str(config_path)) + else: + # It's a file path (absolute, relative, or with .yaml extension) + config = OmegaConf.load(path) + + if argv is not None: + config_argv = OmegaConf.from_dotlist(argv) + config = OmegaConf.merge(config, config_argv) + config = resolve_recursive(config, resolve_inheritance) + return config + + +def resolve_recursive( + config: Any, + resolver: Callable[[Union[DictConfig, ListConfig]], Union[DictConfig, ListConfig]], +) -> Any: + config = resolver(config) + if isinstance(config, DictConfig): + for k in config.keys(): + v = config.get(k) + if isinstance(v, (DictConfig, ListConfig)): + config[k] = resolve_recursive(v, resolver) + if isinstance(config, ListConfig): + for i in range(len(config)): + v = config.get(i) + if isinstance(v, (DictConfig, ListConfig)): + config[i] = resolve_recursive(v, resolver) + return config + + +def resolve_inheritance(config: Union[DictConfig, ListConfig]) -> Any: + """ + Recursively resolve inheritance if the config contains: + __inherit__: path/to/parent.yaml or a ListConfig of such paths. + """ + if isinstance(config, DictConfig): + inherit = config.pop("__inherit__", None) + + if inherit: + inherit_list = inherit if isinstance(inherit, ListConfig) else [inherit] + + parent_config = None + for parent_path in inherit_list: + assert isinstance(parent_path, str) + parent_config = ( + load_config(parent_path) + if parent_config is None + else OmegaConf.merge(parent_config, load_config(parent_path)) + ) + + if len(config.keys()) > 0: + config = OmegaConf.merge(parent_config, config) + else: + config = parent_config + return config + + +def import_item(path: str, name: str) -> Any: + """ + Import a python item. Example: import_item("path.to.file", "MyClass") -> MyClass + """ + return getattr(importlib.import_module(path), name) + + +def create_object(config: DictConfig) -> Any: + """ + Create an object from config. + The config is expected to contains the following: + __object__: + path: path.to.module + name: MyClass + args: as_config | as_params (default to as_config) + """ + config = DictConfig(config) + item = import_item( + path=config.__object__.path, + name=config.__object__.name, + ) + args = config.__object__.get("args", "as_config") + if args == "as_config": + return item(config) + if args == "as_params": + config = OmegaConf.to_object(config) + config.pop("__object__") + return item(**config) + raise NotImplementedError(f"Unknown args type: {args}") + + +def create_dataset(path: str, *args, **kwargs) -> Any: + """ + Create a dataset. Requires the file to contain a "create_dataset" function. + """ + return import_item(path, "create_dataset")(*args, **kwargs) + + +def to_dict_recursive(config_obj): + if isinstance(config_obj, DictConfig): + return {k: to_dict_recursive(v) for k, v in config_obj.items()} + elif isinstance(config_obj, ListConfig): + return [to_dict_recursive(item) for item in config_obj] + return config_obj diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/cli.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..c9463028f1df7246dc8c3341e5c28b943289603b --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/cli.py @@ -0,0 +1,803 @@ +# flake8: noqa: E402 +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +Refactored Depth Anything 3 CLI +Clean, modular command-line interface +""" + +from __future__ import annotations + +import os +import typer + +from depth_anything_3.services import start_server +from depth_anything_3.services.gallery import gallery as gallery_main +from depth_anything_3.services.inference_service import run_inference +from depth_anything_3.services.input_handlers import ( + ColmapHandler, + ImageHandler, + ImagesHandler, + InputHandler, + VideoHandler, + parse_export_feat, +) +from depth_anything_3.utils.constants import ( + DEFAULT_EXPORT_DIR, + DEFAULT_GALLERY_DIR, + DEFAULT_GRADIO_DIR, + DEFAULT_MODEL, +) + +os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True" + +app = typer.Typer(help="Depth Anything 3 - Video depth estimation CLI", add_completion=False) + + +# ============================================================================ +# Input type detection utilities +# ============================================================================ + +# Supported file extensions +IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".webp", ".bmp", ".tiff", ".tif"} +VIDEO_EXTENSIONS = {".mp4", ".avi", ".mov", ".mkv", ".flv", ".wmv", ".webm", ".m4v"} + + +def detect_input_type(input_path: str) -> str: + """ + Detect input type from path. + + Returns: + - "image": Single image file + - "images": Directory containing images + - "video": Video file + - "colmap": COLMAP directory structure + - "unknown": Cannot determine type + """ + if not os.path.exists(input_path): + return "unknown" + + # Check if it's a file + if os.path.isfile(input_path): + ext = os.path.splitext(input_path)[1].lower() + if ext in IMAGE_EXTENSIONS: + return "image" + elif ext in VIDEO_EXTENSIONS: + return "video" + return "unknown" + + # Check if it's a directory + if os.path.isdir(input_path): + # Check for COLMAP structure + images_dir = os.path.join(input_path, "images") + sparse_dir = os.path.join(input_path, "sparse") + + if os.path.isdir(images_dir) and os.path.isdir(sparse_dir): + return "colmap" + + # Check if directory contains image files + for item in os.listdir(input_path): + item_path = os.path.join(input_path, item) + if os.path.isfile(item_path): + ext = os.path.splitext(item)[1].lower() + if ext in IMAGE_EXTENSIONS: + return "images" + + return "unknown" + + return "unknown" + + +# ============================================================================ +# Common parameters and configuration +# ============================================================================ + +# ============================================================================ +# Inference commands +# ============================================================================ + + +@app.command() +def auto( + input_path: str = typer.Argument( + ..., help="Path to input (image, directory, video, or COLMAP)" + ), + model_dir: str = typer.Option(DEFAULT_MODEL, help="Model directory path"), + export_dir: str = typer.Option(DEFAULT_EXPORT_DIR, help="Export directory"), + export_format: str = typer.Option("glb", help="Export format"), + device: str = typer.Option("cuda", help="Device to use"), + use_backend: bool = typer.Option(False, help="Use backend service for inference"), + backend_url: str = typer.Option( + "http://localhost:8008", help="Backend URL (default: http://localhost:8008)" + ), + process_res: int = typer.Option(504, help="Processing resolution"), + process_res_method: str = typer.Option( + "upper_bound_resize", help="Processing resolution method" + ), + export_feat: str = typer.Option( + "", + help="[FEAT_VIS]Export features from specified layers using comma-separated indices (e.g., '0,1,2').", + ), + auto_cleanup: bool = typer.Option( + False, help="Automatically clean export directory if it exists (no prompt)" + ), + # Video-specific options + fps: float = typer.Option(1.0, help="[Video] Sampling FPS for frame extraction"), + # COLMAP-specific options + sparse_subdir: str = typer.Option( + "", help="[COLMAP] Sparse reconstruction subdirectory (e.g., '0' for sparse/0/)" + ), + align_to_input_ext_scale: bool = typer.Option( + True, help="[COLMAP] Align prediction to input extrinsics scale" + ), + # Pose estimation options + use_ray_pose: bool = typer.Option( + False, help="Use ray-based pose estimation instead of camera decoder" + ), + ref_view_strategy: str = typer.Option( + "saddle_balanced", + help="Reference view selection strategy: empty, first, middle, saddle_balanced, saddle_sim_range", + ), + # GLB export options + conf_thresh_percentile: float = typer.Option( + 40.0, help="[GLB] Lower percentile for adaptive confidence threshold" + ), + num_max_points: int = typer.Option( + 1_000_000, help="[GLB] Maximum number of points in the point cloud" + ), + show_cameras: bool = typer.Option( + True, help="[GLB] Show camera wireframes in the exported scene" + ), + # Feat_vis export options + feat_vis_fps: int = typer.Option(15, help="[FEAT_VIS] Frame rate for output video"), +): + """ + Automatically detect input type and run appropriate processing. + + Supports: + - Single image file (.jpg, .png, etc.) + - Directory of images + - Video file (.mp4, .avi, etc.) + - COLMAP directory (with 'images' and 'sparse' subdirectories) + """ + # Detect input type + input_type = detect_input_type(input_path) + + if input_type == "unknown": + typer.echo(f"❌ Error: Cannot determine input type for: {input_path}", err=True) + typer.echo("Supported inputs:", err=True) + typer.echo(" - Single image file (.jpg, .png, etc.)", err=True) + typer.echo(" - Directory containing images", err=True) + typer.echo(" - Video file (.mp4, .avi, etc.)", err=True) + typer.echo(" - COLMAP directory (with 'images/' and 'sparse/' subdirectories)", err=True) + raise typer.Exit(1) + + # Display detected type + typer.echo(f"🔍 Detected input type: {input_type.upper()}") + typer.echo(f"📁 Input path: {input_path}") + typer.echo() + + # Determine backend URL based on use_backend flag + final_backend_url = backend_url if use_backend else None + + # Parse export_feat parameter + export_feat_layers = parse_export_feat(export_feat) + + # Route to appropriate handler + if input_type == "image": + typer.echo("Processing single image...") + # Process input + image_files = ImageHandler.process(input_path) + + # Handle export directory + export_dir = InputHandler.handle_export_dir(export_dir, auto_cleanup) + + # Run inference + run_inference( + image_paths=image_files, + export_dir=export_dir, + model_dir=model_dir, + device=device, + backend_url=final_backend_url, + export_format=export_format, + process_res=process_res, + process_res_method=process_res_method, + export_feat_layers=export_feat_layers, + use_ray_pose=use_ray_pose, + ref_view_strategy=ref_view_strategy, + conf_thresh_percentile=conf_thresh_percentile, + num_max_points=num_max_points, + show_cameras=show_cameras, + feat_vis_fps=feat_vis_fps, + ) + + elif input_type == "images": + typer.echo("Processing directory of images...") + # Process input - use default extensions + image_files = ImagesHandler.process(input_path, "png,jpg,jpeg") + + # Handle export directory + export_dir = InputHandler.handle_export_dir(export_dir, auto_cleanup) + + # Run inference + run_inference( + image_paths=image_files, + export_dir=export_dir, + model_dir=model_dir, + device=device, + backend_url=final_backend_url, + export_format=export_format, + process_res=process_res, + process_res_method=process_res_method, + export_feat_layers=export_feat_layers, + use_ray_pose=use_ray_pose, + ref_view_strategy=ref_view_strategy, + conf_thresh_percentile=conf_thresh_percentile, + num_max_points=num_max_points, + show_cameras=show_cameras, + feat_vis_fps=feat_vis_fps, + ) + + elif input_type == "video": + typer.echo(f"Processing video with FPS={fps}...") + # Handle export directory + export_dir = InputHandler.handle_export_dir(export_dir, auto_cleanup) + + # Process input + image_files = VideoHandler.process(input_path, export_dir, fps) + + # Run inference + run_inference( + image_paths=image_files, + export_dir=export_dir, + model_dir=model_dir, + device=device, + backend_url=final_backend_url, + export_format=export_format, + process_res=process_res, + process_res_method=process_res_method, + export_feat_layers=export_feat_layers, + use_ray_pose=use_ray_pose, + ref_view_strategy=ref_view_strategy, + conf_thresh_percentile=conf_thresh_percentile, + num_max_points=num_max_points, + show_cameras=show_cameras, + feat_vis_fps=feat_vis_fps, + ) + + elif input_type == "colmap": + typer.echo( + f"Processing COLMAP directory (sparse subdirectory: '{sparse_subdir or 'default'}')..." + ) + # Process input + image_files, extrinsics, intrinsics = ColmapHandler.process(input_path, sparse_subdir) + + # Handle export directory + export_dir = InputHandler.handle_export_dir(export_dir, auto_cleanup) + + # Run inference + run_inference( + image_paths=image_files, + export_dir=export_dir, + model_dir=model_dir, + device=device, + backend_url=final_backend_url, + export_format=export_format, + process_res=process_res, + process_res_method=process_res_method, + export_feat_layers=export_feat_layers, + extrinsics=extrinsics, + intrinsics=intrinsics, + align_to_input_ext_scale=align_to_input_ext_scale, + use_ray_pose=use_ray_pose, + ref_view_strategy=ref_view_strategy, + conf_thresh_percentile=conf_thresh_percentile, + num_max_points=num_max_points, + show_cameras=show_cameras, + feat_vis_fps=feat_vis_fps, + ) + + typer.echo() + typer.echo("✅ Processing completed successfully!") + + +@app.command() +def image( + image_path: str = typer.Argument(..., help="Path to input image file"), + model_dir: str = typer.Option(DEFAULT_MODEL, help="Model directory path"), + export_dir: str = typer.Option(DEFAULT_EXPORT_DIR, help="Export directory"), + export_format: str = typer.Option("glb", help="Export format"), + device: str = typer.Option("cuda", help="Device to use"), + use_backend: bool = typer.Option(False, help="Use backend service for inference"), + backend_url: str = typer.Option( + "http://localhost:8008", help="Backend URL (default: http://localhost:8008)" + ), + process_res: int = typer.Option(504, help="Processing resolution"), + process_res_method: str = typer.Option( + "upper_bound_resize", help="Processing resolution method" + ), + export_feat: str = typer.Option( + "", + help="[FEAT_VIS] Export features from specified layers using comma-separated indices (e.g., '0,1,2').", + ), + auto_cleanup: bool = typer.Option( + False, help="Automatically clean export directory if it exists (no prompt)" + ), + # Pose estimation options + use_ray_pose: bool = typer.Option( + False, help="Use ray-based pose estimation instead of camera decoder" + ), + ref_view_strategy: str = typer.Option( + "saddle_balanced", + help="Reference view selection strategy: empty, first, middle, saddle_balanced, saddle_sim_range", + ), + # GLB export options + conf_thresh_percentile: float = typer.Option( + 40.0, help="[GLB] Lower percentile for adaptive confidence threshold" + ), + num_max_points: int = typer.Option( + 1_000_000, help="[GLB] Maximum number of points in the point cloud" + ), + show_cameras: bool = typer.Option( + True, help="[GLB] Show camera wireframes in the exported scene" + ), + # Feat_vis export options + feat_vis_fps: int = typer.Option(15, help="[FEAT_VIS] Frame rate for output video"), +): + """Run camera pose and depth estimation on a single image.""" + # Process input + image_files = ImageHandler.process(image_path) + + # Handle export directory + export_dir = InputHandler.handle_export_dir(export_dir, auto_cleanup) + + # Parse export_feat parameter + export_feat_layers = parse_export_feat(export_feat) + + # Determine backend URL based on use_backend flag + final_backend_url = backend_url if use_backend else None + + # Run inference + run_inference( + image_paths=image_files, + export_dir=export_dir, + model_dir=model_dir, + device=device, + backend_url=final_backend_url, + export_format=export_format, + process_res=process_res, + process_res_method=process_res_method, + export_feat_layers=export_feat_layers, + use_ray_pose=use_ray_pose, + reference_view_strategy=reference_view_strategy, + conf_thresh_percentile=conf_thresh_percentile, + num_max_points=num_max_points, + show_cameras=show_cameras, + feat_vis_fps=feat_vis_fps, + ) + + +@app.command() +def images( + images_dir: str = typer.Argument(..., help="Path to directory containing input images"), + image_extensions: str = typer.Option( + "png,jpg,jpeg", help="Comma-separated image file extensions to process" + ), + model_dir: str = typer.Option(DEFAULT_MODEL, help="Model directory path"), + export_dir: str = typer.Option(DEFAULT_EXPORT_DIR, help="Export directory"), + export_format: str = typer.Option("glb", help="Export format"), + device: str = typer.Option("cuda", help="Device to use"), + use_backend: bool = typer.Option(False, help="Use backend service for inference"), + backend_url: str = typer.Option( + "http://localhost:8008", help="Backend URL (default: http://localhost:8008)" + ), + process_res: int = typer.Option(504, help="Processing resolution"), + process_res_method: str = typer.Option( + "upper_bound_resize", help="Processing resolution method" + ), + export_feat: str = typer.Option( + "", + help="[FEAT_VIS] Export features from specified layers using comma-separated indices (e.g., '0,1,2').", + ), + auto_cleanup: bool = typer.Option( + False, help="Automatically clean export directory if it exists (no prompt)" + ), + # Pose estimation options + use_ray_pose: bool = typer.Option( + False, help="Use ray-based pose estimation instead of camera decoder" + ), + ref_view_strategy: str = typer.Option( + "saddle_balanced", + help="Reference view selection strategy: empty, first, middle, saddle_balanced, saddle_sim_range", + ), + # GLB export options + conf_thresh_percentile: float = typer.Option( + 40.0, help="[GLB] Lower percentile for adaptive confidence threshold" + ), + num_max_points: int = typer.Option( + 1_000_000, help="[GLB] Maximum number of points in the point cloud" + ), + show_cameras: bool = typer.Option( + True, help="[GLB] Show camera wireframes in the exported scene" + ), + # Feat_vis export options + feat_vis_fps: int = typer.Option(15, help="[FEAT_VIS] Frame rate for output video"), +): + """Run camera pose and depth estimation on a directory of images.""" + # Process input + image_files = ImagesHandler.process(images_dir, image_extensions) + + # Handle export directory + export_dir = InputHandler.handle_export_dir(export_dir, auto_cleanup) + + # Parse export_feat parameter + export_feat_layers = parse_export_feat(export_feat) + + # Determine backend URL based on use_backend flag + final_backend_url = backend_url if use_backend else None + + # Run inference + run_inference( + image_paths=image_files, + export_dir=export_dir, + model_dir=model_dir, + device=device, + backend_url=final_backend_url, + export_format=export_format, + process_res=process_res, + process_res_method=process_res_method, + export_feat_layers=export_feat_layers, + use_ray_pose=use_ray_pose, + reference_view_strategy=reference_view_strategy, + conf_thresh_percentile=conf_thresh_percentile, + num_max_points=num_max_points, + show_cameras=show_cameras, + feat_vis_fps=feat_vis_fps, + ) + + +@app.command() +def colmap( + colmap_dir: str = typer.Argument( + ..., help="Path to COLMAP directory containing 'images' and 'sparse' subdirectories" + ), + sparse_subdir: str = typer.Option( + "", help="Sparse reconstruction subdirectory (e.g., '0' for sparse/0/, empty for sparse/)" + ), + align_to_input_ext_scale: bool = typer.Option( + True, help="Align prediction to input extrinsics scale" + ), + model_dir: str = typer.Option(DEFAULT_MODEL, help="Model directory path"), + export_dir: str = typer.Option(DEFAULT_EXPORT_DIR, help="Export directory"), + export_format: str = typer.Option("glb", help="Export format"), + device: str = typer.Option("cuda", help="Device to use"), + use_backend: bool = typer.Option(False, help="Use backend service for inference"), + backend_url: str = typer.Option( + "http://localhost:8008", help="Backend URL (default: http://localhost:8008)" + ), + process_res: int = typer.Option(504, help="Processing resolution"), + process_res_method: str = typer.Option( + "upper_bound_resize", help="Processing resolution method" + ), + export_feat: str = typer.Option( + "", + help="Export features from specified layers using comma-separated indices (e.g., '0,1,2').", + ), + auto_cleanup: bool = typer.Option( + False, help="Automatically clean export directory if it exists (no prompt)" + ), + # Pose estimation options + use_ray_pose: bool = typer.Option( + False, help="Use ray-based pose estimation instead of camera decoder" + ), + ref_view_strategy: str = typer.Option( + "saddle_balanced", + help="Reference view selection strategy: empty, first, middle, saddle_balanced, saddle_sim_range", + ), + # GLB export options + conf_thresh_percentile: float = typer.Option( + 40.0, help="[GLB] Lower percentile for adaptive confidence threshold" + ), + num_max_points: int = typer.Option( + 1_000_000, help="[GLB] Maximum number of points in the point cloud" + ), + show_cameras: bool = typer.Option( + True, help="[GLB] Show camera wireframes in the exported scene" + ), + # Feat_vis export options + feat_vis_fps: int = typer.Option(15, help="[FEAT_VIS] Frame rate for output video"), +): + """Run pose conditioned depth estimation on COLMAP data.""" + # Process input + image_files, extrinsics, intrinsics = ColmapHandler.process(colmap_dir, sparse_subdir) + + # Handle export directory + export_dir = InputHandler.handle_export_dir(export_dir, auto_cleanup) + + # Parse export_feat parameter + export_feat_layers = parse_export_feat(export_feat) + + # Determine backend URL based on use_backend flag + final_backend_url = backend_url if use_backend else None + + # Run inference + run_inference( + image_paths=image_files, + export_dir=export_dir, + model_dir=model_dir, + device=device, + backend_url=final_backend_url, + export_format=export_format, + process_res=process_res, + process_res_method=process_res_method, + export_feat_layers=export_feat_layers, + extrinsics=extrinsics, + intrinsics=intrinsics, + align_to_input_ext_scale=align_to_input_ext_scale, + use_ray_pose=use_ray_pose, + reference_view_strategy=reference_view_strategy, + conf_thresh_percentile=conf_thresh_percentile, + num_max_points=num_max_points, + show_cameras=show_cameras, + feat_vis_fps=feat_vis_fps, + ) + + +@app.command() +def video( + video_path: str = typer.Argument(..., help="Path to input video file"), + fps: float = typer.Option(1.0, help="Sampling FPS for frame extraction"), + model_dir: str = typer.Option(DEFAULT_MODEL, help="Model directory path"), + export_dir: str = typer.Option(DEFAULT_EXPORT_DIR, help="Export directory"), + export_format: str = typer.Option("glb", help="Export format"), + device: str = typer.Option("cuda", help="Device to use"), + use_backend: bool = typer.Option(False, help="Use backend service for inference"), + backend_url: str = typer.Option( + "http://localhost:8008", help="Backend URL (default: http://localhost:8008)" + ), + process_res: int = typer.Option(504, help="Processing resolution"), + process_res_method: str = typer.Option( + "upper_bound_resize", help="Processing resolution method" + ), + export_feat: str = typer.Option( + "", + help="[FEAT_VIS] Export features from specified layers using comma-separated indices (e.g., '0,1,2').", + ), + auto_cleanup: bool = typer.Option( + False, help="Automatically clean export directory if it exists (no prompt)" + ), + # Pose estimation options + use_ray_pose: bool = typer.Option( + False, help="Use ray-based pose estimation instead of camera decoder" + ), + ref_view_strategy: str = typer.Option( + "saddle_balanced", + help="Reference view selection strategy: empty, first, middle, saddle_balanced, saddle_sim_range", + ), + # GLB export options + conf_thresh_percentile: float = typer.Option( + 40.0, help="[GLB] Lower percentile for adaptive confidence threshold" + ), + num_max_points: int = typer.Option( + 1_000_000, help="[GLB] Maximum number of points in the point cloud" + ), + show_cameras: bool = typer.Option( + True, help="[GLB] Show camera wireframes in the exported scene" + ), + # Feat_vis export options + feat_vis_fps: int = typer.Option(15, help="[FEAT_VIS] Frame rate for output video"), +): + """Run depth estimation on video by extracting frames and processing them.""" + # Handle export directory + export_dir = InputHandler.handle_export_dir(export_dir, auto_cleanup) + + # Process input + image_files = VideoHandler.process(video_path, export_dir, fps) + + # Parse export_feat parameter + export_feat_layers = parse_export_feat(export_feat) + + # Determine backend URL based on use_backend flag + final_backend_url = backend_url if use_backend else None + + # Run inference + run_inference( + image_paths=image_files, + export_dir=export_dir, + model_dir=model_dir, + device=device, + backend_url=final_backend_url, + export_format=export_format, + process_res=process_res, + process_res_method=process_res_method, + export_feat_layers=export_feat_layers, + use_ray_pose=use_ray_pose, + reference_view_strategy=reference_view_strategy, + conf_thresh_percentile=conf_thresh_percentile, + num_max_points=num_max_points, + show_cameras=show_cameras, + feat_vis_fps=feat_vis_fps, + ) + + +# ============================================================================ +# Service management commands +# ============================================================================ + + +@app.command() +def backend( + model_dir: str = typer.Option(DEFAULT_MODEL, help="Model directory path"), + device: str = typer.Option("cuda", help="Device to use"), + host: str = typer.Option("127.0.0.1", help="Host to bind to"), + port: int = typer.Option(8008, help="Port to bind to"), + gallery_dir: str = typer.Option(DEFAULT_GALLERY_DIR, help="Gallery directory path (optional)"), +): + """Start model backend service with integrated gallery.""" + typer.echo("=" * 60) + typer.echo("🚀 Starting Depth Anything 3 Backend Server") + typer.echo("=" * 60) + typer.echo(f"Model directory: {model_dir}") + typer.echo(f"Device: {device}") + + # Check if gallery directory exists + if gallery_dir and os.path.exists(gallery_dir): + typer.echo(f"Gallery directory: {gallery_dir}") + else: + gallery_dir = None # Disable gallery if directory doesn't exist + + typer.echo() + typer.echo("📡 Server URLs (Ctrl/CMD+Click to open):") + typer.echo(f" 🏠 Home: http://{host}:{port}") + typer.echo(f" 📊 Dashboard: http://{host}:{port}/dashboard") + typer.echo(f" 📈 API Status: http://{host}:{port}/status") + + if gallery_dir: + typer.echo(f" 🎨 Gallery: http://{host}:{port}/gallery/") + + typer.echo("=" * 60) + + try: + start_server(model_dir, device, host, port, gallery_dir) + except KeyboardInterrupt: + typer.echo("\n👋 Backend server stopped.") + except Exception as e: + typer.echo(f"❌ Failed to start backend: {e}") + raise typer.Exit(1) + + +# ============================================================================ +# Application launch commands +# ============================================================================ + + +@app.command() +def gradio( + model_dir: str = typer.Option(DEFAULT_MODEL, help="Model directory path"), + workspace_dir: str = typer.Option(DEFAULT_GRADIO_DIR, help="Workspace directory path"), + gallery_dir: str = typer.Option(DEFAULT_GALLERY_DIR, help="Gallery directory path"), + host: str = typer.Option("127.0.0.1", help="Host address to bind to"), + port: int = typer.Option(7860, help="Port number to bind to"), + share: bool = typer.Option(False, help="Create a public link for the app"), + debug: bool = typer.Option(False, help="Enable debug mode"), + cache_examples: bool = typer.Option( + False, help="Pre-cache all example scenes at startup for faster loading" + ), + cache_gs_tag: str = typer.Option( + "", + help="Tag to match scene names for high-res+3DGS caching (e.g., 'dl3dv'). Scenes containing this tag will use high_res and infer_gs=True; others will use low_res only.", + ), +): + """Launch Depth Anything 3 Gradio interactive web application""" + from depth_anything_3.app.gradio_app import DepthAnything3App + + # Create necessary directories + os.makedirs(workspace_dir, exist_ok=True) + os.makedirs(gallery_dir, exist_ok=True) + + typer.echo("Launching Depth Anything 3 Gradio application...") + typer.echo(f"Model directory: {model_dir}") + typer.echo(f"Workspace directory: {workspace_dir}") + typer.echo(f"Gallery directory: {gallery_dir}") + typer.echo(f"Host: {host}") + typer.echo(f"Port: {port}") + typer.echo(f"Share: {share}") + typer.echo(f"Debug mode: {debug}") + typer.echo(f"Cache examples: {cache_examples}") + if cache_examples: + if cache_gs_tag: + typer.echo( + f"Cache GS Tag: '{cache_gs_tag}' (scenes matching this tag will use high-res + 3DGS)" + ) + else: + typer.echo(f"Cache GS Tag: None (all scenes will use low-res only)") + + try: + # Initialize and launch application + app = DepthAnything3App( + model_dir=model_dir, workspace_dir=workspace_dir, gallery_dir=gallery_dir + ) + + # Pre-cache examples if requested + if cache_examples: + typer.echo("\n" + "=" * 60) + typer.echo("Pre-caching mode enabled") + if cache_gs_tag: + typer.echo(f"Scenes containing '{cache_gs_tag}' will use HIGH-RES + 3DGS") + typer.echo(f"Other scenes will use LOW-RES only") + else: + typer.echo(f"All scenes will use LOW-RES only") + typer.echo("=" * 60) + app.cache_examples( + show_cam=True, + filter_black_bg=False, + filter_white_bg=False, + save_percentage=20.0, + num_max_points=1000, + cache_gs_tag=cache_gs_tag, + gs_trj_mode="smooth", + gs_video_quality="low", + ) + + # Prepare launch arguments + launch_kwargs = {"share": share, "debug": debug} + + app.launch(host=host, port=port, **launch_kwargs) + + except KeyboardInterrupt: + typer.echo("\nGradio application stopped.") + except Exception as e: + typer.echo(f"Failed to launch Gradio application: {e}") + raise typer.Exit(1) + + +@app.command() +def gallery( + gallery_dir: str = typer.Option(DEFAULT_GALLERY_DIR, help="Gallery root directory"), + host: str = typer.Option("127.0.0.1", help="Host address to bind to"), + port: int = typer.Option(8007, help="Port number to bind to"), + open_browser: bool = typer.Option(False, help="Open browser after launch"), +): + """Launch Depth Anything 3 Gallery server""" + + # Validate gallery directory + if not os.path.exists(gallery_dir): + raise typer.BadParameter(f"Gallery directory not found: {gallery_dir}") + + typer.echo("Launching Depth Anything 3 Gallery server...") + typer.echo(f"Gallery directory: {gallery_dir}") + typer.echo(f"Host: {host}") + typer.echo(f"Port: {port}") + typer.echo(f"Auto-open browser: {open_browser}") + + try: + # Set command line arguments + import sys + + sys.argv = ["gallery", "--dir", gallery_dir, "--host", host, "--port", str(port)] + if open_browser: + sys.argv.append("--open") + + # Launch gallery server + gallery_main() + + except KeyboardInterrupt: + typer.echo("\nGallery server stopped.") + except Exception as e: + typer.echo(f"Failed to launch Gallery server: {e}") + raise typer.Exit(1) + + +if __name__ == "__main__": + app() diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/configs/da3-base.yaml b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/configs/da3-base.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c52a7e5018388a174841469f9a94dc995e14f220 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/configs/da3-base.yaml @@ -0,0 +1,45 @@ +__object__: + path: depth_anything_3.model.da3 + name: DepthAnything3Net + args: as_params + +net: + __object__: + path: depth_anything_3.model.dinov2.dinov2 + name: DinoV2 + args: as_params + + name: vitb + out_layers: [5, 7, 9, 11] + alt_start: 4 + qknorm_start: 4 + rope_start: 4 + cat_token: True + +head: + __object__: + path: depth_anything_3.model.dualdpt + name: DualDPT + args: as_params + + dim_in: &head_dim_in 1536 + output_dim: 2 + features: &head_features 128 + out_channels: &head_out_channels [96, 192, 384, 768] + + +cam_enc: + __object__: + path: depth_anything_3.model.cam_enc + name: CameraEnc + args: as_params + + dim_out: 768 + +cam_dec: + __object__: + path: depth_anything_3.model.cam_dec + name: CameraDec + args: as_params + + dim_in: 1536 diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/configs/da3-giant.yaml b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/configs/da3-giant.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f5a75c043353aa3e5b7c5368e4b26416c2b0b8b0 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/configs/da3-giant.yaml @@ -0,0 +1,71 @@ +__object__: + path: depth_anything_3.model.da3 + name: DepthAnything3Net + args: as_params + +net: + __object__: + path: depth_anything_3.model.dinov2.dinov2 + name: DinoV2 + args: as_params + + name: vitg + out_layers: [19, 27, 33, 39] + alt_start: 13 + qknorm_start: 13 + rope_start: 13 + cat_token: True + +head: + __object__: + path: depth_anything_3.model.dualdpt + name: DualDPT + args: as_params + + dim_in: &head_dim_in 3072 + output_dim: 2 + features: &head_features 256 + out_channels: &head_out_channels [256, 512, 1024, 1024] + + +cam_enc: + __object__: + path: depth_anything_3.model.cam_enc + name: CameraEnc + args: as_params + + dim_out: 1536 + +cam_dec: + __object__: + path: depth_anything_3.model.cam_dec + name: CameraDec + args: as_params + + dim_in: 3072 + + +gs_head: + __object__: + path: depth_anything_3.model.gsdpt + name: GSDPT + args: as_params + + dim_in: *head_dim_in + output_dim: 38 # should align with gs_adapter's setting, for gs params + features: *head_features + out_channels: *head_out_channels + + +gs_adapter: + __object__: + path: depth_anything_3.model.gs_adapter + name: GaussianAdapter + args: as_params + + sh_degree: 2 + pred_color: false # predict SH coefficient if false + pred_offset_depth: true + pred_offset_xy: true + gaussian_scale_min: 1e-5 + gaussian_scale_max: 30.0 diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/configs/da3-large.yaml b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/configs/da3-large.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4fa367c9d9b46eb9a62aef7041f68c709eb4c6e3 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/configs/da3-large.yaml @@ -0,0 +1,45 @@ +__object__: + path: depth_anything_3.model.da3 + name: DepthAnything3Net + args: as_params + +net: + __object__: + path: depth_anything_3.model.dinov2.dinov2 + name: DinoV2 + args: as_params + + name: vitl + out_layers: [11, 15, 19, 23] + alt_start: 8 + qknorm_start: 8 + rope_start: 8 + cat_token: True + +head: + __object__: + path: depth_anything_3.model.dualdpt + name: DualDPT + args: as_params + + dim_in: &head_dim_in 2048 + output_dim: 2 + features: &head_features 256 + out_channels: &head_out_channels [256, 512, 1024, 1024] + + +cam_enc: + __object__: + path: depth_anything_3.model.cam_enc + name: CameraEnc + args: as_params + + dim_out: 1024 + +cam_dec: + __object__: + path: depth_anything_3.model.cam_dec + name: CameraDec + args: as_params + + dim_in: 2048 diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/configs/da3-small.yaml b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/configs/da3-small.yaml new file mode 100644 index 0000000000000000000000000000000000000000..10887437697fc9f2614c03add73fe9858b309d91 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/configs/da3-small.yaml @@ -0,0 +1,45 @@ +__object__: + path: depth_anything_3.model.da3 + name: DepthAnything3Net + args: as_params + +net: + __object__: + path: depth_anything_3.model.dinov2.dinov2 + name: DinoV2 + args: as_params + + name: vits + out_layers: [5, 7, 9, 11] + alt_start: 4 + qknorm_start: 4 + rope_start: 4 + cat_token: True + +head: + __object__: + path: depth_anything_3.model.dualdpt + name: DualDPT + args: as_params + + dim_in: &head_dim_in 768 + output_dim: 2 + features: &head_features 64 + out_channels: &head_out_channels [48, 96, 192, 384] + + +cam_enc: + __object__: + path: depth_anything_3.model.cam_enc + name: CameraEnc + args: as_params + + dim_out: 384 + +cam_dec: + __object__: + path: depth_anything_3.model.cam_dec + name: CameraDec + args: as_params + + dim_in: 768 diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/configs/da3metric-large.yaml b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/configs/da3metric-large.yaml new file mode 100644 index 0000000000000000000000000000000000000000..124635cfd952c25c8857ee3da63ce0444c4377f2 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/configs/da3metric-large.yaml @@ -0,0 +1,28 @@ +__object__: + path: depth_anything_3.model.da3 + name: DepthAnything3Net + args: as_params + +net: + __object__: + path: depth_anything_3.model.dinov2.dinov2 + name: DinoV2 + args: as_params + + name: vitl + out_layers: [4, 11, 17, 23] + alt_start: -1 # -1 means disable + qknorm_start: -1 + rope_start: -1 + cat_token: False + +head: + __object__: + path: depth_anything_3.model.dpt + name: DPT + args: as_params + + dim_in: 1024 + output_dim: 1 + features: 256 + out_channels: [256, 512, 1024, 1024] diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/configs/da3mono-large.yaml b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/configs/da3mono-large.yaml new file mode 100644 index 0000000000000000000000000000000000000000..124635cfd952c25c8857ee3da63ce0444c4377f2 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/configs/da3mono-large.yaml @@ -0,0 +1,28 @@ +__object__: + path: depth_anything_3.model.da3 + name: DepthAnything3Net + args: as_params + +net: + __object__: + path: depth_anything_3.model.dinov2.dinov2 + name: DinoV2 + args: as_params + + name: vitl + out_layers: [4, 11, 17, 23] + alt_start: -1 # -1 means disable + qknorm_start: -1 + rope_start: -1 + cat_token: False + +head: + __object__: + path: depth_anything_3.model.dpt + name: DPT + args: as_params + + dim_in: 1024 + output_dim: 1 + features: 256 + out_channels: [256, 512, 1024, 1024] diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/configs/da3nested-giant-large.yaml b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/configs/da3nested-giant-large.yaml new file mode 100644 index 0000000000000000000000000000000000000000..595c122b1dc976ecfec58b133b2b60d8f724618c --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/configs/da3nested-giant-large.yaml @@ -0,0 +1,10 @@ +__object__: + path: depth_anything_3.model.da3 + name: NestedDepthAnything3Net + args: as_params + +anyview: + __inherit__: depth_anything_3.configs.da3-giant + +metric: + __inherit__: depth_anything_3.configs.da3metric-large diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/__init__.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..57a2a45132eeae8d58a11a26036c54feef9cfe16 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/__init__.py @@ -0,0 +1,20 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from depth_anything_3.model.da3 import DepthAnything3Net, NestedDepthAnything3Net + +__export__ = [ + NestedDepthAnything3Net, + DepthAnything3Net, +] diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/cam_dec.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/cam_dec.py new file mode 100644 index 0000000000000000000000000000000000000000..3353b403683bf556b3823081863573dc7f5f719e --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/cam_dec.py @@ -0,0 +1,45 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import torch +import torch.nn as nn + + +class CameraDec(nn.Module): + def __init__(self, dim_in=1536): + super().__init__() + output_dim = dim_in + self.backbone = nn.Sequential( + nn.Linear(output_dim, output_dim), + nn.ReLU(), + nn.Linear(output_dim, output_dim), + nn.ReLU(), + ) + self.fc_t = nn.Linear(output_dim, 3) + self.fc_qvec = nn.Linear(output_dim, 4) + self.fc_fov = nn.Sequential(nn.Linear(output_dim, 2), nn.ReLU()) + + def forward(self, feat, camera_encoding=None, *args, **kwargs): + B, N = feat.shape[:2] + feat = feat.reshape(B * N, -1) + feat = self.backbone(feat) + out_t = self.fc_t(feat.float()).reshape(B, N, 3) + if camera_encoding is None: + out_qvec = self.fc_qvec(feat.float()).reshape(B, N, 4) + out_fov = self.fc_fov(feat.float()).reshape(B, N, 2) + else: + out_qvec = camera_encoding[..., 3:7] + out_fov = camera_encoding[..., -2:] + pose_enc = torch.cat([out_t, out_qvec, out_fov], dim=-1) + return pose_enc diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/cam_enc.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/cam_enc.py new file mode 100644 index 0000000000000000000000000000000000000000..bf28e701442fa73d89e54b409800908c138a93d8 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/cam_enc.py @@ -0,0 +1,80 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import torch.nn as nn + +from depth_anything_3.model.utils.attention import Mlp +from depth_anything_3.model.utils.block import Block +from depth_anything_3.model.utils.transform import extri_intri_to_pose_encoding +from depth_anything_3.utils.geometry import affine_inverse + + +class CameraEnc(nn.Module): + """ + CameraHead predicts camera parameters from token representations using iterative refinement. + + It applies a series of transformer blocks (the "trunk") to dedicated camera tokens. + """ + + def __init__( + self, + dim_out: int = 1024, + dim_in: int = 9, + trunk_depth: int = 4, + target_dim: int = 9, + num_heads: int = 16, + mlp_ratio: int = 4, + init_values: float = 0.01, + **kwargs, + ): + super().__init__() + self.target_dim = target_dim + self.trunk_depth = trunk_depth + self.trunk = nn.Sequential( + *[ + Block( + dim=dim_out, + num_heads=num_heads, + mlp_ratio=mlp_ratio, + init_values=init_values, + ) + for _ in range(trunk_depth) + ] + ) + self.token_norm = nn.LayerNorm(dim_out) + self.trunk_norm = nn.LayerNorm(dim_out) + self.pose_branch = Mlp( + in_features=dim_in, + hidden_features=dim_out // 2, + out_features=dim_out, + drop=0, + ) + + def forward( + self, + ext, + ixt, + image_size, + ) -> tuple: + c2ws = affine_inverse(ext) + pose_encoding = extri_intri_to_pose_encoding( + c2ws, + ixt, + image_size, + ) + pose_tokens = self.pose_branch(pose_encoding) + pose_tokens = self.token_norm(pose_tokens) + pose_tokens = self.trunk(pose_tokens) + pose_tokens = self.trunk_norm(pose_tokens) + return pose_tokens diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/da3.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/da3.py new file mode 100644 index 0000000000000000000000000000000000000000..f9e5bd683a8a697647da30e4d93a0ead03e9545d --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/da3.py @@ -0,0 +1,442 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import torch +import torch.nn as nn +from addict import Dict +from omegaconf import DictConfig, OmegaConf + +from depth_anything_3.cfg import create_object +from depth_anything_3.model.utils.transform import pose_encoding_to_extri_intri +from depth_anything_3.utils.alignment import ( + apply_metric_scaling, + compute_alignment_mask, + compute_sky_mask, + least_squares_scale_scalar, + sample_tensor_for_quantile, + set_sky_regions_to_max_depth, +) +from depth_anything_3.utils.geometry import affine_inverse, as_homogeneous, map_pdf_to_opacity +from depth_anything_3.utils.ray_utils import get_extrinsic_from_camray + + +def _wrap_cfg(cfg_obj): + return OmegaConf.create(cfg_obj) + + +class DepthAnything3Net(nn.Module): + """ + Depth Anything 3 network for depth estimation and camera pose estimation. + + This network consists of: + - Backbone: DinoV2 feature extractor + - Head: DPT or DualDPT for depth prediction + - Optional camera decoders for pose estimation + - Optional GSDPT for 3DGS prediction + + Args: + preset: Configuration preset containing network dimensions and settings + + Returns: + Dictionary containing: + - depth: Predicted depth map (B, H, W) + - depth_conf: Depth confidence map (B, H, W) + - extrinsics: Camera extrinsics (B, N, 4, 4) + - intrinsics: Camera intrinsics (B, N, 3, 3) + - gaussians: 3D Gaussian Splats (world space), type: model.gs_adapter.Gaussians + - aux: Auxiliary features for specified layers + """ + + # Patch size for feature extraction + PATCH_SIZE = 14 + + def __init__(self, net, head, cam_dec=None, cam_enc=None, gs_head=None, gs_adapter=None): + """ + Initialize DepthAnything3Net with given yaml-initialized configuration. + """ + super().__init__() + self.backbone = net if isinstance(net, nn.Module) else create_object(_wrap_cfg(net)) + self.head = head if isinstance(head, nn.Module) else create_object(_wrap_cfg(head)) + self.cam_dec, self.cam_enc = None, None + if cam_dec is not None: + self.cam_dec = ( + cam_dec if isinstance(cam_dec, nn.Module) else create_object(_wrap_cfg(cam_dec)) + ) + self.cam_enc = ( + cam_enc if isinstance(cam_enc, nn.Module) else create_object(_wrap_cfg(cam_enc)) + ) + self.gs_adapter, self.gs_head = None, None + if gs_head is not None and gs_adapter is not None: + self.gs_adapter = ( + gs_adapter + if isinstance(gs_adapter, nn.Module) + else create_object(_wrap_cfg(gs_adapter)) + ) + gs_out_dim = self.gs_adapter.d_in + 1 + if isinstance(gs_head, nn.Module): + assert ( + gs_head.out_dim == gs_out_dim + ), f"gs_head.out_dim should be {gs_out_dim}, got {gs_head.out_dim}" + self.gs_head = gs_head + else: + assert ( + gs_head["output_dim"] == gs_out_dim + ), f"gs_head output_dim should set to {gs_out_dim}, got {gs_head['output_dim']}" + self.gs_head = create_object(_wrap_cfg(gs_head)) + + def forward( + self, + x: torch.Tensor, + extrinsics: torch.Tensor | None = None, + intrinsics: torch.Tensor | None = None, + export_feat_layers: list[int] | None = [], + infer_gs: bool = False, + use_ray_pose: bool = False, + ref_view_strategy: str = "saddle_balanced", + ) -> Dict[str, torch.Tensor]: + """ + Forward pass through the network. + + Args: + x: Input images (B, N, 3, H, W) + extrinsics: Camera extrinsics (B, N, 4, 4) + intrinsics: Camera intrinsics (B, N, 3, 3) + feat_layers: List of layer indices to extract features from + infer_gs: Enable Gaussian Splatting branch + use_ray_pose: Use ray-based pose estimation + ref_view_strategy: Strategy for selecting reference view + + Returns: + Dictionary containing predictions and auxiliary features + """ + # Extract features using backbone + if extrinsics is not None: + with torch.autocast(device_type=x.device.type, enabled=False): + cam_token = self.cam_enc(extrinsics, intrinsics, x.shape[-2:]) + else: + cam_token = None + + feats, aux_feats = self.backbone( + x, cam_token=cam_token, export_feat_layers=export_feat_layers, ref_view_strategy=ref_view_strategy + ) + # feats = [[item for item in feat] for feat in feats] + H, W = x.shape[-2], x.shape[-1] + + # Process features through depth head + with torch.autocast(device_type=x.device.type, enabled=False): + output = self._process_depth_head(feats, H, W) + if use_ray_pose: + output = self._process_ray_pose_estimation(output, H, W) + else: + output = self._process_camera_estimation(feats, H, W, output) + if infer_gs: + output = self._process_gs_head(feats, H, W, output, x, extrinsics, intrinsics) + + output = self._process_mono_sky_estimation(output) + + # Extract auxiliary features if requested + output.aux = self._extract_auxiliary_features(aux_feats, export_feat_layers, H, W) + + return output + + def _process_mono_sky_estimation( + self, output: Dict[str, torch.Tensor] + ) -> Dict[str, torch.Tensor]: + """Process mono sky estimation.""" + if "sky" not in output: + return output + non_sky_mask = compute_sky_mask(output.sky, threshold=0.3) + if non_sky_mask.sum() <= 10: + return output + if (~non_sky_mask).sum() <= 10: + return output + + non_sky_depth = output.depth[non_sky_mask] + if non_sky_depth.numel() > 100000: + idx = torch.randint(0, non_sky_depth.numel(), (100000,), device=non_sky_depth.device) + sampled_depth = non_sky_depth[idx] + else: + sampled_depth = non_sky_depth + non_sky_max = torch.quantile(sampled_depth, 0.99) + + # Set sky regions to maximum depth and high confidence + output.depth, _ = set_sky_regions_to_max_depth( + output.depth, None, non_sky_mask, max_depth=non_sky_max + ) + return output + + def _process_ray_pose_estimation( + self, output: Dict[str, torch.Tensor], height: int, width: int + ) -> Dict[str, torch.Tensor]: + """Process ray pose estimation if ray pose decoder is available.""" + if "ray" in output and "ray_conf" in output: + pred_extrinsic, pred_focal_lengths, pred_principal_points = get_extrinsic_from_camray( + output.ray, + output.ray_conf, + output.ray.shape[-3], + output.ray.shape[-2], + ) + pred_extrinsic = affine_inverse(pred_extrinsic) # w2c -> c2w + pred_extrinsic = pred_extrinsic[:, :, :3, :] + pred_intrinsic = torch.eye(3, 3)[None, None].repeat(pred_extrinsic.shape[0], pred_extrinsic.shape[1], 1, 1).clone().to(pred_extrinsic.device) + pred_intrinsic[:, :, 0, 0] = pred_focal_lengths[:, :, 0] / 2 * width + pred_intrinsic[:, :, 1, 1] = pred_focal_lengths[:, :, 1] / 2 * height + pred_intrinsic[:, :, 0, 2] = pred_principal_points[:, :, 0] * width * 0.5 + pred_intrinsic[:, :, 1, 2] = pred_principal_points[:, :, 1] * height * 0.5 + del output.ray + del output.ray_conf + output.extrinsics = pred_extrinsic + output.intrinsics = pred_intrinsic + return output + + def _process_depth_head( + self, feats: list[torch.Tensor], H: int, W: int + ) -> Dict[str, torch.Tensor]: + """Process features through the depth prediction head.""" + return self.head(feats, H, W, patch_start_idx=0) + + def _process_camera_estimation( + self, feats: list[torch.Tensor], H: int, W: int, output: Dict[str, torch.Tensor] + ) -> Dict[str, torch.Tensor]: + """Process camera pose estimation if camera decoder is available.""" + if self.cam_dec is not None: + pose_enc = self.cam_dec(feats[-1][1]) + # Remove ray information as it's not needed for pose estimation + if "ray" in output: + del output.ray + if "ray_conf" in output: + del output.ray_conf + + # Convert pose encoding to extrinsics and intrinsics + c2w, ixt = pose_encoding_to_extri_intri(pose_enc, (H, W)) + output.extrinsics = affine_inverse(c2w) + output.intrinsics = ixt + + return output + + def _process_gs_head( + self, + feats: list[torch.Tensor], + H: int, + W: int, + output: Dict[str, torch.Tensor], + in_images: torch.Tensor, + extrinsics: torch.Tensor | None = None, + intrinsics: torch.Tensor | None = None, + ) -> Dict[str, torch.Tensor]: + """Process 3DGS parameters estimation if 3DGS head is available.""" + if self.gs_head is None or self.gs_adapter is None: + return output + assert output.get("depth", None) is not None, "must provide MV depth for the GS head." + + # The depth is defined in the DA3 model's camera space, + # so even with provided GT camera poses, + # we instead use the predicted camera poses for better alignment. + ctx_extr = output.get("extrinsics", None) + ctx_intr = output.get("intrinsics", None) + assert ( + ctx_extr is not None and ctx_intr is not None + ), "must process camera info first if GT is not available" + + gt_extr = extrinsics + # homo the extr if needed + ctx_extr = as_homogeneous(ctx_extr) + if gt_extr is not None: + gt_extr = as_homogeneous(gt_extr) + + # forward through the gs_dpt head to get 'camera space' parameters + gs_outs = self.gs_head( + feats=feats, + H=H, + W=W, + patch_start_idx=0, + images=in_images, + ) + raw_gaussians = gs_outs.raw_gs + densities = gs_outs.raw_gs_conf + + # convert to 'world space' 3DGS parameters; ready to export and render + # gt_extr could be None, and will be used to align the pose scale if available + gs_world = self.gs_adapter( + extrinsics=ctx_extr, + intrinsics=ctx_intr, + depths=output.depth, + opacities=map_pdf_to_opacity(densities), + raw_gaussians=raw_gaussians, + image_shape=(H, W), + gt_extrinsics=gt_extr, + ) + output.gaussians = gs_world + + return output + + def _extract_auxiliary_features( + self, feats: list[torch.Tensor], feat_layers: list[int], H: int, W: int + ) -> Dict[str, torch.Tensor]: + """Extract auxiliary features from specified layers.""" + aux_features = Dict() + assert len(feats) == len(feat_layers) + for feat, feat_layer in zip(feats, feat_layers): + # Reshape features to spatial dimensions + feat_reshaped = feat.reshape( + [ + feat.shape[0], + feat.shape[1], + H // self.PATCH_SIZE, + W // self.PATCH_SIZE, + feat.shape[-1], + ] + ) + aux_features[f"feat_layer_{feat_layer}"] = feat_reshaped + + return aux_features + + +class NestedDepthAnything3Net(nn.Module): + """ + Nested Depth Anything 3 network with metric scaling capabilities. + + This network combines two DepthAnything3Net branches: + - Main branch: Standard depth estimation + - Metric branch: Metric depth estimation for scaling alignment + + The network performs depth alignment using least squares scaling + and handles sky region masking for improved depth estimation. + + Args: + preset: Configuration for the main depth estimation branch + second_preset: Configuration for the metric depth branch + """ + + def __init__(self, anyview: DictConfig, metric: DictConfig): + """ + Initialize NestedDepthAnything3Net with two branches. + + Args: + preset: Configuration for main depth estimation branch + second_preset: Configuration for metric depth branch + """ + super().__init__() + self.da3 = create_object(anyview) + self.da3_metric = create_object(metric) + + def forward( + self, + x: torch.Tensor, + extrinsics: torch.Tensor | None = None, + intrinsics: torch.Tensor | None = None, + export_feat_layers: list[int] | None = [], + infer_gs: bool = False, + use_ray_pose: bool = False, + ref_view_strategy: str = "saddle_balanced", + ) -> Dict[str, torch.Tensor]: + """ + Forward pass through both branches with metric scaling alignment. + + Args: + x: Input images (B, N, 3, H, W) + extrinsics: Camera extrinsics (B, N, 4, 4) - unused + intrinsics: Camera intrinsics (B, N, 3, 3) - unused + feat_layers: List of layer indices to extract features from + infer_gs: Enable Gaussian Splatting branch + use_ray_pose: Use ray-based pose estimation + ref_view_strategy: Strategy for selecting reference view + + Returns: + Dictionary containing aligned depth predictions and camera parameters + """ + # Get predictions from both branches + output = self.da3( + x, extrinsics, intrinsics, export_feat_layers=export_feat_layers, infer_gs=infer_gs, use_ray_pose=use_ray_pose, ref_view_strategy=ref_view_strategy + ) + metric_output = self.da3_metric(x) + + # Apply metric scaling and alignment + output = self._apply_metric_scaling(output, metric_output) + output = self._apply_depth_alignment(output, metric_output) + output = self._handle_sky_regions(output, metric_output) + + return output + + def _apply_metric_scaling( + self, output: Dict[str, torch.Tensor], metric_output: Dict[str, torch.Tensor] + ) -> Dict[str, torch.Tensor]: + """Apply metric scaling to the metric depth output.""" + # Scale metric depth based on camera intrinsics + metric_output.depth = apply_metric_scaling( + metric_output.depth, + output.intrinsics, + ) + return output + + def _apply_depth_alignment( + self, output: Dict[str, torch.Tensor], metric_output: Dict[str, torch.Tensor] + ) -> Dict[str, torch.Tensor]: + """Apply depth alignment using least squares scaling.""" + # Compute non-sky mask + non_sky_mask = compute_sky_mask(metric_output.sky, threshold=0.3) + + # Ensure we have enough non-sky pixels + assert non_sky_mask.sum() > 10, "Insufficient non-sky pixels for alignment" + + # Sample depth confidence for quantile computation + depth_conf_ns = output.depth_conf[non_sky_mask] + depth_conf_sampled = sample_tensor_for_quantile(depth_conf_ns, max_samples=100000) + median_conf = torch.quantile(depth_conf_sampled, 0.5) + + # Compute alignment mask + align_mask = compute_alignment_mask( + output.depth_conf, non_sky_mask, output.depth, metric_output.depth, median_conf + ) + + # Compute scale factor using least squares + valid_depth = output.depth[align_mask] + valid_metric_depth = metric_output.depth[align_mask] + scale_factor = least_squares_scale_scalar(valid_metric_depth, valid_depth) + + # Apply scaling to depth and extrinsics + output.depth *= scale_factor + output.extrinsics[:, :, :3, 3] *= scale_factor + output.is_metric = 1 + output.scale_factor = scale_factor.item() + + return output + + def _handle_sky_regions( + self, + output: Dict[str, torch.Tensor], + metric_output: Dict[str, torch.Tensor], + sky_depth_def: float = 200.0, + ) -> Dict[str, torch.Tensor]: + """Handle sky regions by setting them to maximum depth.""" + non_sky_mask = compute_sky_mask(metric_output.sky, threshold=0.3) + + # Compute maximum depth for non-sky regions + # Use sampling to safely compute quantile on large tensors + non_sky_depth = output.depth[non_sky_mask] + if non_sky_depth.numel() > 100000: + idx = torch.randint(0, non_sky_depth.numel(), (100000,), device=non_sky_depth.device) + sampled_depth = non_sky_depth[idx] + else: + sampled_depth = non_sky_depth + non_sky_max = min(torch.quantile(sampled_depth, 0.99), sky_depth_def) + + # Set sky regions to maximum depth and high confidence + output.depth, output.depth_conf = set_sky_regions_to_max_depth( + output.depth, output.depth_conf, non_sky_mask, max_depth=non_sky_max + ) + + return output diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/dinov2/dinov2.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/dinov2/dinov2.py new file mode 100644 index 0000000000000000000000000000000000000000..ee0d88bdd6d33edda6c0fb237ee0c77ffc3f6034 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/dinov2/dinov2.py @@ -0,0 +1,64 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the Apache License, Version 2.0 +# found in the LICENSE file in the root directory of this source tree. + +# References: +# https://github.com/facebookresearch/dino/blob/main/vision_transformer.py +# https://github.com/rwightman/pytorch-image-models/tree/master/timm/models/vision_transformer.py + + +from typing import List +import torch.nn as nn + +from depth_anything_3.model.dinov2.vision_transformer import ( + vit_base, + vit_giant2, + vit_large, + vit_small, +) + + +class DinoV2(nn.Module): + def __init__( + self, + name: str, + out_layers: List[int], + alt_start: int = -1, + qknorm_start: int = -1, + rope_start: int = -1, + cat_token: bool = True, + **kwargs, + ): + super().__init__() + assert name in {"vits", "vitb", "vitl", "vitg"} + self.name = name + self.out_layers = out_layers + self.alt_start = alt_start + self.qknorm_start = qknorm_start + self.rope_start = rope_start + self.cat_token = cat_token + encoder_map = { + "vits": vit_small, + "vitb": vit_base, + "vitl": vit_large, + "vitg": vit_giant2, + } + encoder_fn = encoder_map[self.name] + ffn_layer = "swiglufused" if self.name == "vitg" else "mlp" + self.pretrained = encoder_fn( + img_size=518, + patch_size=14, + ffn_layer=ffn_layer, + alt_start=alt_start, + qknorm_start=qknorm_start, + rope_start=rope_start, + cat_token=cat_token, + ) + + def forward(self, x, **kwargs): + return self.pretrained.get_intermediate_layers( + x, + self.out_layers, + **kwargs, + ) diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/dinov2/layers/__init__.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/dinov2/layers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..97dfba90c12b2ffc5f0f1f823b6384c9b4cd6fa2 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/dinov2/layers/__init__.py @@ -0,0 +1,25 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +# from .attention import MemEffAttention +from .block import Block +from .layer_scale import LayerScale +from .mlp import Mlp +from .patch_embed import PatchEmbed +from .rope import PositionGetter, RotaryPositionEmbedding2D +from .swiglu_ffn import SwiGLUFFN, SwiGLUFFNFused + +__all__ = [ + Mlp, + PatchEmbed, + SwiGLUFFN, + SwiGLUFFNFused, + Block, + # MemEffAttention, + LayerScale, + PositionGetter, + RotaryPositionEmbedding2D, +] diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/dinov2/layers/attention.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/dinov2/layers/attention.py new file mode 100644 index 0000000000000000000000000000000000000000..096b9d41ddc95b9c4652597b18f53aee31a573b6 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/dinov2/layers/attention.py @@ -0,0 +1,100 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +# References: +# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py +# https://github.com/rwightman/pytorch-image-models/tree/master/timm/models/vision_transformer.py + +import logging +import torch.nn.functional as F +from torch import Tensor, nn + +logger = logging.getLogger("dinov2") + + +class Attention(nn.Module): + def __init__( + self, + dim: int, + num_heads: int = 8, + qkv_bias: bool = False, + proj_bias: bool = True, + attn_drop: float = 0.0, + proj_drop: float = 0.0, + norm_layer: nn.Module = nn.LayerNorm, + qk_norm: bool = False, + fused_attn: bool = True, # use F.scaled_dot_product_attention or not + rope=None, + ) -> None: + super().__init__() + assert dim % num_heads == 0, "dim should be divisible by num_heads" + self.num_heads = num_heads + head_dim = dim // num_heads + self.scale = head_dim**-0.5 + self.fused_attn = fused_attn + + self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) + self.q_norm = norm_layer(head_dim) if qk_norm else nn.Identity() + self.k_norm = norm_layer(head_dim) if qk_norm else nn.Identity() + self.attn_drop = nn.Dropout(attn_drop) + self.proj = nn.Linear(dim, dim, bias=proj_bias) + self.proj_drop = nn.Dropout(proj_drop) + self.rope = rope + + def forward(self, x: Tensor, pos=None, attn_mask=None) -> Tensor: + B, N, C = x.shape + qkv = ( + self.qkv(x) + .reshape(B, N, 3, self.num_heads, C // self.num_heads) + .permute(2, 0, 3, 1, 4) + ) + q, k, v = qkv[0], qkv[1], qkv[2] + q, k = self.q_norm(q), self.k_norm(k) + if self.rope is not None and pos is not None: + q = self.rope(q, pos) + k = self.rope(k, pos) + if self.fused_attn: + x = F.scaled_dot_product_attention( + q, + k, + v, + dropout_p=self.attn_drop.p if self.training else 0.0, + attn_mask=( + (attn_mask)[:, None].repeat(1, self.num_heads, 1, 1) + if attn_mask is not None + else None + ), + ) + else: + q = q * self.scale + attn = q @ k.transpose(-2, -1) + attn = attn.softmax(dim=-1) + attn = self.attn_drop(attn) + x = attn @ v + + x = x.transpose(1, 2).reshape(B, N, C) + x = self.proj(x) + x = self.proj_drop(x) + return x + + def _forward(self, x: Tensor) -> Tensor: + B, N, C = x.shape + qkv = ( + self.qkv(x) + .reshape(B, N, 3, self.num_heads, C // self.num_heads) + .permute(2, 0, 3, 1, 4) + ) + + q, k, v = qkv[0] * self.scale, qkv[1], qkv[2] + attn = q @ k.transpose(-2, -1) + + attn = attn.softmax(dim=-1) + attn = self.attn_drop(attn) + + x = (attn @ v).transpose(1, 2).reshape(B, N, C) + x = self.proj(x) + x = self.proj_drop(x) + return x diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/dinov2/layers/block.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/dinov2/layers/block.py new file mode 100644 index 0000000000000000000000000000000000000000..731519b68b16c8936b765dd1620fbb9c81087f96 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/dinov2/layers/block.py @@ -0,0 +1,143 @@ +# flake8: noqa: F821 +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +# References: +# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py +# https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/patch_embed.py + +import logging +from typing import Callable, Optional +import torch +from torch import Tensor, nn + +from .attention import Attention +from .drop_path import DropPath +from .layer_scale import LayerScale +from .mlp import Mlp + +logger = logging.getLogger("dinov2") +XFORMERS_AVAILABLE = True + + +class Block(nn.Module): + def __init__( + self, + dim: int, + num_heads: int, + mlp_ratio: float = 4.0, + qkv_bias: bool = False, + proj_bias: bool = True, + ffn_bias: bool = True, + drop: float = 0.0, + attn_drop: float = 0.0, + init_values=None, + drop_path: float = 0.0, + act_layer: Callable[..., nn.Module] = nn.GELU, + norm_layer: Callable[..., nn.Module] = nn.LayerNorm, + attn_class: Callable[..., nn.Module] = Attention, + ffn_layer: Callable[..., nn.Module] = Mlp, + qk_norm: bool = False, + rope=None, + ln_eps: float = 1e-6, + ) -> None: + super().__init__() + # print(f"biases: qkv: {qkv_bias}, proj: {proj_bias}, ffn: {ffn_bias}") + self.norm1 = norm_layer(dim, eps=ln_eps) + self.attn = attn_class( + dim, + num_heads=num_heads, + qkv_bias=qkv_bias, + proj_bias=proj_bias, + attn_drop=attn_drop, + proj_drop=drop, + qk_norm=qk_norm, + rope=rope, + ) + self.ls1 = LayerScale(dim, init_values=init_values) if init_values else nn.Identity() + self.drop_path1 = DropPath(drop_path) if drop_path > 0.0 else nn.Identity() + + self.norm2 = norm_layer(dim, eps=ln_eps) + mlp_hidden_dim = int(dim * mlp_ratio) + self.mlp = ffn_layer( + in_features=dim, + hidden_features=mlp_hidden_dim, + act_layer=act_layer, + drop=drop, + bias=ffn_bias, + ) + self.ls2 = LayerScale(dim, init_values=init_values) if init_values else nn.Identity() + self.drop_path2 = DropPath(drop_path) if drop_path > 0.0 else nn.Identity() + + self.sample_drop_ratio = drop_path + + def forward(self, x: Tensor, pos=None, attn_mask=None) -> Tensor: + def attn_residual_func(x: Tensor, pos=None, attn_mask=None) -> Tensor: + return self.ls1(self.attn(self.norm1(x), pos=pos, attn_mask=attn_mask)) + + def ffn_residual_func(x: Tensor) -> Tensor: + return self.ls2(self.mlp(self.norm2(x))) + + if self.training and self.sample_drop_ratio > 0.1: + # the overhead is compensated only for a drop path rate larger than 0.1 + x = drop_add_residual_stochastic_depth( + x, + residual_func=attn_residual_func, + sample_drop_ratio=self.sample_drop_ratio, + pos=pos, + ) + x = drop_add_residual_stochastic_depth( + x, + residual_func=ffn_residual_func, + sample_drop_ratio=self.sample_drop_ratio, + ) + elif self.training and self.sample_drop_ratio > 0.0: + x = x + self.drop_path1(attn_residual_func(x, pos=pos, attn_mask=attn_mask)) + x = x + self.drop_path1(ffn_residual_func(x)) # FIXME: drop_path2 + else: + x = x + attn_residual_func(x, pos=pos, attn_mask=attn_mask) + x = x + ffn_residual_func(x) + return x + + +def drop_add_residual_stochastic_depth( + x: Tensor, + residual_func: Callable[[Tensor], Tensor], + sample_drop_ratio: float = 0.0, + pos: Optional[Tensor] = None, +) -> Tensor: + # 1) extract subset using permutation + b, n, d = x.shape + sample_subset_size = max(int(b * (1 - sample_drop_ratio)), 1) + brange = (torch.randperm(b, device=x.device))[:sample_subset_size] + x_subset = x[brange] + + # 2) apply residual_func to get residual + if pos is not None: + # if necessary, apply rope to the subset + pos = pos[brange] + residual = residual_func(x_subset, pos=pos) + else: + residual = residual_func(x_subset) + + x_flat = x.flatten(1) + residual = residual.flatten(1) + + residual_scale_factor = b / sample_subset_size + + # 3) add the residual + x_plus_residual = torch.index_add( + x_flat, 0, brange, residual.to(dtype=x.dtype), alpha=residual_scale_factor + ) + return x_plus_residual.view_as(x) + + +def get_branges_scales(x, sample_drop_ratio=0.0): + b, n, d = x.shape + sample_subset_size = max(int(b * (1 - sample_drop_ratio)), 1) + brange = (torch.randperm(b, device=x.device))[:sample_subset_size] + residual_scale_factor = b / sample_subset_size + return brange, residual_scale_factor diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/dinov2/layers/drop_path.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/dinov2/layers/drop_path.py new file mode 100644 index 0000000000000000000000000000000000000000..1c2cc94e969711f1eb9f62093b79a0139b9bfb1e --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/dinov2/layers/drop_path.py @@ -0,0 +1,35 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +# References: +# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py +# https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/drop.py + + +from torch import nn + + +def drop_path(x, drop_prob: float = 0.0, training: bool = False): + if drop_prob == 0.0 or not training: + return x + keep_prob = 1 - drop_prob + shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets + random_tensor = x.new_empty(shape).bernoulli_(keep_prob) + if keep_prob > 0.0: + random_tensor.div_(keep_prob) + output = x * random_tensor + return output + + +class DropPath(nn.Module): + """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).""" + + def __init__(self, drop_prob=None): + super().__init__() + self.drop_prob = drop_prob + + def forward(self, x): + return drop_path(x, self.drop_prob, self.training) diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/dinov2/layers/layer_scale.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/dinov2/layers/layer_scale.py new file mode 100644 index 0000000000000000000000000000000000000000..898ee12d8b4b65d30d8c041588a8277a8f13d4f2 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/dinov2/layers/layer_scale.py @@ -0,0 +1,31 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +# Modified from: https://github.com/huggingface/pytorch-image-models/blob/main/timm/models/vision_transformer.py#L103-L110 # noqa: E501 + +from typing import Union +import torch +from torch import Tensor, nn + + +class LayerScale(nn.Module): + def __init__( + self, + dim: int, + init_values: Union[float, Tensor] = 1e-5, + inplace: bool = False, + ) -> None: + super().__init__() + self.dim = dim + self.inplace = inplace + self.init_values = init_values + self.gamma = nn.Parameter(init_values * torch.ones(dim)) + + def forward(self, x: Tensor) -> Tensor: + return x.mul_(self.gamma) if self.inplace else x * self.gamma + + def extra_repr(self) -> str: + return f"{self.dim}, init_values={self.init_values}, inplace={self.inplace}" diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/dinov2/layers/mlp.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/dinov2/layers/mlp.py new file mode 100644 index 0000000000000000000000000000000000000000..78ad0d8897ddb77e95d2e188a579f6e1d21e3fb5 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/dinov2/layers/mlp.py @@ -0,0 +1,40 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +# References: +# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py +# https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/mlp.py + + +from typing import Callable, Optional +from torch import Tensor, nn + + +class Mlp(nn.Module): + def __init__( + self, + in_features: int, + hidden_features: Optional[int] = None, + out_features: Optional[int] = None, + act_layer: Callable[..., nn.Module] = nn.GELU, + drop: float = 0.0, + bias: bool = True, + ) -> None: + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features + self.fc1 = nn.Linear(in_features, hidden_features, bias=bias) + self.act = act_layer() + self.fc2 = nn.Linear(hidden_features, out_features, bias=bias) + self.drop = nn.Dropout(drop) + + def forward(self, x: Tensor) -> Tensor: + x = self.fc1(x) + x = self.act(x) + x = self.drop(x) + x = self.fc2(x) + x = self.drop(x) + return x diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/dinov2/layers/patch_embed.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/dinov2/layers/patch_embed.py new file mode 100644 index 0000000000000000000000000000000000000000..64bf6be8994fe52b2fdf1753fdb9f7a691e14980 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/dinov2/layers/patch_embed.py @@ -0,0 +1,94 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +# References: +# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py +# https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/patch_embed.py + +from typing import Callable, Optional, Tuple, Union +import torch.nn as nn +from torch import Tensor + + +def make_2tuple(x): + if isinstance(x, tuple): + assert len(x) == 2 + return x + + assert isinstance(x, int) + return (x, x) + + +class PatchEmbed(nn.Module): + """ + 2D image to patch embedding: (B,C,H,W) -> (B,N,D) + + Args: + img_size: Image size. + patch_size: Patch token size. + in_chans: Number of input image channels. + embed_dim: Number of linear projection output channels. + norm_layer: Normalization layer. + """ + + def __init__( + self, + img_size: Union[int, Tuple[int, int]] = 224, + patch_size: Union[int, Tuple[int, int]] = 16, + in_chans: int = 3, + embed_dim: int = 768, + norm_layer: Optional[Callable] = None, + flatten_embedding: bool = True, + ) -> None: + super().__init__() + + image_HW = make_2tuple(img_size) + patch_HW = make_2tuple(patch_size) + patch_grid_size = ( + image_HW[0] // patch_HW[0], + image_HW[1] // patch_HW[1], + ) + + self.img_size = image_HW + self.patch_size = patch_HW + self.patches_resolution = patch_grid_size + self.num_patches = patch_grid_size[0] * patch_grid_size[1] + + self.in_chans = in_chans + self.embed_dim = embed_dim + + self.flatten_embedding = flatten_embedding + + self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_HW, stride=patch_HW) + self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity() + + def forward(self, x: Tensor) -> Tensor: + _, _, H, W = x.shape + patch_H, patch_W = self.patch_size + + assert ( + H % patch_H == 0 + ), f"Input image height {H} is not a multiple of patch height {patch_H}" + assert ( + W % patch_W == 0 + ), f"Input image width {W} is not a multiple of patch width: {patch_W}" + + x = self.proj(x) # B C H W + H, W = x.size(2), x.size(3) + x = x.flatten(2).transpose(1, 2) # B HW C + x = self.norm(x) + if not self.flatten_embedding: + x = x.reshape(-1, H, W, self.embed_dim) # B H W C + return x + + def flops(self) -> float: + Ho, Wo = self.patches_resolution + flops = ( + Ho * Wo * self.embed_dim * self.in_chans * (self.patch_size[0] * self.patch_size[1]) + ) + if self.norm is not None: + flops += Ho * Wo * self.embed_dim + return flops diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/dinov2/layers/rope.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/dinov2/layers/rope.py new file mode 100644 index 0000000000000000000000000000000000000000..f75ba37c160cd806a32576e2a1704b3352dec7af --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/dinov2/layers/rope.py @@ -0,0 +1,200 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the Apache License, Version 2.0 +# found in the LICENSE file in the root directory of this source tree. + + +# Implementation of 2D Rotary Position Embeddings (RoPE). + +# This module provides a clean implementation of 2D Rotary Position Embeddings, +# which extends the original RoPE concept to handle 2D spatial positions. + +# Inspired by: +# https://github.com/meta-llama/codellama/blob/main/llama/model.py +# https://github.com/naver-ai/rope-vit + + +from typing import Dict, Tuple +import torch +import torch.nn as nn +import torch.nn.functional as F + + +class PositionGetter: + """Generates and caches 2D spatial positions for patches in a grid. + + This class efficiently manages the generation of spatial coordinates for patches + in a 2D grid, caching results to avoid redundant computations. + + Attributes: + position_cache: Dictionary storing precomputed position tensors for different + grid dimensions. + """ + + def __init__(self): + """Initializes the position generator with an empty cache.""" + self.position_cache: Dict[Tuple[int, int], torch.Tensor] = {} + + def __call__( + self, batch_size: int, height: int, width: int, device: torch.device + ) -> torch.Tensor: + """Generates spatial positions for a batch of patches. + + Args: + batch_size: Number of samples in the batch. + height: Height of the grid in patches. + width: Width of the grid in patches. + device: Target device for the position tensor. + + Returns: + Tensor of shape (batch_size, height*width, 2) containing y,x coordinates + for each position in the grid, repeated for each batch item. + """ + if (height, width) not in self.position_cache: + y_coords = torch.arange(height, device=device) + x_coords = torch.arange(width, device=device) + positions = torch.cartesian_prod(y_coords, x_coords) + self.position_cache[height, width] = positions + + cached_positions = self.position_cache[height, width] + return cached_positions.view(1, height * width, 2).expand(batch_size, -1, -1).clone() + + +class RotaryPositionEmbedding2D(nn.Module): + """2D Rotary Position Embedding implementation. + + This module applies rotary position embeddings to input tokens based on their + 2D spatial positions. It handles the position-dependent rotation of features + separately for vertical and horizontal dimensions. + + Args: + frequency: Base frequency for the position embeddings. Default: 100.0 + scaling_factor: Scaling factor for frequency computation. Default: 1.0 + + Attributes: + base_frequency: Base frequency for computing position embeddings. + scaling_factor: Factor to scale the computed frequencies. + frequency_cache: Cache for storing precomputed frequency components. + """ + + def __init__(self, frequency: float = 100.0, scaling_factor: float = 1.0): + """Initializes the 2D RoPE module.""" + super().__init__() + self.base_frequency = frequency + self.scaling_factor = scaling_factor + self.frequency_cache: Dict[Tuple, Tuple[torch.Tensor, torch.Tensor]] = {} + + def _compute_frequency_components( + self, dim: int, seq_len: int, device: torch.device, dtype: torch.dtype + ) -> Tuple[torch.Tensor, torch.Tensor]: + """Computes frequency components for rotary embeddings. + + Args: + dim: Feature dimension (must be even). + seq_len: Maximum sequence length. + device: Target device for computations. + dtype: Data type for the computed tensors. + + Returns: + Tuple of (cosine, sine) tensors for frequency components. + """ + cache_key = (dim, seq_len, device, dtype) + if cache_key not in self.frequency_cache: + # Compute frequency bands + exponents = torch.arange(0, dim, 2, device=device).float() / dim + inv_freq = 1.0 / (self.base_frequency**exponents) + + # Generate position-dependent frequencies + positions = torch.arange(seq_len, device=device, dtype=inv_freq.dtype) + angles = torch.einsum("i,j->ij", positions, inv_freq) + + # Compute and cache frequency components + angles = angles.to(dtype) + angles = torch.cat((angles, angles), dim=-1) + cos_components = angles.cos().to(dtype) + sin_components = angles.sin().to(dtype) + self.frequency_cache[cache_key] = (cos_components, sin_components) + + return self.frequency_cache[cache_key] + + @staticmethod + def _rotate_features(x: torch.Tensor) -> torch.Tensor: + """Performs feature rotation by splitting and recombining feature dimensions. + + Args: + x: Input tensor to rotate. + + Returns: + Rotated feature tensor. + """ + feature_dim = x.shape[-1] + x1, x2 = x[..., : feature_dim // 2], x[..., feature_dim // 2 :] + return torch.cat((-x2, x1), dim=-1) + + def _apply_1d_rope( + self, + tokens: torch.Tensor, + positions: torch.Tensor, + cos_comp: torch.Tensor, + sin_comp: torch.Tensor, + ) -> torch.Tensor: + """Applies 1D rotary position embeddings along one dimension. + + Args: + tokens: Input token features. + positions: Position indices. + cos_comp: Cosine components for rotation. + sin_comp: Sine components for rotation. + + Returns: + Tokens with applied rotary position embeddings. + """ + # Embed positions with frequency components + cos = F.embedding(positions, cos_comp)[:, None, :, :] + sin = F.embedding(positions, sin_comp)[:, None, :, :] + # Apply rotation + return (tokens * cos) + (self._rotate_features(tokens) * sin) + + def forward(self, tokens: torch.Tensor, positions: torch.Tensor) -> torch.Tensor: + """Applies 2D rotary position embeddings to input tokens. + + Args: + tokens: Input tensor of shape (batch_size, n_heads, n_tokens, dim). + The feature dimension (dim) must be divisible by 4. + positions: Position tensor of shape (batch_size, n_tokens, 2) containing + the y and x coordinates for each token. + + Returns: + Tensor of same shape as input with applied 2D rotary position embeddings. + + Raises: + AssertionError: If input dimensions are invalid or positions are malformed. + """ + # Validate inputs + assert tokens.size(-1) % 2 == 0, "Feature dimension must be even" + assert ( + positions.ndim == 3 and positions.shape[-1] == 2 + ), "Positions must have shape (batch_size, n_tokens, 2)" + + # Compute feature dimension for each spatial direction + feature_dim = tokens.size(-1) // 2 + + # Get frequency components + max_position = int(positions.max()) + 1 + cos_comp, sin_comp = self._compute_frequency_components( + feature_dim, max_position, tokens.device, tokens.dtype + ) + + # Split features for vertical and horizontal processing + vertical_features, horizontal_features = tokens.chunk(2, dim=-1) + + # Apply RoPE separately for each dimension + vertical_features = self._apply_1d_rope( + vertical_features, positions[..., 0], cos_comp, sin_comp + ) + horizontal_features = self._apply_1d_rope( + horizontal_features, positions[..., 1], cos_comp, sin_comp + ) + + # Combine processed features + return torch.cat((vertical_features, horizontal_features), dim=-1) diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/dinov2/layers/swiglu_ffn.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/dinov2/layers/swiglu_ffn.py new file mode 100644 index 0000000000000000000000000000000000000000..c8f58e5b265f74c82a4c40adc3ee33a965e503cf --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/dinov2/layers/swiglu_ffn.py @@ -0,0 +1,62 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +from typing import Callable, Optional +import torch.nn.functional as F +from torch import Tensor, nn + + +class SwiGLUFFN(nn.Module): + def __init__( + self, + in_features: int, + hidden_features: Optional[int] = None, + out_features: Optional[int] = None, + act_layer: Callable[..., nn.Module] = None, + drop: float = 0.0, + bias: bool = True, + ) -> None: + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features + self.w12 = nn.Linear(in_features, 2 * hidden_features, bias=bias) + self.w3 = nn.Linear(hidden_features, out_features, bias=bias) + + def forward(self, x: Tensor) -> Tensor: + x12 = self.w12(x) + x1, x2 = x12.chunk(2, dim=-1) + hidden = F.silu(x1) * x2 + return self.w3(hidden) + + +try: + from xformers.ops import SwiGLU + + XFORMERS_AVAILABLE = True +except ImportError: + SwiGLU = SwiGLUFFN + XFORMERS_AVAILABLE = False + + +class SwiGLUFFNFused(SwiGLU): + def __init__( + self, + in_features: int, + hidden_features: Optional[int] = None, + out_features: Optional[int] = None, + act_layer: Callable[..., nn.Module] = None, + drop: float = 0.0, + bias: bool = True, + ) -> None: + out_features = out_features or in_features + hidden_features = hidden_features or in_features + hidden_features = (int(hidden_features * 2 / 3) + 7) // 8 * 8 + super().__init__( + in_features=in_features, + hidden_features=hidden_features, + out_features=out_features, + bias=bias, + ) diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/dinov2/vision_transformer.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/dinov2/vision_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..b392e4835b98d4cca40d69a5275784ef2843f6a2 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/dinov2/vision_transformer.py @@ -0,0 +1,456 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the Apache License, Version 2.0 +# found in the LICENSE file in the root directory of this source tree. + +# References: +# https://github.com/facebookresearch/dino/blob/main/vision_transformer.py +# https://github.com/rwightman/pytorch-image-models/tree/master/timm/models/vision_transformer.py + +import math +from typing import Callable, List, Sequence, Tuple, Union +import numpy as np +import torch +import torch.nn as nn +import torch.utils.checkpoint +from einops import rearrange + +from depth_anything_3.utils.logger import logger + +from .layers import LayerScale # noqa: F401 +from .layers import Mlp # noqa: F401 +from .layers import ( # noqa: F401 + Block, + PatchEmbed, + PositionGetter, + RotaryPositionEmbedding2D, + SwiGLUFFNFused, +) +from depth_anything_3.model.reference_view_selector import ( + RefViewStrategy, + select_reference_view, + reorder_by_reference, + restore_original_order, +) +from depth_anything_3.utils.constants import THRESH_FOR_REF_SELECTION + +# logger = logging.getLogger("dinov2") + + +def get_1d_sincos_pos_embed_from_grid(embed_dim, pos): + """ + embed_dim: output dimension for each position + pos: a list of positions to be encoded: size (M,) + out: (M, D) + """ + assert embed_dim % 2 == 0 + omega = np.arange(embed_dim // 2, dtype=float) + omega /= embed_dim / 2.0 + omega = 1.0 / 10000**omega # (D/2,) + + pos = pos.reshape(-1) # (M,) + out = np.einsum("m,d->md", pos, omega) # (M, D/2), outer product + + emb_sin = np.sin(out) # (M, D/2) + emb_cos = np.cos(out) # (M, D/2) + + emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D) + return emb + + +def named_apply( + fn: Callable, module: nn.Module, name="", depth_first=True, include_root=False +) -> nn.Module: + if not depth_first and include_root: + fn(module=module, name=name) + for child_name, child_module in module.named_children(): + child_name = ".".join((name, child_name)) if name else child_name + named_apply( + fn=fn, module=child_module, name=child_name, depth_first=depth_first, include_root=True + ) + if depth_first and include_root: + fn(module=module, name=name) + return module + + +class BlockChunk(nn.ModuleList): + def forward(self, x): + for b in self: + x = b(x) + return x + + +class DinoVisionTransformer(nn.Module): + def __init__( + self, + img_size=224, + patch_size=16, + in_chans=3, + embed_dim=768, + depth=12, + num_heads=12, + mlp_ratio=4.0, + qkv_bias=True, + ffn_bias=True, + proj_bias=True, + drop_path_rate=0.0, + drop_path_uniform=False, + init_values=1.0, # for layerscale: None or 0 => no layerscale + embed_layer=PatchEmbed, + act_layer=nn.GELU, + block_fn=Block, + ffn_layer="mlp", + block_chunks=1, + num_register_tokens=0, + interpolate_antialias=False, + interpolate_offset=0.1, + alt_start=-1, + qknorm_start=-1, + rope_start=-1, + rope_freq=100, + plus_cam_token=False, + cat_token=True, + ): + """ + Args: + img_size (int, tuple): input image size + patch_size (int, tuple): patch size + in_chans (int): number of input channels + embed_dim (int): embedding dimension + depth (int): depth of transformer + num_heads (int): number of attention heads + mlp_ratio (int): ratio of mlp hidden dim to embedding dim + qkv_bias (bool): enable bias for qkv if True + proj_bias (bool): enable bias for proj in attn if True + ffn_bias (bool): enable bias for ffn if True + weight_init (str): weight init scheme + init_values (float): layer-scale init values + embed_layer (nn.Module): patch embedding layer + act_layer (nn.Module): MLP activation layer + block_fn (nn.Module): transformer block class + ffn_layer (str): "mlp", "swiglu", "swiglufused" or "identity" + block_chunks: (int) split block sequence into block_chunks units for FSDP wrap + num_register_tokens: (int) number of extra cls tokens (so-called "registers") + interpolate_antialias: (str) flag to apply anti-aliasing when interpolating + positional embeddings + interpolate_offset: (float) work-around offset to apply when interpolating + positional embeddings + """ + super().__init__() + self.patch_start_idx = 1 + norm_layer = nn.LayerNorm + self.num_features = self.embed_dim = ( + embed_dim # num_features for consistency with other models + ) + self.alt_start = alt_start + self.qknorm_start = qknorm_start + self.rope_start = rope_start + self.cat_token = cat_token + self.num_tokens = 1 + self.n_blocks = depth + self.num_heads = num_heads + self.patch_size = patch_size + self.num_register_tokens = num_register_tokens + self.interpolate_antialias = interpolate_antialias + self.interpolate_offset = interpolate_offset + + self.patch_embed = embed_layer( + img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim + ) + num_patches = self.patch_embed.num_patches + self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) + if self.alt_start != -1: + self.camera_token = nn.Parameter(torch.randn(1, 2, embed_dim)) + self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + self.num_tokens, embed_dim)) + assert num_register_tokens >= 0 + self.register_tokens = ( + nn.Parameter(torch.zeros(1, num_register_tokens, embed_dim)) + if num_register_tokens + else None + ) + + if drop_path_uniform is True: + dpr = [drop_path_rate] * depth + else: + dpr = [ + x.item() for x in torch.linspace(0, drop_path_rate, depth) + ] # stochastic depth decay rule + if ffn_layer == "mlp": + logger.info("using MLP layer as FFN") + ffn_layer = Mlp + elif ffn_layer == "swiglufused" or ffn_layer == "swiglu": + logger.info("using SwiGLU layer as FFN") + ffn_layer = SwiGLUFFNFused + elif ffn_layer == "identity": + logger.info("using Identity layer as FFN") + + def f(*args, **kwargs): + return nn.Identity() + + ffn_layer = f + else: + raise NotImplementedError + + if self.rope_start != -1: + self.rope = RotaryPositionEmbedding2D(frequency=rope_freq) if rope_freq > 0 else None + self.position_getter = PositionGetter() if self.rope is not None else None + else: + self.rope = None + blocks_list = [ + block_fn( + dim=embed_dim, + num_heads=num_heads, + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + proj_bias=proj_bias, + ffn_bias=ffn_bias, + drop_path=dpr[i], + norm_layer=norm_layer, + act_layer=act_layer, + ffn_layer=ffn_layer, + init_values=init_values, + qk_norm=i >= qknorm_start if qknorm_start != -1 else False, + rope=self.rope if i >= rope_start and rope_start != -1 else None, + ) + for i in range(depth) + ] + self.blocks = nn.ModuleList(blocks_list) + self.norm = norm_layer(embed_dim) + + def interpolate_pos_encoding(self, x, w, h): + previous_dtype = x.dtype + npatch = x.shape[1] - 1 + N = self.pos_embed.shape[1] - 1 + if npatch == N and w == h: + return self.pos_embed + pos_embed = self.pos_embed.float() + class_pos_embed = pos_embed[:, 0] + patch_pos_embed = pos_embed[:, 1:] + dim = x.shape[-1] + w0 = w // self.patch_size + h0 = h // self.patch_size + M = int(math.sqrt(N)) # Recover the number of patches in each dimension + assert N == M * M + kwargs = {} + if self.interpolate_offset: + # Historical kludge: add a small number to avoid floating point error in the + # interpolation, see https://github.com/facebookresearch/dino/issues/8 + # Note: still needed for backward-compatibility, the underlying operators are using + # both output size and scale factors + sx = float(w0 + self.interpolate_offset) / M + sy = float(h0 + self.interpolate_offset) / M + kwargs["scale_factor"] = (sx, sy) + else: + # Simply specify an output size instead of a scale factor + kwargs["size"] = (w0, h0) + patch_pos_embed = nn.functional.interpolate( + patch_pos_embed.reshape(1, M, M, dim).permute(0, 3, 1, 2), + mode="bicubic", + antialias=self.interpolate_antialias, + **kwargs, + ) + assert (w0, h0) == patch_pos_embed.shape[-2:] + patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim) + return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1).to(previous_dtype) + + def prepare_cls_token(self, B, S): + cls_token = self.cls_token.expand(B, S, -1) + cls_token = cls_token.reshape(B * S, -1, self.embed_dim) + return cls_token + + def prepare_tokens_with_masks(self, x, masks=None, cls_token=None, **kwargs): + B, S, nc, w, h = x.shape + x = rearrange(x, "b s c h w -> (b s) c h w") + x = self.patch_embed(x) + if masks is not None: + x = torch.where(masks.unsqueeze(-1), self.mask_token.to(x.dtype).unsqueeze(0), x) + cls_token = self.prepare_cls_token(B, S) + x = torch.cat((cls_token, x), dim=1) + x = x + self.interpolate_pos_encoding(x, w, h) + if self.register_tokens is not None: + x = torch.cat( + ( + x[:, :1], + self.register_tokens.expand(x.shape[0], -1, -1), + x[:, 1:], + ), + dim=1, + ) + x = rearrange(x, "(b s) n c -> b s n c", b=B, s=S) + return x + + def _prepare_rope(self, B, S, H, W, device): + pos = None + pos_nodiff = None + if self.rope is not None: + pos = self.position_getter( + B * S, H // self.patch_size, W // self.patch_size, device=device + ) + pos = rearrange(pos, "(b s) n c -> b s n c", b=B) + pos_nodiff = torch.zeros_like(pos).to(pos.dtype) + if self.patch_start_idx > 0: + pos = pos + 1 + pos_special = torch.zeros(B * S, self.patch_start_idx, 2).to(device).to(pos.dtype) + pos_special = rearrange(pos_special, "(b s) n c -> b s n c", b=B) + pos = torch.cat([pos_special, pos], dim=2) + pos_nodiff = pos_nodiff + 1 + pos_nodiff = torch.cat([pos_special, pos_nodiff], dim=2) + return pos, pos_nodiff + + def _get_intermediate_layers_not_chunked(self, x, n=1, export_feat_layers=[], **kwargs): + B, S, _, H, W = x.shape + x = self.prepare_tokens_with_masks(x) + output, total_block_len, aux_output = [], len(self.blocks), [] + blocks_to_take = range(total_block_len - n, total_block_len) if isinstance(n, int) else n + pos, pos_nodiff = self._prepare_rope(B, S, H, W, x.device) + + for i, blk in enumerate(self.blocks): + if i < self.rope_start or self.rope is None: + g_pos, l_pos = None, None + else: + g_pos = pos_nodiff + l_pos = pos + + if self.alt_start != -1 and (i == self.alt_start - 1) and x.shape[1] >= THRESH_FOR_REF_SELECTION: + # Select reference view using configured strategy + strategy = kwargs.get("ref_view_strategy", "saddle_balanced") + logger.info(f"Selecting reference view using strategy: {strategy}") + b_idx = select_reference_view(x, strategy=strategy) + # Reorder views to place reference view first + x = reorder_by_reference(x, b_idx) + local_x = reorder_by_reference(local_x, b_idx) + + if self.alt_start != -1 and i == self.alt_start: + if kwargs.get("cam_token", None) is not None: + logger.info("Using camera conditions provided by the user") + cam_token = kwargs.get("cam_token") + else: + ref_token = self.camera_token[:, :1].expand(B, -1, -1) + src_token = self.camera_token[:, 1:].expand(B, S - 1, -1) + cam_token = torch.cat([ref_token, src_token], dim=1) + x[:, :, 0] = cam_token + + if self.alt_start != -1 and i >= self.alt_start and i % 2 == 1: + x = self.process_attention( + x, blk, "global", pos=g_pos, attn_mask=kwargs.get("attn_mask", None) + ) + else: + x = self.process_attention(x, blk, "local", pos=l_pos) + local_x = x + + if i in blocks_to_take: + out_x = torch.cat([local_x, x], dim=-1) if self.cat_token else x + # Restore original view order if reordering was applied + if x.shape[1] >= THRESH_FOR_REF_SELECTION and self.alt_start != -1 and 'b_idx' in locals(): + out_x = restore_original_order(out_x, b_idx) + output.append((out_x[:, :, 0], out_x)) + if i in export_feat_layers: + aux_output.append(x) + return output, aux_output + + def process_attention(self, x, block, attn_type="global", pos=None, attn_mask=None): + b, s, n = x.shape[:3] + if attn_type == "local": + x = rearrange(x, "b s n c -> (b s) n c") + if pos is not None: + pos = rearrange(pos, "b s n c -> (b s) n c") + elif attn_type == "global": + x = rearrange(x, "b s n c -> b (s n) c") + if pos is not None: + pos = rearrange(pos, "b s n c -> b (s n) c") + else: + raise ValueError(f"Invalid attention type: {attn_type}") + + x = block(x, pos=pos, attn_mask=attn_mask) + + if attn_type == "local": + x = rearrange(x, "(b s) n c -> b s n c", b=b, s=s) + elif attn_type == "global": + x = rearrange(x, "b (s n) c -> b s n c", b=b, s=s) + return x + + def get_intermediate_layers( + self, + x: torch.Tensor, + n: Union[int, Sequence] = 1, # Layers or n last layers to take + export_feat_layers: List[int] = [], + **kwargs, + ) -> Tuple[Union[torch.Tensor, Tuple[torch.Tensor]]]: + outputs, aux_outputs = self._get_intermediate_layers_not_chunked( + x, n, export_feat_layers=export_feat_layers, **kwargs + ) + camera_tokens = [out[0] for out in outputs] + if outputs[0][1].shape[-1] == self.embed_dim: + outputs = [self.norm(out[1]) for out in outputs] + elif outputs[0][1].shape[-1] == (self.embed_dim * 2): + outputs = [ + torch.cat( + [out[1][..., : self.embed_dim], self.norm(out[1][..., self.embed_dim :])], + dim=-1, + ) + for out in outputs + ] + else: + raise ValueError(f"Invalid output shape: {outputs[0][1].shape}") + aux_outputs = [self.norm(out) for out in aux_outputs] + outputs = [out[..., 1 + self.num_register_tokens :, :] for out in outputs] + aux_outputs = [out[..., 1 + self.num_register_tokens :, :] for out in aux_outputs] + return tuple(zip(outputs, camera_tokens)), aux_outputs + + +def vit_small(patch_size=16, num_register_tokens=0, depth=12, **kwargs): + model = DinoVisionTransformer( + patch_size=patch_size, + embed_dim=384, + depth=depth, + num_heads=6, + mlp_ratio=4, + # block_fn=partial(Block, attn_class=MemEffAttention), + num_register_tokens=num_register_tokens, + **kwargs, + ) + return model + + +def vit_base(patch_size=16, num_register_tokens=0, depth=12, **kwargs): + model = DinoVisionTransformer( + patch_size=patch_size, + embed_dim=768, + depth=depth, + num_heads=12, + mlp_ratio=4, + # block_fn=partial(Block, attn_class=MemEffAttention), + num_register_tokens=num_register_tokens, + **kwargs, + ) + return model + + +def vit_large(patch_size=16, num_register_tokens=0, depth=24, **kwargs): + model = DinoVisionTransformer( + patch_size=patch_size, + embed_dim=1024, + depth=depth, + num_heads=16, + mlp_ratio=4, + # block_fn=partial(Block, attn_class=MemEffAttention), + num_register_tokens=num_register_tokens, + **kwargs, + ) + return model + + +def vit_giant2(patch_size=16, num_register_tokens=0, depth=40, **kwargs): + """ + Close to ViT-giant, with embed-dim 1536 and 24 heads => embed-dim per head 64 + """ + model = DinoVisionTransformer( + patch_size=patch_size, + embed_dim=1536, + depth=depth, + num_heads=24, + mlp_ratio=4, + num_register_tokens=num_register_tokens, + **kwargs, + ) + return model diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/dpt.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/dpt.py new file mode 100644 index 0000000000000000000000000000000000000000..337a8a964a7f96fae997c8b12e3ae13e99dbaa58 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/dpt.py @@ -0,0 +1,458 @@ +# flake8: noqa E501 +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import Dict as TyDict +from typing import List, Sequence, Tuple +import torch +import torch.nn as nn +from addict import Dict +from einops import rearrange + +from depth_anything_3.model.utils.head_utils import ( + Permute, + create_uv_grid, + custom_interpolate, + position_grid_to_embed, +) + + +class DPT(nn.Module): + """ + DPT for dense prediction (main head + optional sky head, sky always 1 channel). + + Returns: + - Main head: + * If output_dim>1: { head_name, f"{head_name}_conf" } + * If output_dim==1: { head_name } + - Sky head (if use_sky_head=True): { sky_name } # [B, S, 1, H/down_ratio, W/down_ratio] + """ + + def __init__( + self, + dim_in: int, + *, + patch_size: int = 14, + output_dim: int = 1, + activation: str = "exp", + conf_activation: str = "expp1", + features: int = 256, + out_channels: Sequence[int] = (256, 512, 1024, 1024), + pos_embed: bool = False, + down_ratio: int = 1, + head_name: str = "depth", + # ---- sky head (fixed 1 channel) ---- + use_sky_head: bool = True, + sky_name: str = "sky", + sky_activation: str = "relu", # 'sigmoid' / 'relu' / 'linear' + use_ln_for_heads: bool = False, # If needed, apply LayerNorm on intermediate features of both heads + norm_type: str = "idt", # use to match legacy GS-DPT head, "idt" / "layer" + fusion_block_inplace: bool = False, + ) -> None: + super().__init__() + + # -------------------- configuration -------------------- + self.patch_size = patch_size + self.activation = activation + self.conf_activation = conf_activation + self.pos_embed = pos_embed + self.down_ratio = down_ratio + + # Names + self.head_main = head_name + self.sky_name = sky_name + + # Main head: output dimension and confidence switch + self.out_dim = output_dim + self.has_conf = output_dim > 1 + + # Sky head parameters (always 1 channel) + self.use_sky_head = use_sky_head + self.sky_activation = sky_activation + + # Fixed 4 intermediate outputs + self.intermediate_layer_idx: Tuple[int, int, int, int] = (0, 1, 2, 3) + + # -------------------- token pre-norm + per-stage projection -------------------- + if norm_type == "layer": + self.norm = nn.LayerNorm(dim_in) + elif norm_type == "idt": + self.norm = nn.Identity() + else: + raise Exception(f"Unknown norm_type {norm_type}, should be 'layer' or 'idt'.") + self.projects = nn.ModuleList( + [nn.Conv2d(dim_in, oc, kernel_size=1, stride=1, padding=0) for oc in out_channels] + ) + + # -------------------- Spatial re-size (align to common scale before fusion) -------------------- + # Design consistent with original: relative to patch grid (x4, x2, x1, /2) + self.resize_layers = nn.ModuleList( + [ + nn.ConvTranspose2d( + out_channels[0], out_channels[0], kernel_size=4, stride=4, padding=0 + ), + nn.ConvTranspose2d( + out_channels[1], out_channels[1], kernel_size=2, stride=2, padding=0 + ), + nn.Identity(), + nn.Conv2d(out_channels[3], out_channels[3], kernel_size=3, stride=2, padding=1), + ] + ) + + # -------------------- scratch: stage adapters + main fusion chain -------------------- + self.scratch = _make_scratch(list(out_channels), features, expand=False) + + # Main fusion chain + self.scratch.refinenet1 = _make_fusion_block(features, inplace=fusion_block_inplace) + self.scratch.refinenet2 = _make_fusion_block(features, inplace=fusion_block_inplace) + self.scratch.refinenet3 = _make_fusion_block(features, inplace=fusion_block_inplace) + self.scratch.refinenet4 = _make_fusion_block( + features, has_residual=False, inplace=fusion_block_inplace + ) + + # Heads (shared neck1; then split into two heads) + head_features_1 = features + head_features_2 = 32 + self.scratch.output_conv1 = nn.Conv2d( + head_features_1, head_features_1 // 2, kernel_size=3, stride=1, padding=1 + ) + + ln_seq = ( + [Permute((0, 2, 3, 1)), nn.LayerNorm(head_features_2), Permute((0, 3, 1, 2))] + if use_ln_for_heads + else [] + ) + + # Main head + self.scratch.output_conv2 = nn.Sequential( + nn.Conv2d(head_features_1 // 2, head_features_2, kernel_size=3, stride=1, padding=1), + *ln_seq, + nn.ReLU(inplace=True), + nn.Conv2d(head_features_2, output_dim, kernel_size=1, stride=1, padding=0), + ) + + # Sky head (fixed 1 channel) + if self.use_sky_head: + self.scratch.sky_output_conv2 = nn.Sequential( + nn.Conv2d( + head_features_1 // 2, head_features_2, kernel_size=3, stride=1, padding=1 + ), + *ln_seq, + nn.ReLU(inplace=True), + nn.Conv2d(head_features_2, 1, kernel_size=1, stride=1, padding=0), + ) + + # ------------------------------------------------------------------------- + # Public forward (supports frame chunking to save memory) + # ------------------------------------------------------------------------- + def forward( + self, + feats: List[torch.Tensor], + H: int, + W: int, + patch_start_idx: int, + chunk_size: int = 8, + **kwargs, + ) -> Dict: + """ + Args: + feats: List of 4 entries, each entry is a tensor like [B, S, T, C] (or the 0th element of tuple/list is that tensor). + H, W: Original image dimensions + patch_start_idx: Starting index of patch tokens in sequence (for cropping non-patch tokens) + chunk_size: Chunk size along time dimension S + + Returns: + Dict[str, Tensor] + """ + B, S, N, C = feats[0][0].shape + feats = [feat[0].reshape(B * S, N, C) for feat in feats] + + # update image info, used by the GS-DPT head + extra_kwargs = {} + if "images" in kwargs: + extra_kwargs.update({"images": rearrange(kwargs["images"], "B S ... -> (B S) ...")}) + + if chunk_size is None or chunk_size >= S: + out_dict = self._forward_impl(feats, H, W, patch_start_idx, **extra_kwargs) + out_dict = {k: v.view(B, S, *v.shape[1:]) for k, v in out_dict.items()} + return Dict(out_dict) + + out_dicts: List[TyDict[str, torch.Tensor]] = [] + for s0 in range(0, S, chunk_size): + s1 = min(s0 + chunk_size, S) + kw = {} + if "images" in extra_kwargs: + kw.update({"images": extra_kwargs["images"][s0:s1]}) + out_dicts.append( + self._forward_impl([f[s0:s1] for f in feats], H, W, patch_start_idx, **kw) + ) + out_dict = {k: torch.cat([od[k] for od in out_dicts], dim=0) for k in out_dicts[0].keys()} + out_dict = {k: v.view(B, S, *v.shape[1:]) for k, v in out_dict.items()} + return Dict(out_dict) + + # ------------------------------------------------------------------------- + # Internal forward (single chunk) + # ------------------------------------------------------------------------- + def _forward_impl( + self, + feats: List[torch.Tensor], + H: int, + W: int, + patch_start_idx: int, + ) -> TyDict[str, torch.Tensor]: + B, _, C = feats[0].shape + ph, pw = H // self.patch_size, W // self.patch_size + resized_feats = [] + for stage_idx, take_idx in enumerate(self.intermediate_layer_idx): + x = feats[take_idx][:, patch_start_idx:] # [B*S, N_patch, C] + x = self.norm(x) + # permute -> contiguous before reshape to keep conv input contiguous + x = x.permute(0, 2, 1).contiguous().reshape(B, C, ph, pw) # [B*S, C, ph, pw] + + x = self.projects[stage_idx](x) + if self.pos_embed: + x = self._add_pos_embed(x, W, H) + x = self.resize_layers[stage_idx](x) # Align scale + resized_feats.append(x) + + # 2) Fusion pyramid (main branch only) + fused = self._fuse(resized_feats) + + # 3) Upsample to target resolution, optionally add position encoding again + h_out = int(ph * self.patch_size / self.down_ratio) + w_out = int(pw * self.patch_size / self.down_ratio) + + fused = self.scratch.output_conv1(fused) + fused = custom_interpolate(fused, (h_out, w_out), mode="bilinear", align_corners=True) + if self.pos_embed: + fused = self._add_pos_embed(fused, W, H) + + # 4) Shared neck1 + feat = fused + + # 5) Main head: logits -> activation + main_logits = self.scratch.output_conv2(feat) + outs: TyDict[str, torch.Tensor] = {} + if self.has_conf: + fmap = main_logits.permute(0, 2, 3, 1) + pred = self._apply_activation_single(fmap[..., :-1], self.activation) + conf = self._apply_activation_single(fmap[..., -1], self.conf_activation) + outs[self.head_main] = pred.squeeze(1) + outs[f"{self.head_main}_conf"] = conf.squeeze(1) + else: + outs[self.head_main] = self._apply_activation_single( + main_logits, self.activation + ).squeeze(1) + + # 6) Sky head (fixed 1 channel) + if self.use_sky_head: + sky_logits = self.scratch.sky_output_conv2(feat) + outs[self.sky_name] = self._apply_sky_activation(sky_logits).squeeze(1) + + return outs + + # ------------------------------------------------------------------------- + # Subroutines + # ------------------------------------------------------------------------- + def _fuse(self, feats: List[torch.Tensor]) -> torch.Tensor: + """ + 4-layer top-down fusion, returns finest scale features (after fusion, before neck1). + """ + l1, l2, l3, l4 = feats + + l1_rn = self.scratch.layer1_rn(l1) + l2_rn = self.scratch.layer2_rn(l2) + l3_rn = self.scratch.layer3_rn(l3) + l4_rn = self.scratch.layer4_rn(l4) + + # 4 -> 3 -> 2 -> 1 + out = self.scratch.refinenet4(l4_rn, size=l3_rn.shape[2:]) + out = self.scratch.refinenet3(out, l3_rn, size=l2_rn.shape[2:]) + out = self.scratch.refinenet2(out, l2_rn, size=l1_rn.shape[2:]) + out = self.scratch.refinenet1(out, l1_rn) + return out + + def _apply_activation_single( + self, x: torch.Tensor, activation: str = "linear" + ) -> torch.Tensor: + """ + Apply activation to single channel output, maintaining semantic consistency with value branch in multi-channel case. + Supports: exp / relu / sigmoid / softplus / tanh / linear / expp1 + """ + act = activation.lower() if isinstance(activation, str) else activation + if act == "exp": + return torch.exp(x) + if act == "expp1": + return torch.exp(x) + 1 + if act == "expm1": + return torch.expm1(x) + if act == "relu": + return torch.relu(x) + if act == "sigmoid": + return torch.sigmoid(x) + if act == "softplus": + return torch.nn.functional.softplus(x) + if act == "tanh": + return torch.tanh(x) + # Default linear + return x + + def _apply_sky_activation(self, x: torch.Tensor) -> torch.Tensor: + """ + Sky head activation (fixed 1 channel): + * 'sigmoid' -> Sigmoid probability map + * 'relu' -> ReLU positive domain output + * 'linear' -> Original value (logits) + """ + act = ( + self.sky_activation.lower() + if isinstance(self.sky_activation, str) + else self.sky_activation + ) + if act == "sigmoid": + return torch.sigmoid(x) + if act == "relu": + return torch.relu(x) + # 'linear' + return x + + def _add_pos_embed(self, x: torch.Tensor, W: int, H: int, ratio: float = 0.1) -> torch.Tensor: + """Simple UV position encoding directly added to feature map.""" + pw, ph = x.shape[-1], x.shape[-2] + pe = create_uv_grid(pw, ph, aspect_ratio=W / H, dtype=x.dtype, device=x.device) + pe = position_grid_to_embed(pe, x.shape[1]) * ratio + pe = pe.permute(2, 0, 1)[None].expand(x.shape[0], -1, -1, -1) + return x + pe + + +# ----------------------------------------------------------------------------- +# Building blocks (preserved, consistent with original) +# ----------------------------------------------------------------------------- +def _make_fusion_block( + features: int, + size: Tuple[int, int] = None, + has_residual: bool = True, + groups: int = 1, + inplace: bool = False, +) -> nn.Module: + return FeatureFusionBlock( + features=features, + activation=nn.ReLU(inplace=inplace), + deconv=False, + bn=False, + expand=False, + align_corners=True, + size=size, + has_residual=has_residual, + groups=groups, + ) + + +def _make_scratch( + in_shape: List[int], out_shape: int, groups: int = 1, expand: bool = False +) -> nn.Module: + scratch = nn.Module() + # Optional expansion by stage + c1 = out_shape + c2 = out_shape * (2 if expand else 1) + c3 = out_shape * (4 if expand else 1) + c4 = out_shape * (8 if expand else 1) + + scratch.layer1_rn = nn.Conv2d(in_shape[0], c1, 3, 1, 1, bias=False, groups=groups) + scratch.layer2_rn = nn.Conv2d(in_shape[1], c2, 3, 1, 1, bias=False, groups=groups) + scratch.layer3_rn = nn.Conv2d(in_shape[2], c3, 3, 1, 1, bias=False, groups=groups) + scratch.layer4_rn = nn.Conv2d(in_shape[3], c4, 3, 1, 1, bias=False, groups=groups) + return scratch + + +class ResidualConvUnit(nn.Module): + """Lightweight residual convolution block for fusion""" + + def __init__(self, features: int, activation: nn.Module, bn: bool, groups: int = 1) -> None: + super().__init__() + self.bn = bn + self.groups = groups + self.conv1 = nn.Conv2d(features, features, 3, 1, 1, bias=True, groups=groups) + self.conv2 = nn.Conv2d(features, features, 3, 1, 1, bias=True, groups=groups) + self.norm1 = None + self.norm2 = None + self.activation = activation + self.skip_add = nn.quantized.FloatFunctional() + + def forward(self, x: torch.Tensor) -> torch.Tensor: # type: ignore[override] + out = self.activation(x) + out = self.conv1(out) + if self.norm1 is not None: + out = self.norm1(out) + + out = self.activation(out) + out = self.conv2(out) + if self.norm2 is not None: + out = self.norm2(out) + + return self.skip_add.add(out, x) + + +class FeatureFusionBlock(nn.Module): + """Top-down fusion block: (optional) residual merge + upsampling + 1x1 contraction""" + + def __init__( + self, + features: int, + activation: nn.Module, + deconv: bool = False, + bn: bool = False, + expand: bool = False, + align_corners: bool = True, + size: Tuple[int, int] = None, + has_residual: bool = True, + groups: int = 1, + ) -> None: + super().__init__() + self.align_corners = align_corners + self.size = size + self.has_residual = has_residual + + self.resConfUnit1 = ( + ResidualConvUnit(features, activation, bn, groups=groups) if has_residual else None + ) + self.resConfUnit2 = ResidualConvUnit(features, activation, bn, groups=groups) + + out_features = (features // 2) if expand else features + self.out_conv = nn.Conv2d(features, out_features, 1, 1, 0, bias=True, groups=groups) + self.skip_add = nn.quantized.FloatFunctional() + + def forward(self, *xs: torch.Tensor, size: Tuple[int, int] = None) -> torch.Tensor: # type: ignore[override] + """ + xs: + - xs[0]: Top branch input + - xs[1]: Lateral input (can do residual addition with top branch) + """ + y = xs[0] + if self.has_residual and len(xs) > 1 and self.resConfUnit1 is not None: + y = self.skip_add.add(y, self.resConfUnit1(xs[1])) + + y = self.resConfUnit2(y) + + # Upsampling + if (size is None) and (self.size is None): + up_kwargs = {"scale_factor": 2} + elif size is None: + up_kwargs = {"size": self.size} + else: + up_kwargs = {"size": size} + + y = custom_interpolate(y, **up_kwargs, mode="bilinear", align_corners=self.align_corners) + y = self.out_conv(y) + return y diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/dualdpt.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/dualdpt.py new file mode 100644 index 0000000000000000000000000000000000000000..229e1a990472de96f003a4a2d75fdf4ca94b0a3a --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/dualdpt.py @@ -0,0 +1,488 @@ +# flake8: noqa E501 +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import List, Sequence, Tuple +import torch +import torch.nn as nn +from addict import Dict + +from depth_anything_3.model.dpt import _make_fusion_block, _make_scratch +from depth_anything_3.model.utils.head_utils import ( + Permute, + create_uv_grid, + custom_interpolate, + position_grid_to_embed, +) + + +class DualDPT(nn.Module): + """ + Dual-head DPT for dense prediction with an always-on auxiliary head. + + Architectural notes: + - Sky/object branches are removed. + - `intermediate_layer_idx` is fixed to (0, 1, 2, 3). + - Auxiliary head has its **own** fusion blocks (no fusion_inplace / no sharing). + - Auxiliary head is internally multi-level; **only the final level** is returned. + - Returns a **dict** with keys from `head_names`, e.g.: + { main_name, f"{main_name}_conf", aux_name, f"{aux_name}_conf" } + - `feature_only` is fixed to False. + """ + + def __init__( + self, + dim_in: int, + *, + patch_size: int = 14, + output_dim: int = 2, + activation: str = "exp", + conf_activation: str = "expp1", + features: int = 256, + out_channels: Sequence[int] = (256, 512, 1024, 1024), + pos_embed: bool = True, + down_ratio: int = 1, + aux_pyramid_levels: int = 4, + aux_out1_conv_num: int = 5, + head_names: Tuple[str, str] = ("depth", "ray"), + ) -> None: + super().__init__() + + # -------------------- configuration -------------------- + self.patch_size = patch_size + self.activation = activation + self.conf_activation = conf_activation + self.pos_embed = pos_embed + self.down_ratio = down_ratio + + self.aux_levels = aux_pyramid_levels + self.aux_out1_conv_num = aux_out1_conv_num + + # names ONLY come from config (no hard-coded strings elsewhere) + self.head_main, self.head_aux = head_names + + # Always expect 4 scales; enforce intermediate idx = (0, 1, 2, 3) + self.intermediate_layer_idx: Tuple[int, int, int, int] = (0, 1, 2, 3) + + # -------------------- token pre-norm + per-stage projection -------------------- + self.norm = nn.LayerNorm(dim_in) + self.projects = nn.ModuleList( + [nn.Conv2d(dim_in, oc, kernel_size=1, stride=1, padding=0) for oc in out_channels] + ) + + # -------------------- spatial re-sizers (align to common scale before fusion) -------------------- + # design: stage strides (x4, x2, x1, /2) relative to patch grid to align to a common pivot scale + self.resize_layers = nn.ModuleList( + [ + nn.ConvTranspose2d( + out_channels[0], out_channels[0], kernel_size=4, stride=4, padding=0 + ), + nn.ConvTranspose2d( + out_channels[1], out_channels[1], kernel_size=2, stride=2, padding=0 + ), + nn.Identity(), + nn.Conv2d(out_channels[3], out_channels[3], kernel_size=3, stride=2, padding=1), + ] + ) + + # -------------------- scratch: stage adapters + fusion (main & aux are separate) -------------------- + self.scratch = _make_scratch(list(out_channels), features, expand=False) + + # Main fusion chain (independent) + self.scratch.refinenet1 = _make_fusion_block(features) + self.scratch.refinenet2 = _make_fusion_block(features) + self.scratch.refinenet3 = _make_fusion_block(features) + self.scratch.refinenet4 = _make_fusion_block(features, has_residual=False) + + # Primary head neck + head (independent) + head_features_1 = features + head_features_2 = 32 + self.scratch.output_conv1 = nn.Conv2d( + head_features_1, head_features_1 // 2, kernel_size=3, stride=1, padding=1 + ) + self.scratch.output_conv2 = nn.Sequential( + nn.Conv2d(head_features_1 // 2, head_features_2, kernel_size=3, stride=1, padding=1), + nn.ReLU(inplace=True), + nn.Conv2d(head_features_2, output_dim, kernel_size=1, stride=1, padding=0), + ) + + # Auxiliary fusion chain (completely separate; no sharing, i.e., "fusion_inplace=False") + self.scratch.refinenet1_aux = _make_fusion_block(features) + self.scratch.refinenet2_aux = _make_fusion_block(features) + self.scratch.refinenet3_aux = _make_fusion_block(features) + self.scratch.refinenet4_aux = _make_fusion_block(features, has_residual=False) + + # Aux pre-head per level (we will only *return final level*) + self.scratch.output_conv1_aux = nn.ModuleList( + [self._make_aux_out1_block(head_features_1) for _ in range(self.aux_levels)] + ) + + # Aux final projection per level + use_ln = True + ln_seq = ( + [Permute((0, 2, 3, 1)), nn.LayerNorm(head_features_2), Permute((0, 3, 1, 2))] + if use_ln + else [] + ) + self.scratch.output_conv2_aux = nn.ModuleList( + [ + nn.Sequential( + nn.Conv2d( + head_features_1 // 2, head_features_2, kernel_size=3, stride=1, padding=1 + ), + *ln_seq, + nn.ReLU(inplace=True), + nn.Conv2d(head_features_2, 7, kernel_size=1, stride=1, padding=0), + ) + for _ in range(self.aux_levels) + ] + ) + + # ------------------------------------------------------------------------- + # Public forward (supports frame chunking for memory) + # ------------------------------------------------------------------------- + + def forward( + self, + feats: List[torch.Tensor], + H: int, + W: int, + patch_start_idx: int, + chunk_size: int = 8, + ) -> Dict[str, torch.Tensor]: + """ + Args: + aggregated_tokens_list: List of 4 tensors [B, S, T, C] from transformer. + images: [B, S, 3, H, W], in [0, 1]. + patch_start_idx: Patch-token start in the token sequence (to drop non-patch tokens). + frames_chunk_size: Optional chunking along S for memory. + + Returns: + Dict[str, Tensor] with keys based on `head_names`, e.g.: + self.head_main, f"{self.head_main}_conf", + self.head_aux, f"{self.head_aux}_conf" + Shapes: + main: [B, S, out_dim, H/down_ratio, W/down_ratio] + main_cf: [B, S, 1, H/down_ratio, W/down_ratio] + aux: [B, S, 7, H/down_ratio, W/down_ratio] + aux_cf: [B, S, 1, H/down_ratio, W/down_ratio] + """ + B, S, N, C = feats[0][0].shape + feats = [feat[0].reshape(B * S, N, C) for feat in feats] + if chunk_size is None or chunk_size >= S: + out_dict = self._forward_impl(feats, H, W, patch_start_idx) + out_dict = {k: v.reshape(B, S, *v.shape[1:]) for k, v in out_dict.items()} + return Dict(out_dict) + out_dicts = [] + for s0 in range(0, B * S, chunk_size): + s1 = min(s0 + chunk_size, B * S) + out_dict = self._forward_impl( + [feat[s0:s1] for feat in feats], + H, + W, + patch_start_idx, + ) + out_dicts.append(out_dict) + out_dict = { + k: torch.cat([out_dict[k] for out_dict in out_dicts], dim=0) + for k in out_dicts[0].keys() + } + out_dict = {k: v.view(B, S, *v.shape[1:]) for k, v in out_dict.items()} + return Dict(out_dict) + + # ------------------------------------------------------------------------- + # Internal forward (single chunk) + # ------------------------------------------------------------------------- + + def _forward_impl( + self, + feats: List[torch.Tensor], + H: int, + W: int, + patch_start_idx: int, + ) -> Dict[str, torch.Tensor]: + B, _, C = feats[0].shape + ph, pw = H // self.patch_size, W // self.patch_size + resized_feats = [] + for stage_idx, take_idx in enumerate(self.intermediate_layer_idx): + x = feats[take_idx][:, patch_start_idx:] + x = self.norm(x) + x = x.permute(0, 2, 1).reshape(B, C, ph, pw) # [B*S, C, ph, pw] + + x = self.projects[stage_idx](x) + if self.pos_embed: + x = self._add_pos_embed(x, W, H) + x = self.resize_layers[stage_idx](x) # align scales + resized_feats.append(x) + + # 2) Fuse pyramid (main & aux are completely independent) + fused_main, fused_aux_pyr = self._fuse(resized_feats) + + # 3) Upsample to target resolution and (optional) add pos-embed again + h_out = int(ph * self.patch_size / self.down_ratio) + w_out = int(pw * self.patch_size / self.down_ratio) + + fused_main = custom_interpolate( + fused_main, (h_out, w_out), mode="bilinear", align_corners=True + ) + if self.pos_embed: + fused_main = self._add_pos_embed(fused_main, W, H) + + # Primary head: conv1 -> conv2 -> activate + # fused_main = self.scratch.output_conv1(fused_main) + main_logits = self.scratch.output_conv2(fused_main) + fmap = main_logits.permute(0, 2, 3, 1) + main_pred = self._apply_activation_single(fmap[..., :-1], self.activation) + main_conf = self._apply_activation_single(fmap[..., -1], self.conf_activation) + + # Auxiliary head (multi-level inside) -> only last level returned (after activation) + last_aux = fused_aux_pyr[-1] + if self.pos_embed: + last_aux = self._add_pos_embed(last_aux, W, H) + # neck (per-level pre-conv) then final projection (only for last level) + # last_aux = self.scratch.output_conv1_aux[-1](last_aux) + last_aux_logits = self.scratch.output_conv2_aux[-1](last_aux) + fmap_last = last_aux_logits.permute(0, 2, 3, 1) + aux_pred = self._apply_activation_single(fmap_last[..., :-1], "linear") + aux_conf = self._apply_activation_single(fmap_last[..., -1], self.conf_activation) + return { + self.head_main: main_pred.squeeze(-1), + f"{self.head_main}_conf": main_conf, + self.head_aux: aux_pred, + f"{self.head_aux}_conf": aux_conf, + } + + # ------------------------------------------------------------------------- + # Subroutines + # ------------------------------------------------------------------------- + + def _fuse(self, feats: List[torch.Tensor]) -> Tuple[torch.Tensor, List[torch.Tensor]]: + """ + Feature pyramid fusion. + Returns: + fused_main: Tensor at finest scale (after refinenet1) + aux_pyr: List of aux tensors at each level (pre out_conv1_aux) + """ + l1, l2, l3, l4 = feats + + l1_rn = self.scratch.layer1_rn(l1) + l2_rn = self.scratch.layer2_rn(l2) + l3_rn = self.scratch.layer3_rn(l3) + l4_rn = self.scratch.layer4_rn(l4) + + # level 4 -> 3 + out = self.scratch.refinenet4(l4_rn, size=l3_rn.shape[2:]) + aux_out = self.scratch.refinenet4_aux(l4_rn, size=l3_rn.shape[2:]) + aux_list: List[torch.Tensor] = [] + if self.aux_levels >= 4: + aux_list.append(aux_out) + + # level 3 -> 2 + out = self.scratch.refinenet3(out, l3_rn, size=l2_rn.shape[2:]) + aux_out = self.scratch.refinenet3_aux(aux_out, l3_rn, size=l2_rn.shape[2:]) + if self.aux_levels >= 3: + aux_list.append(aux_out) + + # level 2 -> 1 + out = self.scratch.refinenet2(out, l2_rn, size=l1_rn.shape[2:]) + aux_out = self.scratch.refinenet2_aux(aux_out, l2_rn, size=l1_rn.shape[2:]) + if self.aux_levels >= 2: + aux_list.append(aux_out) + + # level 1 (final) + out = self.scratch.refinenet1(out, l1_rn) + aux_out = self.scratch.refinenet1_aux(aux_out, l1_rn) + aux_list.append(aux_out) + + out = self.scratch.output_conv1(out) + aux_list = [self.scratch.output_conv1_aux[i](aux) for i, aux in enumerate(aux_list)] + + return out, aux_list + + def _add_pos_embed(self, x: torch.Tensor, W: int, H: int, ratio: float = 0.1) -> torch.Tensor: + """Simple UV positional embedding added to feature maps.""" + pw, ph = x.shape[-1], x.shape[-2] + pe = create_uv_grid(pw, ph, aspect_ratio=W / H, dtype=x.dtype, device=x.device) + pe = position_grid_to_embed(pe, x.shape[1]) * ratio + pe = pe.permute(2, 0, 1)[None].expand(x.shape[0], -1, -1, -1) + return x + pe + + def _make_aux_out1_block(self, in_ch: int) -> nn.Sequential: + """Factory for the aux pre-head stack before the final 1x1 projection.""" + if self.aux_out1_conv_num == 5: + return nn.Sequential( + nn.Conv2d(in_ch, in_ch // 2, 3, 1, 1), + nn.Conv2d(in_ch // 2, in_ch, 3, 1, 1), + nn.Conv2d(in_ch, in_ch // 2, 3, 1, 1), + nn.Conv2d(in_ch // 2, in_ch, 3, 1, 1), + nn.Conv2d(in_ch, in_ch // 2, 3, 1, 1), + ) + if self.aux_out1_conv_num == 3: + return nn.Sequential( + nn.Conv2d(in_ch, in_ch // 2, 3, 1, 1), + nn.Conv2d(in_ch // 2, in_ch, 3, 1, 1), + nn.Conv2d(in_ch, in_ch // 2, 3, 1, 1), + ) + if self.aux_out1_conv_num == 1: + return nn.Sequential(nn.Conv2d(in_ch, in_ch // 2, 3, 1, 1)) + raise ValueError(f"aux_out1_conv_num {self.aux_out1_conv_num} not supported") + + def _apply_activation_single( + self, x: torch.Tensor, activation: str = "linear" + ) -> torch.Tensor: + """ + Apply activation to single channel output, maintaining semantic consistency with value branch in multi-channel case. + Supports: exp / relu / sigmoid / softplus / tanh / linear / expp1 + """ + act = activation.lower() if isinstance(activation, str) else activation + if act == "exp": + return torch.exp(x) + if act == "expm1": + return torch.expm1(x) + if act == "expp1": + return torch.exp(x) + 1 + if act == "relu": + return torch.relu(x) + if act == "sigmoid": + return torch.sigmoid(x) + if act == "softplus": + return torch.nn.functional.softplus(x) + if act == "tanh": + return torch.tanh(x) + # Default linear + return x + + +# # ----------------------------------------------------------------------------- +# # Building blocks (tidy) +# # ----------------------------------------------------------------------------- + + +# def _make_fusion_block( +# features: int, +# size: Tuple[int, int] = None, +# has_residual: bool = True, +# groups: int = 1, +# inplace: bool = False, # <- activation uses inplace=True by default; not related to "fusion_inplace" +# ) -> nn.Module: +# return FeatureFusionBlock( +# features=features, +# activation=nn.ReLU(inplace=inplace), +# deconv=False, +# bn=False, +# expand=False, +# align_corners=True, +# size=size, +# has_residual=has_residual, +# groups=groups, +# ) + + +# def _make_scratch( +# in_shape: List[int], out_shape: int, groups: int = 1, expand: bool = False +# ) -> nn.Module: +# scratch = nn.Module() +# # optionally expand widths by stage +# c1 = out_shape +# c2 = out_shape * (2 if expand else 1) +# c3 = out_shape * (4 if expand else 1) +# c4 = out_shape * (8 if expand else 1) + +# scratch.layer1_rn = nn.Conv2d(in_shape[0], c1, 3, 1, 1, bias=False, groups=groups) +# scratch.layer2_rn = nn.Conv2d(in_shape[1], c2, 3, 1, 1, bias=False, groups=groups) +# scratch.layer3_rn = nn.Conv2d(in_shape[2], c3, 3, 1, 1, bias=False, groups=groups) +# scratch.layer4_rn = nn.Conv2d(in_shape[3], c4, 3, 1, 1, bias=False, groups=groups) +# return scratch + + +# class ResidualConvUnit(nn.Module): +# """Lightweight residual conv block used within fusion.""" + +# def __init__(self, features: int, activation: nn.Module, bn: bool, groups: int = 1) -> None: +# super().__init__() +# self.bn = bn +# self.groups = groups +# self.conv1 = nn.Conv2d(features, features, 3, 1, 1, bias=True, groups=groups) +# self.conv2 = nn.Conv2d(features, features, 3, 1, 1, bias=True, groups=groups) +# self.norm1 = None +# self.norm2 = None +# self.activation = activation +# self.skip_add = nn.quantized.FloatFunctional() + +# def forward(self, x: torch.Tensor) -> torch.Tensor: # type: ignore[override] +# out = self.activation(x) +# out = self.conv1(out) +# if self.norm1 is not None: +# out = self.norm1(out) + +# out = self.activation(out) +# out = self.conv2(out) +# if self.norm2 is not None: +# out = self.norm2(out) + +# return self.skip_add.add(out, x) + + +# class FeatureFusionBlock(nn.Module): +# """Top-down fusion block: (optional) residual merge + upsample + 1x1 shrink.""" + +# def __init__( +# self, +# features: int, +# activation: nn.Module, +# deconv: bool = False, +# bn: bool = False, +# expand: bool = False, +# align_corners: bool = True, +# size: Tuple[int, int] = None, +# has_residual: bool = True, +# groups: int = 1, +# ) -> None: +# super().__init__() +# self.align_corners = align_corners +# self.size = size +# self.has_residual = has_residual + +# self.resConfUnit1 = ( +# ResidualConvUnit(features, activation, bn, groups=groups) if has_residual else None +# ) +# self.resConfUnit2 = ResidualConvUnit(features, activation, bn, groups=groups) + +# out_features = (features // 2) if expand else features +# self.out_conv = nn.Conv2d(features, out_features, 1, 1, 0, bias=True, groups=groups) +# self.skip_add = nn.quantized.FloatFunctional() + +# def forward(self, *xs: torch.Tensor, size: Tuple[int, int] = None) -> torch.Tensor: # type: ignore[override] +# """ +# xs: +# - xs[0]: top input +# - xs[1]: (optional) lateral (to be added with residual) +# """ +# y = xs[0] +# if self.has_residual and len(xs) > 1 and self.resConfUnit1 is not None: +# y = self.skip_add.add(y, self.resConfUnit1(xs[1])) + +# y = self.resConfUnit2(y) + +# # upsample +# if (size is None) and (self.size is None): +# up_kwargs = {"scale_factor": 2} +# elif size is None: +# up_kwargs = {"size": self.size} +# else: +# up_kwargs = {"size": size} + +# y = custom_interpolate(y, **up_kwargs, mode="bilinear", align_corners=self.align_corners) +# y = self.out_conv(y) +# return y diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/gs_adapter.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/gs_adapter.py new file mode 100644 index 0000000000000000000000000000000000000000..1335ce387476c339fdd7a8b3cb5349dfce56a7e0 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/gs_adapter.py @@ -0,0 +1,200 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import Optional +import torch +from einops import einsum, rearrange, repeat +from torch import nn + +from depth_anything_3.model.utils.transform import cam_quat_xyzw_to_world_quat_wxyz +from depth_anything_3.specs import Gaussians +from depth_anything_3.utils.geometry import affine_inverse, get_world_rays, sample_image_grid +from depth_anything_3.utils.pose_align import batch_align_poses_umeyama +from depth_anything_3.utils.sh_helpers import rotate_sh + + +class GaussianAdapter(nn.Module): + + def __init__( + self, + sh_degree: int = 0, + pred_color: bool = False, + pred_offset_depth: bool = False, + pred_offset_xy: bool = True, + gaussian_scale_min: float = 1e-5, + gaussian_scale_max: float = 30.0, + ): + super().__init__() + self.sh_degree = sh_degree + self.pred_color = pred_color + self.pred_offset_depth = pred_offset_depth + self.pred_offset_xy = pred_offset_xy + self.gaussian_scale_min = gaussian_scale_min + self.gaussian_scale_max = gaussian_scale_max + + # Create a mask for the spherical harmonics coefficients. This ensures that at + # initialization, the coefficients are biased towards having a large DC + # component and small view-dependent components. + if not pred_color: + self.register_buffer( + "sh_mask", + torch.ones((self.d_sh,), dtype=torch.float32), + persistent=False, + ) + for degree in range(1, sh_degree + 1): + self.sh_mask[degree**2 : (degree + 1) ** 2] = 0.1 * 0.25**degree + + def forward( + self, + extrinsics: torch.Tensor, # "*#batch 4 4" + intrinsics: torch.Tensor, # "*#batch 3 3" + depths: torch.Tensor, # "*#batch" + opacities: torch.Tensor, # "*#batch" | "*#batch _" + raw_gaussians: torch.Tensor, # "*#batch _" + image_shape: tuple[int, int], + eps: float = 1e-8, + gt_extrinsics: Optional[torch.Tensor] = None, # "*#batch 4 4" + **kwargs, + ) -> Gaussians: + device = extrinsics.device + dtype = raw_gaussians.dtype + H, W = image_shape + b, v = raw_gaussians.shape[:2] + + # get cam2worlds and intr_normed to adapt to 3DGS codebase + cam2worlds = affine_inverse(extrinsics) + intr_normed = intrinsics.clone().detach() + intr_normed[..., 0, :] /= W + intr_normed[..., 1, :] /= H + + # 1. compute 3DGS means + # 1.1) offset the predicted depth if needed + if self.pred_offset_depth: + gs_depths = depths + raw_gaussians[..., -1] + raw_gaussians = raw_gaussians[..., :-1] + else: + gs_depths = depths + # 1.2) align predicted poses with GT if needed + if gt_extrinsics is not None and not torch.equal(extrinsics, gt_extrinsics): + try: + _, _, pose_scales = batch_align_poses_umeyama( + gt_extrinsics.detach().float(), + extrinsics.detach().float(), + ) + except Exception: + pose_scales = torch.ones_like(extrinsics[:, 0, 0, 0]) + pose_scales = torch.clamp(pose_scales, min=1 / 3.0, max=3.0) + cam2worlds[:, :, :3, 3] = cam2worlds[:, :, :3, 3] * rearrange( + pose_scales, "b -> b () ()" + ) # [b, i, j] + gs_depths = gs_depths * rearrange(pose_scales, "b -> b () () ()") # [b, v, h, w] + # 1.3) casting xy in image space + xy_ray, _ = sample_image_grid((H, W), device) + xy_ray = xy_ray[None, None, ...].expand(b, v, -1, -1, -1) # b v h w xy + # offset xy if needed + if self.pred_offset_xy: + pixel_size = 1 / torch.tensor((W, H), dtype=xy_ray.dtype, device=device) + offset_xy = raw_gaussians[..., :2] + xy_ray = xy_ray + offset_xy * pixel_size + raw_gaussians = raw_gaussians[..., 2:] # skip the offset_xy + # 1.4) unproject depth + xy to world ray + origins, directions = get_world_rays( + xy_ray, + repeat(cam2worlds, "b v i j -> b v h w i j", h=H, w=W), + repeat(intr_normed, "b v i j -> b v h w i j", h=H, w=W), + ) + gs_means_world = origins + directions * gs_depths[..., None] + gs_means_world = rearrange(gs_means_world, "b v h w d -> b (v h w) d") + + # 2. compute other GS attributes + scales, rotations, sh = raw_gaussians.split((3, 4, 3 * self.d_sh), dim=-1) + + # 2.1) 3DGS scales + # make the scale invarient to resolution + scale_min = self.gaussian_scale_min + scale_max = self.gaussian_scale_max + scales = scale_min + (scale_max - scale_min) * scales.sigmoid() + pixel_size = 1 / torch.tensor((W, H), dtype=dtype, device=device) + multiplier = self.get_scale_multiplier(intr_normed, pixel_size) + gs_scales = scales * gs_depths[..., None] * multiplier[..., None, None, None] + gs_scales = rearrange(gs_scales, "b v h w d -> b (v h w) d") + + # 2.2) 3DGS quaternion (world space) + # due to historical issue, assume quaternion in order xyzw, not wxyz + # Normalize the quaternion features to yield a valid quaternion. + rotations = rotations / (rotations.norm(dim=-1, keepdim=True) + eps) + # rotate them to world space + cam_quat_xyzw = rearrange(rotations, "b v h w c -> b (v h w) c") + c2w_mat = repeat( + cam2worlds, + "b v i j -> b (v h w) i j", + h=H, + w=W, + ) + world_quat_wxyz = cam_quat_xyzw_to_world_quat_wxyz(cam_quat_xyzw, c2w_mat) + gs_rotations_world = world_quat_wxyz # b (v h w) c + + # 2.3) 3DGS color / SH coefficient (world space) + sh = rearrange(sh, "... (xyz d_sh) -> ... xyz d_sh", xyz=3) + if not self.pred_color: + sh = sh * self.sh_mask + + if self.pred_color or self.sh_degree == 0: + # predict pre-computed color or predict only DC band, no need to transform + gs_sh_world = sh + else: + gs_sh_world = rotate_sh(sh, cam2worlds[:, :, None, None, None, :3, :3]) + gs_sh_world = rearrange(gs_sh_world, "b v h w xyz d_sh -> b (v h w) xyz d_sh") + + # 2.4) 3DGS opacity + gs_opacities = rearrange(opacities, "b v h w ... -> b (v h w) ...") + + return Gaussians( + means=gs_means_world, + harmonics=gs_sh_world, + opacities=gs_opacities, + scales=gs_scales, + rotations=gs_rotations_world, + ) + + def get_scale_multiplier( + self, + intrinsics: torch.Tensor, # "*#batch 3 3" + pixel_size: torch.Tensor, # "*#batch 2" + multiplier: float = 0.1, + ) -> torch.Tensor: # " *batch" + xy_multipliers = multiplier * einsum( + intrinsics[..., :2, :2].float().inverse().to(intrinsics), + pixel_size, + "... i j, j -> ... i", + ) + return xy_multipliers.sum(dim=-1) + + @property + def d_sh(self) -> int: + return 1 if self.pred_color else (self.sh_degree + 1) ** 2 + + @property + def d_in(self) -> int: + # provided as reference to the gs_dpt output dim + raw_gs_dim = 0 + if self.pred_offset_xy: + raw_gs_dim += 2 + raw_gs_dim += 3 # scales + raw_gs_dim += 4 # quaternion + raw_gs_dim += 3 * self.d_sh # color + if self.pred_offset_depth: + raw_gs_dim += 1 + + return raw_gs_dim diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/gsdpt.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/gsdpt.py new file mode 100644 index 0000000000000000000000000000000000000000..70448b7235982a3b47c0c07f15edd4c38677e72e --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/gsdpt.py @@ -0,0 +1,133 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import Dict as TyDict +from typing import List, Sequence +import torch +import torch.nn as nn + +from depth_anything_3.model.dpt import DPT +from depth_anything_3.model.utils.head_utils import activate_head_gs, custom_interpolate + + +class GSDPT(DPT): + + def __init__( + self, + dim_in: int, + patch_size: int = 14, + output_dim: int = 4, + activation: str = "linear", + conf_activation: str = "sigmoid", + features: int = 256, + out_channels: Sequence[int] = (256, 512, 1024, 1024), + pos_embed: bool = True, + feature_only: bool = False, + down_ratio: int = 1, + conf_dim: int = 1, + norm_type: str = "idt", # use to match legacy GS-DPT head, "idt" / "layer" + fusion_block_inplace: bool = False, + ) -> None: + super().__init__( + dim_in=dim_in, + patch_size=patch_size, + output_dim=output_dim, + activation=activation, + conf_activation=conf_activation, + features=features, + out_channels=out_channels, + pos_embed=pos_embed, + down_ratio=down_ratio, + head_name="raw_gs", + use_sky_head=False, + norm_type=norm_type, + fusion_block_inplace=fusion_block_inplace, + ) + self.conf_dim = conf_dim + if conf_dim and conf_dim > 1: + assert ( + conf_activation == "linear" + ), "use linear prediction when using view-dependent opacity" + + merger_out_dim = features if feature_only else features // 2 + self.images_merger = nn.Sequential( + nn.Conv2d(3, merger_out_dim // 4, 3, 1, 1), # fewer channels first + nn.GELU(), + nn.Conv2d(merger_out_dim // 4, merger_out_dim // 2, 3, 1, 1), + nn.GELU(), + nn.Conv2d(merger_out_dim // 2, merger_out_dim, 3, 1, 1), + nn.GELU(), + ) + + # ------------------------------------------------------------------------- + # Internal forward (single chunk) + # ------------------------------------------------------------------------- + def _forward_impl( + self, + feats: List[torch.Tensor], + H: int, + W: int, + patch_start_idx: int, + images: torch.Tensor, + ) -> TyDict[str, torch.Tensor]: + B, _, C = feats[0].shape + ph, pw = H // self.patch_size, W // self.patch_size + resized_feats = [] + for stage_idx, take_idx in enumerate(self.intermediate_layer_idx): + x = feats[take_idx][:, patch_start_idx:] # [B*S, N_patch, C] + x = self.norm(x) + x = x.permute(0, 2, 1).reshape(B, C, ph, pw) # [B*S, C, ph, pw] + + x = self.projects[stage_idx](x) + if self.pos_embed: + x = self._add_pos_embed(x, W, H) + x = self.resize_layers[stage_idx](x) # Align scale + resized_feats.append(x) + + # 2) Fusion pyramid (main branch only) + fused = self._fuse(resized_feats) + fused = self.scratch.output_conv1(fused) + + # 3) Upsample to target resolution, optionally add position encoding again + h_out = int(ph * self.patch_size / self.down_ratio) + w_out = int(pw * self.patch_size / self.down_ratio) + + fused = custom_interpolate(fused, (h_out, w_out), mode="bilinear", align_corners=True) + + # inject the image information here + fused = fused + self.images_merger(images) + + if self.pos_embed: + fused = self._add_pos_embed(fused, W, H) + + # 4) Shared neck1 + # feat = self.scratch.output_conv1(fused) + feat = fused + + # 5) Main head: logits -> activate_head or single channel activation + main_logits = self.scratch.output_conv2(feat) + outs: TyDict[str, torch.Tensor] = {} + if self.has_conf: + pred, conf = activate_head_gs( + main_logits, + activation=self.activation, + conf_activation=self.conf_activation, + conf_dim=self.conf_dim, + ) + outs[self.head_main] = pred.squeeze(1) + outs[f"{self.head_main}_conf"] = conf.squeeze(1) + else: + outs[self.head_main] = self._apply_activation_single(main_logits).squeeze(1) + + return outs diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/reference_view_selector.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/reference_view_selector.py new file mode 100644 index 0000000000000000000000000000000000000000..f406f5ff2e0dad5ce2d12f3a1d3919773fc21e66 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/reference_view_selector.py @@ -0,0 +1,223 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Reference View Selection Strategies + +This module provides different strategies for selecting a reference view +from multiple input views in multi-view depth estimation. +""" + +import torch +from typing import Literal + + +RefViewStrategy = Literal["first", "middle", "saddle_balanced", "saddle_sim_range"] + + +def select_reference_view( + x: torch.Tensor, + strategy: RefViewStrategy = "saddle_balanced", +) -> torch.Tensor: + """ + Select a reference view from multiple views using the specified strategy. + + Args: + x: Input tensor of shape (B, S, N, C) where + B = batch size + S = number of views + N = number of tokens + C = channel dimension + strategy: Selection strategy, one of: + - "first": Always select the first view + - "middle": Select the middle view + - "saddle_balanced": Select view with balanced features across multiple metrics + - "saddle_sim_range": Select view with largest similarity range + + Returns: + b_idx: Tensor of shape (B,) containing the selected view index for each batch + """ + B, S, N, C = x.shape + + # For single view, no reordering needed + if S <= 1: + return torch.zeros(B, dtype=torch.long, device=x.device) + + # Simple position-based strategies + if strategy == "first": + return torch.zeros(B, dtype=torch.long, device=x.device) + + elif strategy == "middle": + return torch.full((B,), S // 2, dtype=torch.long, device=x.device) + + # Feature-based strategies require normalized class tokens + # Extract and normalize class tokens (first token of each view) + img_class_feat = x[:, :, 0] / x[:, :, 0].norm(dim=-1, keepdim=True) # B S C + + if strategy == "saddle_balanced": + # Select view with balanced features across multiple metrics + # Compute similarity matrix + sim = torch.matmul(img_class_feat, img_class_feat.transpose(1, 2)) # B S S + sim_no_diag = sim - torch.eye(S, device=sim.device).unsqueeze(0) + sim_score = sim_no_diag.sum(dim=-1) / (S - 1) # B S + + feat_norm = x[:, :, 0].norm(dim=-1) # B S + feat_var = img_class_feat.var(dim=-1) # B S + + # Normalize all metrics to [0, 1] + def normalize_metric(metric): + min_val = metric.min(dim=1, keepdim=True).values + max_val = metric.max(dim=1, keepdim=True).values + return (metric - min_val) / (max_val - min_val + 1e-8) + + sim_score_norm = normalize_metric(sim_score) + norm_norm = normalize_metric(feat_norm) + var_norm = normalize_metric(feat_var) + + # Select view closest to the median (0.5) across all metrics + balance_score = ( + (sim_score_norm - 0.5).abs() + + (norm_norm - 0.5).abs() + + (var_norm - 0.5).abs() + ) + b_idx = balance_score.argmin(dim=1) + + elif strategy == "saddle_sim_range": + # Select view with largest similarity range (max - min) + sim = torch.matmul(img_class_feat, img_class_feat.transpose(1, 2)) # B S S + sim_no_diag = sim - torch.eye(S, device=sim.device).unsqueeze(0) + + sim_max = sim_no_diag.max(dim=-1).values # B S + sim_min = sim_no_diag.min(dim=-1).values # B S + sim_range = sim_max - sim_min + b_idx = sim_range.argmax(dim=1) + + else: + raise ValueError( + f"Unknown reference view selection strategy: {strategy}. " + f"Must be one of: 'first', 'middle', 'saddle_balanced', 'saddle_sim_range'" + ) + + return b_idx + + +def reorder_by_reference( + x: torch.Tensor, + b_idx: torch.Tensor, +) -> torch.Tensor: + """ + Reorder views to place the selected reference view first. + + Args: + x: Input tensor of shape (B, S, N, C) + b_idx: Reference view indices of shape (B,) + + Returns: + Reordered tensor with reference view at position 0 + + Example: + If b_idx = [2] and S = 5 (views [0,1,2,3,4]), + result order is [2,0,1,3,4] (ref_idx first, then others in order) + """ + B, S = x.shape[0], x.shape[1] + + # For single view, no reordering needed + if S <= 1: + return x + + # Create position indices: (B, S) where each row is [0, 1, 2, ..., S-1] + positions = torch.arange(S, device=x.device).unsqueeze(0).expand(B, -1) # B S + + # For each position, determine which original index it should take + # Position 0 gets ref_idx + # Position 1 to ref_idx gets indices 0 to ref_idx-1 + # Position ref_idx+1 to S-1 gets indices ref_idx+1 to S-1 + + b_idx_expanded = b_idx.unsqueeze(1) # B 1 + + # Create the reordering indices + # For positions 1 to ref_idx: map to indices 0 to ref_idx-1 (shift by -1) + # For positions > ref_idx: keep the same + reorder_indices = positions.clone() + reorder_indices = torch.where( + (positions > 0) & (positions <= b_idx_expanded), + positions - 1, + positions + ) + # Set position 0 to ref_idx + reorder_indices[:, 0] = b_idx + + # Gather using advanced indexing + batch_indices = torch.arange(B, device=x.device).unsqueeze(1) # B 1 + x_reordered = x[batch_indices, reorder_indices] + + return x_reordered + + +def restore_original_order( + x: torch.Tensor, + b_idx: torch.Tensor, +) -> torch.Tensor: + """ + Restore original view order after processing. + + Args: + x: Reordered tensor of shape (B, S, ...) + b_idx: Original reference view indices of shape (B,) + + Returns: + Tensor with original view order restored + + Example: + If original order was [0, 1, 2, 3, 4] and b_idx=2, + reordered becomes [2, 0, 1, 3, 4] (reference at position 0), + restore should return [0, 1, 2, 3, 4] (original order). + """ + B, S = x.shape[0], x.shape[1] + + # For single view, no restoration needed + if S <= 1: + return x + + # Create target position indices: (B, S) where each row is [0, 1, 2, ..., S-1] + target_positions = torch.arange(S, device=x.device).unsqueeze(0).expand(B, -1) # B S + + # For each target position, determine which current position it comes from + # Target position 0 to ref_idx-1 <- Current position 1 to ref_idx (shift by +1) + # Target position ref_idx <- Current position 0 + # Target position ref_idx+1 to S-1 <- Current position ref_idx+1 to S-1 (no change) + + b_idx_expanded = b_idx.unsqueeze(1) # B 1 + + # Create the restore indices + restore_indices = torch.where( + target_positions < b_idx_expanded, + target_positions + 1, # Positions before ref_idx come from current position + 1 + target_positions # Positions after ref_idx stay the same + ) + # Target position = ref_idx comes from current position 0 + # Use scatter to set specific positions + restore_indices = torch.scatter( + restore_indices, + dim=1, + index=b_idx_expanded, + src=torch.zeros_like(b_idx_expanded) + ) + + # Gather using advanced indexing + batch_indices = torch.arange(B, device=x.device).unsqueeze(1) # B 1 + x_restored = x[batch_indices, restore_indices] + + return x_restored + diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/utils/attention.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/utils/attention.py new file mode 100644 index 0000000000000000000000000000000000000000..49c07a8c5e5c65fc8e0700aab9ae660552dba610 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/utils/attention.py @@ -0,0 +1,109 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Modified from: https://github.com/huggingface/pytorch-image-models/blob/main/timm/models/vision_transformer.py#L103-L110 # noqa + +from typing import Callable, Optional, Union +import torch +import torch.nn.functional as F +from torch import Tensor, nn + + +class Attention(nn.Module): + def __init__( + self, + dim: int, + num_heads: int = 8, + qkv_bias: bool = True, + proj_bias: bool = True, + attn_drop: float = 0.0, + proj_drop: float = 0.0, + norm_layer: nn.Module = nn.LayerNorm, + qk_norm: bool = False, + rope=None, + ) -> None: + super().__init__() + assert dim % num_heads == 0, "dim should be divisible by num_heads" + self.num_heads = num_heads + self.head_dim = dim // num_heads + self.scale = self.head_dim**-0.5 + self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) + self.q_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity() + self.k_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity() + self.attn_drop = nn.Dropout(attn_drop) + self.proj = nn.Linear(dim, dim, bias=proj_bias) + self.proj_drop = nn.Dropout(proj_drop) + self.rope = rope + + def forward(self, x: Tensor, pos=None, attn_mask=None) -> Tensor: + # Debug breakpoint removed for production + B, N, C = x.shape + qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4) + q, k, v = qkv.unbind(0) + q, k = self.q_norm(q), self.k_norm(k) + q = self.rope(q, pos) if self.rope is not None else q + k = self.rope(k, pos) if self.rope is not None else k + x = F.scaled_dot_product_attention( + q, + k, + v, + dropout_p=self.attn_drop.p if self.training else 0.0, + attn_mask=attn_mask, + ) + x = x.transpose(1, 2).reshape(B, N, C) + x = self.proj(x) + x = self.proj_drop(x) + return x + + +class LayerScale(nn.Module): + def __init__( + self, + dim: int, + init_values: Union[float, Tensor] = 1e-5, + inplace: bool = False, + ) -> None: + super().__init__() + self.inplace = inplace + self.gamma = nn.Parameter(init_values * torch.ones(dim)) + + def forward(self, x: Tensor) -> Tensor: + return x.mul_(self.gamma) if self.inplace else x * self.gamma + + +class Mlp(nn.Module): + def __init__( + self, + in_features: int, + hidden_features: Optional[int] = None, + out_features: Optional[int] = None, + act_layer: Callable[..., nn.Module] = nn.GELU, + drop: float = 0.0, + bias: bool = True, + ) -> None: + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features + self.fc1 = nn.Linear(in_features, hidden_features, bias=bias) + self.act = act_layer() + self.fc2 = nn.Linear(hidden_features, out_features, bias=bias) + self.drop = nn.Dropout(drop) + + def forward(self, x: Tensor) -> Tensor: + x = self.fc1(x) + x = self.act(x) + x = self.drop(x) + x = self.fc2(x) + x = self.drop(x) + return x diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/utils/block.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/utils/block.py new file mode 100644 index 0000000000000000000000000000000000000000..993fb4c0bdc02bd0976a6471adf1a15452d0f5c0 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/utils/block.py @@ -0,0 +1,81 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +from typing import Callable +from torch import Tensor, nn + +from .attention import Attention, LayerScale, Mlp + + +class Block(nn.Module): + def __init__( + self, + dim: int, + num_heads: int, + mlp_ratio: float = 4.0, + qkv_bias: bool = True, + proj_bias: bool = True, + ffn_bias: bool = True, + drop: float = 0.0, + attn_drop: float = 0.0, + init_values=None, + drop_path: float = 0.0, + act_layer: Callable[..., nn.Module] = nn.GELU, + norm_layer: Callable[..., nn.Module] = nn.LayerNorm, + attn_class: Callable[..., nn.Module] = Attention, + ffn_layer: Callable[..., nn.Module] = Mlp, + qk_norm: bool = False, + rope=None, + ) -> None: + super().__init__() + + self.norm1 = norm_layer(dim) + + self.attn = attn_class( + dim, + num_heads=num_heads, + qkv_bias=qkv_bias, + proj_bias=proj_bias, + attn_drop=attn_drop, + proj_drop=drop, + qk_norm=qk_norm, + rope=rope, + ) + + self.ls1 = LayerScale(dim, init_values=init_values) if init_values else nn.Identity() + self.norm2 = norm_layer(dim) + mlp_hidden_dim = int(dim * mlp_ratio) + self.mlp = ffn_layer( + in_features=dim, + hidden_features=mlp_hidden_dim, + act_layer=act_layer, + drop=drop, + bias=ffn_bias, + ) + self.ls2 = LayerScale(dim, init_values=init_values) if init_values else nn.Identity() + + self.sample_drop_ratio = 0.0 # Equivalent to always having drop_path=0 + + def forward(self, x: Tensor, pos=None, attn_mask=None) -> Tensor: + def attn_residual_func(x: Tensor, pos=None, attn_mask=None) -> Tensor: + return self.ls1(self.attn(self.norm1(x), pos=pos, attn_mask=attn_mask)) + + def ffn_residual_func(x: Tensor) -> Tensor: + return self.ls2(self.mlp(self.norm2(x))) + + # drop_path is always 0, so always take the else branch + x = x + attn_residual_func(x, pos=pos, attn_mask=attn_mask) + x = x + ffn_residual_func(x) + return x diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/utils/gs_renderer.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/utils/gs_renderer.py new file mode 100644 index 0000000000000000000000000000000000000000..91414d38e84cc030af5207682d06135eec72b125 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/utils/gs_renderer.py @@ -0,0 +1,340 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import math +from math import isqrt +from typing import Literal, Optional +import torch +from einops import rearrange, repeat +from tqdm import tqdm + +from depth_anything_3.specs import Gaussians +from depth_anything_3.utils.camera_trj_helpers import ( + interpolate_extrinsics, + interpolate_intrinsics, + render_dolly_zoom_path, + render_stabilization_path, + render_wander_path, + render_wobble_inter_path, +) +from depth_anything_3.utils.geometry import affine_inverse, as_homogeneous, get_fov +from depth_anything_3.utils.logger import logger + +try: + from gsplat import rasterization +except ImportError: + logger.warn( + "Dependency `gsplat` is required for rendering 3DGS. " + "Install via: pip install git+https://github.com/nerfstudio-project/" + "gsplat.git@0b4dddf04cb687367602c01196913cde6a743d70" + ) + + +def render_3dgs( + extrinsics: torch.Tensor, # "batch_views 4 4", w2c + intrinsics: torch.Tensor, # "batch_views 3 3", normalized + image_shape: tuple[int, int], + gaussian: Gaussians, + background_color: Optional[torch.Tensor] = None, # "batch_views 3" + use_sh: bool = True, + num_view: int = 1, + color_mode: Literal["RGB+D", "RGB+ED"] = "RGB+D", + **kwargs, +) -> tuple[ + torch.Tensor, # "batch_views 3 height width" + torch.Tensor, # "batch_views height width" +]: + # extract gaussian params + gaussian_means = gaussian.means + gaussian_scales = gaussian.scales + gaussian_quats = gaussian.rotations + gaussian_opacities = gaussian.opacities + gaussian_sh_coefficients = gaussian.harmonics + b, _, _ = extrinsics.shape + + if background_color is None: + background_color = repeat(torch.tensor([0.0, 0.0, 0.0]), "c -> b c", b=b).to( + gaussian_sh_coefficients + ) + + if use_sh: + _, _, _, n = gaussian_sh_coefficients.shape + degree = isqrt(n) - 1 + shs = rearrange(gaussian_sh_coefficients, "b g xyz n -> b g n xyz").contiguous() + else: # use color + shs = ( + gaussian_sh_coefficients.squeeze(-1).sigmoid().contiguous() + ) # (b, g, c), normed to (0, 1) + + h, w = image_shape + + fov_x, fov_y = get_fov(intrinsics).unbind(dim=-1) + tan_fov_x = (0.5 * fov_x).tan() + tan_fov_y = (0.5 * fov_y).tan() + focal_length_x = w / (2 * tan_fov_x) + focal_length_y = h / (2 * tan_fov_y) + + view_matrix = extrinsics.float() + + all_images = [] + all_radii = [] + all_depths = [] + # render view in a batch based, each batch contains one scene + # assume the Gaussian parameters are originally repeated along the view dim + batch_scene = b // num_view + + def index_i_gs_attr(full_attr, idx): + # return rearrange(full_attr, "(b v) ... -> b v ...", v=num_view)[idx, 0] + return full_attr[idx] + + for i in range(batch_scene): + K = repeat( + torch.tensor( + [ + [0, 0, w / 2.0], + [0, 0, h / 2.0], + [0, 0, 1], + ] + ), + "i j -> v i j", + v=num_view, + ).to(gaussian_means) + K[:, 0, 0] = focal_length_x.reshape(batch_scene, num_view)[i] + K[:, 1, 1] = focal_length_y.reshape(batch_scene, num_view)[i] + + i_means = index_i_gs_attr(gaussian_means, i) # [N, 3] + i_scales = index_i_gs_attr(gaussian_scales, i) + i_quats = index_i_gs_attr(gaussian_quats, i) + i_opacities = index_i_gs_attr(gaussian_opacities, i) # [N,] + i_colors = index_i_gs_attr(shs, i) # [N, K, 3] + i_viewmats = rearrange(view_matrix, "(b v) ... -> b v ...", v=num_view)[i] # [v, 4, 4] + i_backgrounds = rearrange(background_color, "(b v) ... -> b v ...", v=num_view)[ + i + ] # [v, 3] + + render_colors, render_alphas, info = rasterization( + means=i_means, + quats=i_quats, # [N, 4] + scales=i_scales, # [N, 3] + opacities=i_opacities, + colors=i_colors, + viewmats=i_viewmats, # [v, 4, 4] + Ks=K, # [v, 3, 3] + backgrounds=i_backgrounds, + render_mode=color_mode, + width=w, + height=h, + packed=False, + sh_degree=degree if use_sh else None, + ) + depth = render_colors[..., -1].unbind(dim=0) + + image = rearrange(render_colors[..., :3], "v h w c -> v c h w").unbind(dim=0) + radii = info["radii"].unbind(dim=0) + try: + info["means2d"].retain_grad() # [1, N, 2] + except Exception: + pass + all_images.extend(image) + all_depths.extend(depth) + all_radii.extend(radii) + + return torch.stack(all_images), torch.stack(all_depths) + + +def run_renderer_in_chunk_w_trj_mode( + gaussians: Gaussians, + extrinsics: torch.Tensor, # world2cam, "batch view 4 4" | "batch view 3 4" + intrinsics: torch.Tensor, # unnormed intrinsics, "batch view 3 3" + image_shape: tuple[int, int], + chunk_size: Optional[int] = 8, + trj_mode: Literal[ + "original", + "smooth", + "interpolate", + "interpolate_smooth", + "wander", + "dolly_zoom", + "extend", + "wobble_inter", + ] = "smooth", + input_shape: Optional[tuple[int, int]] = None, + enable_tqdm: Optional[bool] = False, + **kwargs, +) -> tuple[ + torch.Tensor, # color, "batch view 3 height width" + torch.Tensor, # depth, "batch view height width" +]: + cam2world = affine_inverse(as_homogeneous(extrinsics)) + if input_shape is not None: + in_h, in_w = input_shape + else: + in_h, in_w = image_shape + intr_normed = intrinsics.clone().detach() + intr_normed[..., 0, :] /= in_w + intr_normed[..., 1, :] /= in_h + if extrinsics.shape[1] <= 1: + assert trj_mode in [ + "wander", + "dolly_zoom", + ], "Please set trj_mode to 'wander' or 'dolly_zoom' when n_views=1" + + def _smooth_trj_fn_batch(raw_c2ws, k_size=50): + try: + smooth_c2ws = torch.stack( + [render_stabilization_path(c2w_i, k_size) for c2w_i in raw_c2ws], + dim=0, + ) + except Exception as e: + print(f"[DEBUG] Path smoothing failed with error: {e}.") + smooth_c2ws = raw_c2ws + return smooth_c2ws + + # get rendered trj + if trj_mode == "original": + tgt_c2w = cam2world + tgt_intr = intr_normed + elif trj_mode == "smooth": + tgt_c2w = _smooth_trj_fn_batch(cam2world) + tgt_intr = intr_normed + elif trj_mode in ["interpolate", "interpolate_smooth", "extend"]: + inter_len = 8 + total_len = (cam2world.shape[1] - 1) * inter_len + if total_len > 24 * 18: # no more than 18s + inter_len = max(1, 24 * 10 // (cam2world.shape[1] - 1)) + if total_len < 24 * 2: # no less than 2s + inter_len = max(1, 24 * 2 // (cam2world.shape[1] - 1)) + + if inter_len > 2: + t = torch.linspace(0, 1, inter_len, dtype=torch.float32, device=cam2world.device) + t = (torch.cos(torch.pi * (t + 1)) + 1) / 2 + tgt_c2w_b = [] + tgt_intr_b = [] + for b_idx in range(cam2world.shape[0]): + tgt_c2w = [] + tgt_intr = [] + for cur_idx in range(cam2world.shape[1] - 1): + tgt_c2w.append( + interpolate_extrinsics( + cam2world[b_idx, cur_idx], cam2world[b_idx, cur_idx + 1], t + )[(0 if cur_idx == 0 else 1) :] + ) + tgt_intr.append( + interpolate_intrinsics( + intr_normed[b_idx, cur_idx], intr_normed[b_idx, cur_idx + 1], t + )[(0 if cur_idx == 0 else 1) :] + ) + tgt_c2w_b.append(torch.cat(tgt_c2w)) + tgt_intr_b.append(torch.cat(tgt_intr)) + tgt_c2w = torch.stack(tgt_c2w_b) # b v 4 4 + tgt_intr = torch.stack(tgt_intr_b) # b v 3 3 + else: + tgt_c2w = cam2world + tgt_intr = intr_normed + if trj_mode in ["interpolate_smooth", "extend"]: + tgt_c2w = _smooth_trj_fn_batch(tgt_c2w) + if trj_mode == "extend": + # apply dolly_zoom and wander in the middle frame + assert cam2world.shape[0] == 1, "extend only supports for batch_size=1 currently." + mid_idx = tgt_c2w.shape[1] // 2 + c2w_wd, intr_wd = render_wander_path( + tgt_c2w[0, mid_idx], + tgt_intr[0, mid_idx], + h=in_h, + w=in_w, + num_frames=max(36, min(60, mid_idx // 2)), + max_disp=24.0, + ) + c2w_dz, intr_dz = render_dolly_zoom_path( + tgt_c2w[0, mid_idx], + tgt_intr[0, mid_idx], + h=in_h, + w=in_w, + num_frames=max(36, min(60, mid_idx // 2)), + ) + tgt_c2w = torch.cat( + [ + tgt_c2w[:, :mid_idx], + c2w_wd.unsqueeze(0), + c2w_dz.unsqueeze(0), + tgt_c2w[:, mid_idx:], + ], + dim=1, + ) + tgt_intr = torch.cat( + [ + tgt_intr[:, :mid_idx], + intr_wd.unsqueeze(0), + intr_dz.unsqueeze(0), + tgt_intr[:, mid_idx:], + ], + dim=1, + ) + elif trj_mode in ["wander", "dolly_zoom"]: + if trj_mode == "wander": + render_fn = render_wander_path + extra_kwargs = {"max_disp": 24.0} + else: + render_fn = render_dolly_zoom_path + extra_kwargs = {"D_focus": 30.0, "max_disp": 2.0} + tgt_c2w = [] + tgt_intr = [] + for b_idx in range(cam2world.shape[0]): + c2w_i, intr_i = render_fn( + cam2world[b_idx, 0], intr_normed[b_idx, 0], h=in_h, w=in_w, **extra_kwargs + ) + tgt_c2w.append(c2w_i) + tgt_intr.append(intr_i) + tgt_c2w = torch.stack(tgt_c2w) + tgt_intr = torch.stack(tgt_intr) + elif trj_mode == "wobble_inter": + tgt_c2w, tgt_intr = render_wobble_inter_path( + cam2world=cam2world, + intr_normed=intr_normed, + inter_len=10, + n_skip=3, + ) + else: + raise Exception(f"trj mode [{trj_mode}] is not implemented.") + + _, v = tgt_c2w.shape[:2] + tgt_extr = affine_inverse(tgt_c2w) + if chunk_size is None: + chunk_size = v + chunk_size = min(v, chunk_size) + all_colors = [] + all_depths = [] + for chunk_idx in tqdm( + range(math.ceil(v / chunk_size)), + desc="Rendering novel views", + disable=(not enable_tqdm), + leave=False, + ): + s = int(chunk_idx * chunk_size) + e = int((chunk_idx + 1) * chunk_size) + cur_n_view = tgt_extr[:, s:e].shape[1] + color, depth = render_3dgs( + extrinsics=rearrange(tgt_extr[:, s:e], "b v ... -> (b v) ..."), # w2c + intrinsics=rearrange(tgt_intr[:, s:e], "b v ... -> (b v) ..."), # normed + image_shape=image_shape, + gaussian=gaussians, + num_view=cur_n_view, + **kwargs, + ) + all_colors.append(rearrange(color, "(b v) ... -> b v ...", v=cur_n_view)) + all_depths.append(rearrange(depth, "(b v) ... -> b v ...", v=cur_n_view)) + all_colors = torch.cat(all_colors, dim=1) + all_depths = torch.cat(all_depths, dim=1) + + return all_colors, all_depths diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/utils/head_utils.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/utils/head_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..c1209582bc6e9b1658a0358df03f5ea79fe61daf --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/utils/head_utils.py @@ -0,0 +1,230 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import Tuple, Union +import torch +import torch.nn as nn +import torch.nn.functional as F + +# ----------------------------------------------------------------------------- +# Activation functions +# ----------------------------------------------------------------------------- + + +def activate_head_gs(out, activation="norm_exp", conf_activation="expp1", conf_dim=None): + """ + Process network output to extract GS params and density values. + Density could be view-dependent as SH coefficient + + + Args: + out: Network output tensor (B, C, H, W) + activation: Activation type for 3D points + conf_activation: Activation type for confidence values + + Returns: + Tuple of (3D points tensor, confidence tensor) + """ + # Move channels from last dim to the 4th dimension => (B, H, W, C) + fmap = out.permute(0, 2, 3, 1) # B,H,W,C expected + + # Split into xyz (first C-1 channels) and confidence (last channel) + conf_dim = 1 if conf_dim is None else conf_dim + xyz = fmap[:, :, :, :-conf_dim] + conf = fmap[:, :, :, -1] if conf_dim == 1 else fmap[:, :, :, -conf_dim:] + + if activation == "norm_exp": + d = xyz.norm(dim=-1, keepdim=True).clamp(min=1e-8) + xyz_normed = xyz / d + pts3d = xyz_normed * torch.expm1(d) + elif activation == "norm": + pts3d = xyz / xyz.norm(dim=-1, keepdim=True) + elif activation == "exp": + pts3d = torch.exp(xyz) + elif activation == "relu": + pts3d = F.relu(xyz) + elif activation == "sigmoid": + pts3d = torch.sigmoid(xyz) + elif activation == "linear": + pts3d = xyz + else: + raise ValueError(f"Unknown activation: {activation}") + + if conf_activation == "expp1": + conf_out = 1 + conf.exp() + elif conf_activation == "expp0": + conf_out = conf.exp() + elif conf_activation == "sigmoid": + conf_out = torch.sigmoid(conf) + elif conf_activation == "linear": + conf_out = conf + else: + raise ValueError(f"Unknown conf_activation: {conf_activation}") + + return pts3d, conf_out + + +# ----------------------------------------------------------------------------- +# Other utilities +# ----------------------------------------------------------------------------- + + +class Permute(nn.Module): + """nn.Module wrapper around Tensor.permute for cleaner nn.Sequential usage.""" + + dims: Tuple[int, ...] + + def __init__(self, dims: Tuple[int, ...]) -> None: + super().__init__() + self.dims = dims + + def forward(self, x: torch.Tensor) -> torch.Tensor: # type: ignore[override] + return x.permute(*self.dims) + + +def position_grid_to_embed( + pos_grid: torch.Tensor, embed_dim: int, omega_0: float = 100 +) -> torch.Tensor: + """ + Convert 2D position grid (HxWx2) to sinusoidal embeddings (HxWxC) + + Args: + pos_grid: Tensor of shape (H, W, 2) containing 2D coordinates + embed_dim: Output channel dimension for embeddings + + Returns: + Tensor of shape (H, W, embed_dim) with positional embeddings + """ + H, W, grid_dim = pos_grid.shape + assert grid_dim == 2 + pos_flat = pos_grid.reshape(-1, grid_dim) # Flatten to (H*W, 2) + + # Process x and y coordinates separately + emb_x = make_sincos_pos_embed(embed_dim // 2, pos_flat[:, 0], omega_0=omega_0) # [1, H*W, D/2] + emb_y = make_sincos_pos_embed(embed_dim // 2, pos_flat[:, 1], omega_0=omega_0) # [1, H*W, D/2] + + # Combine and reshape + emb = torch.cat([emb_x, emb_y], dim=-1) # [1, H*W, D] + + return emb.view(H, W, embed_dim) # [H, W, D] + + +def make_sincos_pos_embed(embed_dim: int, pos: torch.Tensor, omega_0: float = 100) -> torch.Tensor: + """ + This function generates a 1D positional embedding from a given grid using sine and cosine functions. # noqa + + Args: + - embed_dim: The embedding dimension. + - pos: The position to generate the embedding from. + + Returns: + - emb: The generated 1D positional embedding. + """ + assert embed_dim % 2 == 0 + omega = torch.arange(embed_dim // 2, dtype=torch.float32, device=pos.device) + omega /= embed_dim / 2.0 + omega = 1.0 / omega_0**omega # (D/2,) + + pos = pos.reshape(-1) # (M,) + out = torch.einsum("m,d->md", pos, omega) # (M, D/2), outer product + + emb_sin = torch.sin(out) # (M, D/2) + emb_cos = torch.cos(out) # (M, D/2) + + emb = torch.cat([emb_sin, emb_cos], dim=1) # (M, D) + return emb.float() + + +# Inspired by https://github.com/microsoft/moge + + +def create_uv_grid( + width: int, + height: int, + aspect_ratio: float = None, + dtype: torch.dtype = None, + device: torch.device = None, +) -> torch.Tensor: + """ + Create a normalized UV grid of shape (width, height, 2). + + The grid spans horizontally and vertically according to an aspect ratio, + ensuring the top-left corner is at (-x_span, -y_span) and the bottom-right + corner is at (x_span, y_span), normalized by the diagonal of the plane. + + Args: + width (int): Number of points horizontally. + height (int): Number of points vertically. + aspect_ratio (float, optional): Width-to-height ratio. Defaults to width/height. + dtype (torch.dtype, optional): Data type of the resulting tensor. + device (torch.device, optional): Device on which the tensor is created. + + Returns: + torch.Tensor: A (width, height, 2) tensor of UV coordinates. + """ + # Derive aspect ratio if not explicitly provided + if aspect_ratio is None: + aspect_ratio = float(width) / float(height) + + # Compute normalized spans for X and Y + diag_factor = (aspect_ratio**2 + 1.0) ** 0.5 + span_x = aspect_ratio / diag_factor + span_y = 1.0 / diag_factor + + # Establish the linspace boundaries + left_x = -span_x * (width - 1) / width + right_x = span_x * (width - 1) / width + top_y = -span_y * (height - 1) / height + bottom_y = span_y * (height - 1) / height + + # Generate 1D coordinates + x_coords = torch.linspace(left_x, right_x, steps=width, dtype=dtype, device=device) + y_coords = torch.linspace(top_y, bottom_y, steps=height, dtype=dtype, device=device) + + # Create 2D meshgrid (width x height) and stack into UV + uu, vv = torch.meshgrid(x_coords, y_coords, indexing="xy") + uv_grid = torch.stack((uu, vv), dim=-1) + + return uv_grid + + +# ----------------------------------------------------------------------------- +# Interpolation (safe interpolation, avoid INT_MAX overflow) +# ----------------------------------------------------------------------------- +def custom_interpolate( + x: torch.Tensor, + size: Union[Tuple[int, int], None] = None, + scale_factor: Union[float, None] = None, + mode: str = "bilinear", + align_corners: bool = True, +) -> torch.Tensor: + """ + Safe interpolation implementation to avoid INT_MAX overflow in torch.nn.functional.interpolate. + """ + if size is None: + assert scale_factor is not None, "Either size or scale_factor must be provided." + size = (int(x.shape[-2] * scale_factor), int(x.shape[-1] * scale_factor)) + + INT_MAX = 1610612736 + total = size[0] * size[1] * x.shape[0] * x.shape[1] + + if total > INT_MAX: + chunks = torch.chunk(x, chunks=(total // INT_MAX) + 1, dim=0) + outs = [ + nn.functional.interpolate(c, size=size, mode=mode, align_corners=align_corners) + for c in chunks + ] + return torch.cat(outs, dim=0).contiguous() + + return nn.functional.interpolate(x, size=size, mode=mode, align_corners=align_corners) diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/utils/transform.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/utils/transform.py new file mode 100644 index 0000000000000000000000000000000000000000..8d732b093e5ad1578bc0ba5eb0e31b1b69b766ed --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/model/utils/transform.py @@ -0,0 +1,208 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import torch +import torch.nn.functional as F + + +def extri_intri_to_pose_encoding( + extrinsics, + intrinsics, + image_size_hw=None, +): + """Convert camera extrinsics and intrinsics to a compact pose encoding.""" + + # extrinsics: BxSx3x4 + # intrinsics: BxSx3x3 + R = extrinsics[:, :, :3, :3] # BxSx3x3 + T = extrinsics[:, :, :3, 3] # BxSx3 + + quat = mat_to_quat(R) + # Note the order of h and w here + H, W = image_size_hw + fov_h = 2 * torch.atan((H / 2) / intrinsics[..., 1, 1]) + fov_w = 2 * torch.atan((W / 2) / intrinsics[..., 0, 0]) + pose_encoding = torch.cat([T, quat, fov_h[..., None], fov_w[..., None]], dim=-1).float() + + return pose_encoding + + +def pose_encoding_to_extri_intri( + pose_encoding, + image_size_hw=None, +): + """Convert a pose encoding back to camera extrinsics and intrinsics.""" + + T = pose_encoding[..., :3] + quat = pose_encoding[..., 3:7] + fov_h = pose_encoding[..., 7] + fov_w = pose_encoding[..., 8] + + R = quat_to_mat(quat) + extrinsics = torch.cat([R, T[..., None]], dim=-1) + + H, W = image_size_hw + fy = (H / 2.0) / torch.clamp(torch.tan(fov_h / 2.0), 1e-6) + fx = (W / 2.0) / torch.clamp(torch.tan(fov_w / 2.0), 1e-6) + intrinsics = torch.zeros(pose_encoding.shape[:2] + (3, 3), device=pose_encoding.device) + intrinsics[..., 0, 0] = fx + intrinsics[..., 1, 1] = fy + intrinsics[..., 0, 2] = W / 2 + intrinsics[..., 1, 2] = H / 2 + intrinsics[..., 2, 2] = 1.0 # Set the homogeneous coordinate to 1 + + return extrinsics, intrinsics + + +def quat_to_mat(quaternions: torch.Tensor) -> torch.Tensor: + """ + Quaternion Order: XYZW or say ijkr, scalar-last + + Convert rotations given as quaternions to rotation matrices. + Args: + quaternions: quaternions with real part last, + as tensor of shape (..., 4). + + Returns: + Rotation matrices as tensor of shape (..., 3, 3). + """ + i, j, k, r = torch.unbind(quaternions, -1) + two_s = 2.0 / (quaternions * quaternions).sum(-1) + + o = torch.stack( + ( + 1 - two_s * (j * j + k * k), + two_s * (i * j - k * r), + two_s * (i * k + j * r), + two_s * (i * j + k * r), + 1 - two_s * (i * i + k * k), + two_s * (j * k - i * r), + two_s * (i * k - j * r), + two_s * (j * k + i * r), + 1 - two_s * (i * i + j * j), + ), + -1, + ) + return o.reshape(quaternions.shape[:-1] + (3, 3)) + + +def mat_to_quat(matrix: torch.Tensor) -> torch.Tensor: + """ + Convert rotations given as rotation matrices to quaternions. + + Args: + matrix: Rotation matrices as tensor of shape (..., 3, 3). + + Returns: + quaternions with real part last, as tensor of shape (..., 4). + Quaternion Order: XYZW or say ijkr, scalar-last + """ + if matrix.size(-1) != 3 or matrix.size(-2) != 3: + raise ValueError(f"Invalid rotation matrix shape {matrix.shape}.") + + batch_dim = matrix.shape[:-2] + m00, m01, m02, m10, m11, m12, m20, m21, m22 = torch.unbind( + matrix.reshape(batch_dim + (9,)), dim=-1 + ) + + q_abs = _sqrt_positive_part( + torch.stack( + [ + 1.0 + m00 + m11 + m22, + 1.0 + m00 - m11 - m22, + 1.0 - m00 + m11 - m22, + 1.0 - m00 - m11 + m22, + ], + dim=-1, + ) + ) + + quat_by_rijk = torch.stack( + [ + torch.stack([q_abs[..., 0] ** 2, m21 - m12, m02 - m20, m10 - m01], dim=-1), + torch.stack([m21 - m12, q_abs[..., 1] ** 2, m10 + m01, m02 + m20], dim=-1), + torch.stack([m02 - m20, m10 + m01, q_abs[..., 2] ** 2, m12 + m21], dim=-1), + torch.stack([m10 - m01, m20 + m02, m21 + m12, q_abs[..., 3] ** 2], dim=-1), + ], + dim=-2, + ) + + flr = torch.tensor(0.1).to(dtype=q_abs.dtype, device=q_abs.device) + quat_candidates = quat_by_rijk / (2.0 * q_abs[..., None].max(flr)) + + out = quat_candidates[F.one_hot(q_abs.argmax(dim=-1), num_classes=4) > 0.5, :].reshape( + batch_dim + (4,) + ) + + out = out[..., [1, 2, 3, 0]] + + out = standardize_quaternion(out) + + return out + + +def _sqrt_positive_part(x: torch.Tensor) -> torch.Tensor: + """ + Returns torch.sqrt(torch.max(0, x)) + but with a zero subgradient where x is 0. + """ + ret = torch.zeros_like(x) + positive_mask = x > 0 + if torch.is_grad_enabled(): + ret[positive_mask] = torch.sqrt(x[positive_mask]) + else: + ret = torch.where(positive_mask, torch.sqrt(x), ret) + return ret + + +def standardize_quaternion(quaternions: torch.Tensor) -> torch.Tensor: + """ + Convert a unit quaternion to a standard form: one in which the real + part is non negative. + + Args: + quaternions: Quaternions with real part last, + as tensor of shape (..., 4). + + Returns: + Standardized quaternions as tensor of shape (..., 4). + """ + return torch.where(quaternions[..., 3:4] < 0, -quaternions, quaternions) + + +def cam_quat_xyzw_to_world_quat_wxyz(cam_quat_xyzw, c2w): + # cam_quat_xyzw: (b, n, 4) in xyzw + # c2w: (b, n, 4, 4) + b, n = cam_quat_xyzw.shape[:2] + # 1. xyzw -> wxyz + cam_quat_wxyz = torch.cat( + [ + cam_quat_xyzw[..., 3:4], # w + cam_quat_xyzw[..., 0:1], # x + cam_quat_xyzw[..., 1:2], # y + cam_quat_xyzw[..., 2:3], # z + ], + dim=-1, + ) + # 2. Quaternion to matrix + cam_quat_wxyz_flat = cam_quat_wxyz.reshape(-1, 4) + rotmat_cam = quat_to_mat(cam_quat_wxyz_flat).reshape(b, n, 3, 3) + # 3. Transform to world space + rotmat_c2w = c2w[..., :3, :3] + rotmat_world = torch.matmul(rotmat_c2w, rotmat_cam) + # 4. Matrix to quaternion (wxyz) + rotmat_world_flat = rotmat_world.reshape(-1, 3, 3) + world_quat_wxyz_flat = mat_to_quat(rotmat_world_flat) + world_quat_wxyz = world_quat_wxyz_flat.reshape(b, n, 4) + return world_quat_wxyz diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/registry.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/registry.py new file mode 100644 index 0000000000000000000000000000000000000000..96450717d696b395503fedfe93af812e975d2671 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/registry.py @@ -0,0 +1,50 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from collections import OrderedDict +from pathlib import Path + + +def get_all_models() -> OrderedDict: + """ + Scans all YAML files in the configs directory and returns a sorted dictionary where: + - Keys are model names (YAML filenames without the .yaml extension) + - Values are absolute paths to the corresponding YAML files + """ + # Get path to the configs directory within the da3 package + # Works both in development and after pip installation + # configs_dir = files("depth_anything_3").joinpath("configs") + configs_dir = Path(__file__).resolve().parent / "configs" + + # Ensure path is a Path object for consistent cross-platform handling + configs_dir = Path(configs_dir) + + model_entries = [] + # Iterate through all items in the configs directory + for item in configs_dir.iterdir(): + # Filter for YAML files (excluding directories) + if item.is_file() and item.suffix == ".yaml": + # Extract model name (filename without .yaml extension) + model_name = item.stem + # Get absolute path (resolve() handles symlinks) + file_abs_path = str(item.resolve()) + model_entries.append((model_name, file_abs_path)) + + # Sort entries by model name and convert to OrderedDict + sorted_entries = sorted(model_entries, key=lambda x: x[0]) + return OrderedDict(sorted_entries) + + +# Global registry for external imports +MODEL_REGISTRY = get_all_models() diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/services/__init__.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/services/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..07ed8b6b96d68a3f3933dfa6651875f3f88b0aef --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/services/__init__.py @@ -0,0 +1,24 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Services module for Depth Anything 3. +""" + +from depth_anything_3.services.backend import create_app, start_server + +__all__ = [ + start_server, + create_app, +] diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/services/backend.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/services/backend.py new file mode 100644 index 0000000000000000000000000000000000000000..e279e64c35067ba3d2fcb4b68f71debf9c039903 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/services/backend.py @@ -0,0 +1,1417 @@ +# flake8: noqa: E501 +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Model backend service for Depth Anything 3. +Provides HTTP API for model inference with persistent model loading. +""" + +import os +import posixpath +import time +import uuid + +from concurrent.futures import ThreadPoolExecutor +from typing import Any, Dict, List, Optional +from urllib.parse import quote +import numpy as np + +import uvicorn +from fastapi import FastAPI, HTTPException +from fastapi.responses import FileResponse, HTMLResponse +from pydantic import BaseModel + +from ..api import DepthAnything3 +from ..utils.memory import ( + get_gpu_memory_info, + cleanup_cuda_memory, + check_memory_availability, + estimate_memory_requirement, +) + + +class InferenceRequest(BaseModel): + """Request model for inference API.""" + + image_paths: List[str] + export_dir: Optional[str] = None + export_format: str = "mini_npz-glb" + extrinsics: Optional[List[List[List[float]]]] = None + intrinsics: Optional[List[List[List[float]]]] = None + process_res: int = 504 + process_res_method: str = "upper_bound_resize" + export_feat_layers: List[int] = [] + align_to_input_ext_scale: bool = True + # GLB export parameters + conf_thresh_percentile: float = 40.0 + num_max_points: int = 1_000_000 + show_cameras: bool = True + # Feat_vis export parameters + feat_vis_fps: int = 15 + + +class InferenceResponse(BaseModel): + """Response model for inference API.""" + + success: bool + message: str + task_id: Optional[str] = None + export_dir: Optional[str] = None + export_format: str = "mini_npz-glb" + processing_time: Optional[float] = None + + +class TaskStatus(BaseModel): + """Task status model.""" + + task_id: str + status: str # "pending", "running", "completed", "failed" + message: str + progress: Optional[float] = None # 0.0 to 1.0 + created_at: float + started_at: Optional[float] = None + completed_at: Optional[float] = None + export_dir: Optional[str] = None + request: Optional[InferenceRequest] = None # Store the original request + + # Essential task parameters + num_images: Optional[int] = None # Number of input images + export_format: Optional[str] = None # Export format + process_res_method: Optional[str] = None # Processing resolution method + video_path: Optional[str] = None # Source video path + + +class ModelBackend: + """Model backend service with persistent model loading.""" + + def __init__(self, model_dir: str, device: str = "cuda"): + self.model_dir = model_dir + self.device = device + self.model = None + self.model_loaded = False + self.load_time = None + self.load_start_time = None # Time when model loading started + self.load_completed_time = None # Time when model loading completed + self.last_used = None + + def load_model(self): + """Load model if not already loaded.""" + if self.model_loaded and self.model is not None: + self.last_used = time.time() + return self.model + + try: + print(f"Loading model from {self.model_dir}...") + self.load_start_time = time.time() + start_time = time.time() + + self.model = DepthAnything3.from_pretrained(self.model_dir).to(self.device) + self.model.eval() + + self.model_loaded = True + self.load_time = time.time() - start_time + self.load_completed_time = time.time() + self.last_used = time.time() + + print(f"Model loaded successfully in {self.load_time:.2f}s") + return self.model + + except Exception as e: + print(f"Failed to load model: {e}") + raise e + + def get_model(self): + """Get model, loading if necessary.""" + if not self.model_loaded: + return self.load_model() + self.last_used = time.time() + return self.model + + def get_status(self) -> Dict[str, Any]: + """Get backend status information.""" + # Calculate uptime from when model loading completed + uptime = 0 + if self.model_loaded and self.load_completed_time: + uptime = time.time() - self.load_completed_time + + return { + "model_loaded": self.model_loaded, + "model_dir": self.model_dir, + "device": self.device, + "load_time": self.load_time, + "last_used": self.last_used, + "uptime": uptime, + } + + +# Global backend instance +_backend: Optional[ModelBackend] = None +_app: Optional[FastAPI] = None +_tasks: Dict[str, TaskStatus] = {} +_executor = ThreadPoolExecutor(max_workers=1) # Restrict to single-task execution +_running_task_id: Optional[str] = None # Currently running task ID +_task_queue: List[str] = [] # Pending task queue + +# Task cleanup configuration +MAX_TASK_HISTORY = 100 # Maximum number of tasks to keep in memory +CLEANUP_INTERVAL = 300 # Cleanup interval in seconds (5 minutes) + + +def _process_next_task(): + """Process the next task in the queue.""" + global _task_queue, _running_task_id + + if not _task_queue or _running_task_id is not None: + return + + # Get next task from queue + task_id = _task_queue.pop(0) + + # Get task request from tasks dict (we need to store the request) + if task_id not in _tasks: + return + + # Submit task to executor + _executor.submit(_run_inference_task, task_id) + + +# get_gpu_memory_info imported from depth_anything_3.utils.memory + + +# cleanup_cuda_memory imported from depth_anything_3.utils.memory + + +# check_memory_availability imported from depth_anything_3.utils.memory + + +# estimate_memory_requirement imported from depth_anything_3.utils.memory + + +def _run_inference_task(task_id: str): + """Run inference task in background thread with OOM protection.""" + global _tasks, _backend, _running_task_id, _task_queue + + model = None + inference_started = False + start_time = time.time() + + try: + # Get task request + if task_id not in _tasks or _tasks[task_id].request is None: + print(f"[{task_id}] Task not found or request missing") + return + + request = _tasks[task_id].request + num_images = len(request.image_paths) + + # Set current running task + _running_task_id = task_id + + # Update task status to running + _tasks[task_id].status = "running" + _tasks[task_id].started_at = start_time + _tasks[task_id].message = f"[{task_id}] Starting inference on {num_images} frames..." + print(f"[{task_id}] Starting inference on {num_images} frames") + + # Pre-inference cleanup to ensure maximum available memory + print(f"[{task_id}] Pre-inference cleanup...") + cleanup_cuda_memory() + + # Check memory availability + estimated_memory = estimate_memory_requirement(num_images, request.process_res) + mem_available, mem_msg = check_memory_availability(estimated_memory) + print(f"[{task_id}] {mem_msg}") + + if not mem_available: + # Try aggressive cleanup + print(f"[{task_id}] Insufficient memory, attempting aggressive cleanup...") + cleanup_cuda_memory() + time.sleep(0.5) # Give system time to reclaim memory + + # Check again + mem_available, mem_msg = check_memory_availability(estimated_memory) + if not mem_available: + raise RuntimeError( + f"Insufficient GPU memory after cleanup. {mem_msg}\n" + f"Suggestions:\n" + f" 1. Reduce process_res (current: {request.process_res})\n" + f" 2. Process fewer images at once (current: {num_images})\n" + f" 3. Clear other GPU processes" + ) + + # Get model (with error handling) + print(f"[{task_id}] Loading model...") + _tasks[task_id].message = f"[{task_id}] Loading model..." + _tasks[task_id].progress = 0.1 + + try: + model = _backend.get_model() + except RuntimeError as e: + if "out of memory" in str(e).lower(): + cleanup_cuda_memory() + raise RuntimeError( + f"OOM during model loading: {str(e)}\n" + f"Try reducing the batch size or resolution." + ) + raise + + print(f"[{task_id}] Model loaded successfully") + _tasks[task_id].progress = 0.2 + + # Prepare inference parameters + inference_kwargs = { + "image": request.image_paths, + "export_format": request.export_format, + "process_res": request.process_res, + "process_res_method": request.process_res_method, + "export_feat_layers": request.export_feat_layers, + "align_to_input_ext_scale": request.align_to_input_ext_scale, + "conf_thresh_percentile": request.conf_thresh_percentile, + "num_max_points": request.num_max_points, + "show_cameras": request.show_cameras, + "feat_vis_fps": request.feat_vis_fps, + } + + if request.export_dir: + inference_kwargs["export_dir"] = request.export_dir + + if request.extrinsics: + inference_kwargs["extrinsics"] = np.array(request.extrinsics, dtype=np.float32) + + if request.intrinsics: + inference_kwargs["intrinsics"] = np.array(request.intrinsics, dtype=np.float32) + + # Run inference with timing + inference_start_time = time.time() + print(f"[{task_id}] Running model inference...") + _tasks[task_id].message = f"[{task_id}] Running model inference on {num_images} images..." + _tasks[task_id].progress = 0.3 + + inference_started = True + + try: + model.inference(**inference_kwargs) + inference_time = time.time() - inference_start_time + avg_time_per_image = inference_time / num_images if num_images > 0 else 0 + + print( + f"[{task_id}] Inference completed in {inference_time:.2f}s " + f"({avg_time_per_image:.2f}s per image)" + ) + + except RuntimeError as e: + if "out of memory" in str(e).lower(): + cleanup_cuda_memory() + raise RuntimeError( + f"OOM during inference: {str(e)}\n" + f"Settings: {num_images} images, resolution={request.process_res}\n" + f"Suggestions:\n" + f" 1. Reduce process_res to {int(request.process_res * 0.75)}\n" + f" 2. Process images in smaller batches\n" + f" 3. Use process_res_method='resize' instead of 'upper_bound_resize'" + ) + raise + + _tasks[task_id].progress = 0.9 + + # Post-inference cleanup + print(f"[{task_id}] Post-inference cleanup...") + cleanup_cuda_memory() + + # Calculate total processing time + total_time = time.time() - start_time + + # Update task status to completed + _tasks[task_id].status = "completed" + _tasks[task_id].completed_at = time.time() + _tasks[task_id].message = ( + f"[{task_id}] Completed in {total_time:.2f}s " f"({avg_time_per_image:.2f}s per image)" + ) + _tasks[task_id].progress = 1.0 + _tasks[task_id].export_dir = request.export_dir + + # Clear running state + _running_task_id = None + + # Process next task in queue + _process_next_task() + + print(f"[{task_id}] Task completed successfully") + print( + f"[{task_id}] Total time: {total_time:.2f}s, " + f"Inference time: {inference_time:.2f}s, " + f"Avg per image: {avg_time_per_image:.2f}s" + ) + + except Exception as e: + # Update task status to failed + error_msg = str(e) + total_time = time.time() - start_time + + print(f"[{task_id}] Task failed after {total_time:.2f}s: {error_msg}") + + # Always attempt cleanup on failure + cleanup_cuda_memory() + + _tasks[task_id].status = "failed" + _tasks[task_id].completed_at = time.time() + _tasks[task_id].message = f"[{task_id}] Failed after {total_time:.2f}s: {error_msg}" + + # Clear running state + _running_task_id = None + + # Process next task in queue + _process_next_task() + + finally: + # Final cleanup in finally block to ensure it always runs + # This is critical for releasing resources even if unexpected errors occur + try: + if inference_started: + print(f"[{task_id}] Final cleanup in finally block...") + cleanup_cuda_memory() + except Exception as e: + print(f"[{task_id}] Warning: Finally block cleanup failed: {e}") + + # Schedule cleanup after task completion + _schedule_task_cleanup() + + +def _cleanup_old_tasks(): + """Clean up old completed/failed tasks to prevent memory buildup.""" + global _tasks + + current_time = time.time() + tasks_to_remove = [] + + # Find tasks to remove - more aggressive cleanup + for task_id, task in _tasks.items(): + # Remove completed/failed tasks older than 10 minutes (instead of 1 hour) + if ( + task.status in ["completed", "failed"] + and task.completed_at + and current_time - task.completed_at > 600 + ): # 10 minutes + tasks_to_remove.append(task_id) + + # Remove old tasks + for task_id in tasks_to_remove: + del _tasks[task_id] + print(f"[CLEANUP] Removed old task: {task_id}") + + # If still too many tasks, remove oldest completed/failed tasks + if len(_tasks) > MAX_TASK_HISTORY: + completed_tasks = [ + (task_id, task) + for task_id, task in _tasks.items() + if task.status in ["completed", "failed"] + ] + completed_tasks.sort(key=lambda x: x[1].completed_at or 0) + + excess_count = len(_tasks) - MAX_TASK_HISTORY + for i in range(min(excess_count, len(completed_tasks))): + task_id = completed_tasks[i][0] + del _tasks[task_id] + print(f"[CLEANUP] Removed excess task: {task_id}") + + # Count active tasks (only pending and running) + active_count = sum(1 for task in _tasks.values() if task.status in ["pending", "running"]) + print( + "[CLEANUP] Task cleanup completed. " + f"Total tasks: {len(_tasks)}, Active tasks: {active_count}" + ) + + +def _schedule_task_cleanup(): + """Schedule task cleanup in background.""" + + def cleanup_worker(): + try: + time.sleep(2) # Small delay to ensure task status is updated + _cleanup_old_tasks() + except Exception as e: + print(f"[CLEANUP] Cleanup worker failed: {e}") + + # Run cleanup in background thread + _executor.submit(cleanup_worker) + + +# ============================================================================ +# Gallery utilities (extracted from gallery.py) +# ============================================================================ + +GALLERY_IMAGE_EXTS = (".png", ".jpg", ".jpeg", ".webp", ".bmp") + + +def _load_gallery_html() -> str: + """ + Load and modify gallery HTML to work under /gallery/ subdirectory. + Replaces API paths from root to /gallery/ prefix. + """ + from ..services.gallery import HTML_PAGE + + # Replace API paths to be under /gallery/ subdirectory + html = ( + HTML_PAGE.replace("fetch('/manifest.json'", "fetch('/gallery/manifest.json'") + .replace("fetch('/manifest/'+", "fetch('/gallery/manifest/'+") + .replace( + "if(location.pathname!=\"/\")history.replaceState(null,'','/'+location.search)", + "if(!location.pathname.startsWith(\"/gallery\"))history.replaceState(null,'','/gallery/'+location.search)", + ) + ) + + return html + + +def _gallery_url_join(*parts: str) -> str: + """Join URL parts safely.""" + norm = posixpath.join(*[p.replace("\\", "/") for p in parts]) + segs = [s for s in norm.split("/") if s not in ("", ".")] + return "/".join(quote(s) for s in segs) + + +def _is_plain_name(name: str) -> bool: + """Check if name is safe for use in paths.""" + return all(c not in name for c in ("/", "\\")) and name not in (".", "..") + + +def build_group_list(root_dir: str) -> dict: + """Build list of groups from gallery directory.""" + groups = [] + try: + for gname in sorted(os.listdir(root_dir)): + gpath = os.path.join(root_dir, gname) + if not os.path.isdir(gpath): + continue + has_scene = False + try: + for sname in os.listdir(gpath): + spath = os.path.join(gpath, sname) + if not os.path.isdir(spath): + continue + if os.path.exists(os.path.join(spath, "scene.glb")) and os.path.exists( + os.path.join(spath, "scene.jpg") + ): + has_scene = True + break + except Exception: + pass + if has_scene: + groups.append({"id": gname, "title": gname}) + except Exception as e: + print(f"[warn] build_group_list failed: {e}") + return {"groups": groups} + + +def build_group_manifest(root_dir: str, group: str) -> dict: + """Build manifest for a specific group.""" + items = [] + gpath = os.path.join(root_dir, group) + try: + if not os.path.isdir(gpath): + return {"group": group, "items": []} + for sname in sorted(os.listdir(gpath)): + spath = os.path.join(gpath, sname) + if not os.path.isdir(spath): + continue + glb_fs = os.path.join(spath, "scene.glb") + jpg_fs = os.path.join(spath, "scene.jpg") + if not (os.path.exists(glb_fs) and os.path.exists(jpg_fs)): + continue + depth_images = [] + dpath = os.path.join(spath, "depth_vis") + if os.path.isdir(dpath): + files = [ + f + for f in os.listdir(dpath) + if os.path.splitext(f)[1].lower() in GALLERY_IMAGE_EXTS + ] + for fn in sorted(files): + depth_images.append( + "/gallery/" + _gallery_url_join(group, sname, "depth_vis", fn) + ) + items.append( + { + "id": sname, + "title": sname, + "model": "/gallery/" + _gallery_url_join(group, sname, "scene.glb"), + "thumbnail": "/gallery/" + _gallery_url_join(group, sname, "scene.jpg"), + "depth_images": depth_images, + } + ) + except Exception as e: + print(f"[warn] build_group_manifest failed for {group}: {e}") + return {"group": group, "items": items} + + +def create_app(model_dir: str, device: str = "cuda", gallery_dir: Optional[str] = None) -> FastAPI: + """Create FastAPI application with model backend.""" + global _backend, _app + + _backend = ModelBackend(model_dir, device) + _app = FastAPI( + title="Depth Anything 3 Backend", + description="Model inference service for Depth Anything 3", + version="1.0.0", + ) + + # Store gallery directory globally for use in routes + _gallery_dir = gallery_dir + + @_app.get("/", response_class=HTMLResponse) + async def root(): + """Home page with navigation to dashboard and gallery.""" + html_content = ( + """ + + + + + + Depth Anything 3 Backend + + + +
+

Depth Anything 3

+

Model Backend Service

+ + +
+ + + """ + ) + return HTMLResponse(html_content) + + @_app.get("/dashboard", response_class=HTMLResponse) + async def dashboard(): + """HTML dashboard for monitoring backend status and tasks.""" + if _backend is None: + return HTMLResponse("

Backend not initialized

", status_code=500) + + # Get backend status + status = _backend.get_status() + + # Safely format status values + if status["load_time"] is not None: + load_time_str = f"{status['load_time']:.2f}s" + else: + load_time_str = "Not loaded" + + if status["uptime"] is not None: + uptime_str = f"{status['uptime']:.2f}s" + else: + uptime_str = "Not running" + + # Get tasks information + active_tasks = [task for task in _tasks.values() if task.status in ["pending", "running"]] + completed_tasks = [ + task for task in _tasks.values() if task.status in ["completed", "failed"] + ] + + # Generate task HTML + active_tasks_html = "" + if active_tasks: + for task in active_tasks: + task_details = f""" +
+
+ {task.task_id} + {task.status} +
+
{task.message}
+
+ + Images: {task.num_images or 'N/A'} | + Format: {task.export_format or 'N/A'} | + Method: {task.process_res_method or 'N/A'} | + Export Dir: {task.export_dir or 'N/A'} + + {f'
Video: {task.video_path}' if task.video_path else ''} +
+
+ """ + active_tasks_html += task_details + else: + active_tasks_html = "

No active tasks

" + + completed_tasks_html = "" + if completed_tasks: + for task in completed_tasks[-10:]: + task_details = f""" +
+
+ {task.task_id} + {task.status} +
+
{task.message}
+
+ + Images: {task.num_images or 'N/A'} | + Format: {task.export_format or 'N/A'} | + Method: {task.process_res_method or 'N/A'} | + Export Dir: {task.export_dir or 'N/A'} + + {f'
Video: {task.video_path}' if task.video_path else ''} +
+
+ """ + completed_tasks_html += task_details + else: + completed_tasks_html = "

No completed tasks

" + + # Generate HTML + html_content = f""" + + + + + + Depth Anything 3 Backend Dashboard + + + +
+
+

Depth Anything 3 Backend Dashboard

+

Real-time monitoring of model status and inference tasks

+
+ +
+
+

Model Status

+
+ Status: + + {'Online' if status['model_loaded'] else 'Offline'} + +
+
+ Model Directory: + {status['model_dir']} +
+
+ Device: + {status['device']} +
+
+ Load Time: + {load_time_str} +
+
+ Uptime: + {uptime_str} +
+
+ +
+

Task Summary

+
+ Active Tasks: + {len(active_tasks)} +
+
+ Completed Tasks: + {len(completed_tasks)} +
+
+ Total Tasks: + {len(_tasks)} +
+
+
+ +
+

Active Tasks

+ + +
Last updated: {time.strftime('%Y-%m-%d %H:%M:%S')}
+ + {active_tasks_html} +
+ +
+

Recent Completed Tasks

+ {completed_tasks_html} +
+
+ + + + + """ + + return HTMLResponse(html_content) + + @_app.get("/status") + async def get_status(): + """Get backend status with GPU memory information.""" + if _backend is None: + raise HTTPException(status_code=500, detail="Backend not initialized") + + status = _backend.get_status() + + # Add GPU memory information + gpu_memory = get_gpu_memory_info() + if gpu_memory: + status["gpu_memory"] = { + "total_gb": round(gpu_memory["total_gb"], 2), + "allocated_gb": round(gpu_memory["allocated_gb"], 2), + "reserved_gb": round(gpu_memory["reserved_gb"], 2), + "free_gb": round(gpu_memory["free_gb"], 2), + "utilization_percent": round(gpu_memory["utilization"], 1), + } + else: + status["gpu_memory"] = None + + return status + + @_app.post("/inference", response_model=InferenceResponse) + async def run_inference(request: InferenceRequest): + """Submit inference task and return task ID.""" + global _running_task_id + + if _backend is None: + raise HTTPException(status_code=500, detail="Backend not initialized") + + # Generate unique task ID + task_id = str(uuid.uuid4()) + + # Create task status + if _running_task_id is not None: + status_msg = f"[{task_id}] Task queued (waiting for {_running_task_id} to complete)" + else: + status_msg = f"[{task_id}] Task submitted" + + _tasks[task_id] = TaskStatus( + task_id=task_id, + status="pending", + message=status_msg, + created_at=time.time(), + export_dir=request.export_dir, + request=request, + # Record essential parameters + num_images=len(request.image_paths), + export_format=request.export_format, + process_res_method=request.process_res_method, + video_path=( + request.image_paths[0] if request.image_paths else None + ), # Use first image path as video reference + ) + + # Add task to queue + _task_queue.append(task_id) + + # If no task is running, start processing the queue + if _running_task_id is None: + _process_next_task() + + return InferenceResponse( + success=True, + message="Task submitted successfully", + task_id=task_id, + export_dir=request.export_dir, + export_format=request.export_format, + ) + + @_app.get("/task/{task_id}", response_model=TaskStatus) + async def get_task_status(task_id: str): + """Get task status by task ID.""" + if task_id not in _tasks: + raise HTTPException(status_code=404, detail="Task not found") + + return _tasks[task_id] + + @_app.get("/gpu-memory") + async def get_gpu_memory(): + """Get detailed GPU memory information.""" + gpu_memory = get_gpu_memory_info() + if gpu_memory is None: + return { + "available": False, + "message": "CUDA not available or memory info cannot be retrieved", + } + + return { + "available": True, + "total_gb": round(gpu_memory["total_gb"], 2), + "allocated_gb": round(gpu_memory["allocated_gb"], 2), + "reserved_gb": round(gpu_memory["reserved_gb"], 2), + "free_gb": round(gpu_memory["free_gb"], 2), + "utilization_percent": round(gpu_memory["utilization"], 1), + "status": ( + "healthy" + if gpu_memory["utilization"] < 80 + else "warning" if gpu_memory["utilization"] < 95 else "critical" + ), + } + + @_app.get("/tasks") + async def list_tasks(): + """List all tasks.""" + # Separate active and completed tasks + active_tasks = [task for task in _tasks.values() if task.status in ["pending", "running"]] + completed_tasks = [ + task for task in _tasks.values() if task.status in ["completed", "failed"] + ] + + return { + "tasks": list(_tasks.values()), + "active_tasks": active_tasks, + "completed_tasks": completed_tasks, + "active_count": len(active_tasks), + "total_count": len(_tasks), + } + + @_app.post("/cleanup") + async def manual_cleanup(): + """Manually trigger task cleanup.""" + try: + _cleanup_old_tasks() + return {"message": "Cleanup completed", "active_tasks": len(_tasks)} + except Exception as e: + raise HTTPException(status_code=500, detail=f"Cleanup failed: {str(e)}") + + @_app.delete("/task/{task_id}") + async def delete_task(task_id: str): + """Delete a specific task.""" + if task_id not in _tasks: + raise HTTPException(status_code=404, detail="Task not found") + + # Only allow deletion of completed/failed tasks + if _tasks[task_id].status not in ["completed", "failed"]: + raise HTTPException(status_code=400, detail="Cannot delete running or pending tasks") + + del _tasks[task_id] + return {"message": f"Task {task_id} deleted successfully"} + + @_app.post("/reload") + async def reload_model(): + """Reload the model.""" + if _backend is None: + raise HTTPException(status_code=500, detail="Backend not initialized") + + try: + _backend.model = None + _backend.model_loaded = False + _backend.load_model() + return {"message": "Model reloaded successfully"} + except Exception as e: + raise HTTPException(status_code=500, detail=f"Failed to reload model: {str(e)}") + + # ============================================================================ + # Gallery routes + # ============================================================================ + + if _gallery_dir and os.path.exists(_gallery_dir): + # Load gallery HTML page (with modified paths for /gallery/ subdirectory) + _gallery_html = _load_gallery_html() + + @_app.get("/gallery/", response_class=HTMLResponse) + @_app.get("/gallery", response_class=HTMLResponse) + async def gallery_home(): + """Gallery home page.""" + return HTMLResponse(_gallery_html) + + @_app.get("/gallery/manifest.json") + async def gallery_manifest(): + """Get gallery group list.""" + try: + return build_group_list(_gallery_dir) + except Exception as e: + raise HTTPException( + status_code=500, detail=f"Failed to build group list: {str(e)}" + ) + + @_app.get("/gallery/manifest/{group}.json") + async def gallery_group_manifest(group: str): + """Get manifest for a specific group.""" + if not _is_plain_name(group): + raise HTTPException(status_code=400, detail="Invalid group name") + try: + return build_group_manifest(_gallery_dir, group) + except Exception as e: + raise HTTPException( + status_code=500, detail=f"Failed to build group manifest: {str(e)}" + ) + + @_app.get("/gallery/{path:path}") + async def gallery_files(path: str): + """Serve gallery static files (GLB, JPG, etc.).""" + # Security check: prevent directory traversal + path_parts = path.split("/") + if any(not _is_plain_name(part) for part in path_parts if part): + raise HTTPException(status_code=400, detail="Invalid path") + + file_path = os.path.join(_gallery_dir, *path_parts) + + # Ensure the file is within gallery directory + real_file_path = os.path.realpath(file_path) + real_gallery_dir = os.path.realpath(_gallery_dir) + if not real_file_path.startswith(real_gallery_dir): + raise HTTPException(status_code=403, detail="Access denied") + + if not os.path.exists(file_path) or not os.path.isfile(file_path): + raise HTTPException(status_code=404, detail="File not found") + + return FileResponse(file_path) + + return _app + + +def start_server( + model_dir: str, + device: str = "cuda", + host: str = "127.0.0.1", + port: int = 8000, + gallery_dir: Optional[str] = None, +): + """Start the backend server.""" + app = create_app(model_dir, device, gallery_dir) + + print("Starting Depth Anything 3 Backend...") + print(f"Model directory: {model_dir}") + print(f"Device: {device}") + print(f"Server: http://{host}:{port}") + print(f"Dashboard: http://{host}:{port}/dashboard") + print(f"API Status: http://{host}:{port}/status") + + if gallery_dir and os.path.exists(gallery_dir): + print(f"Gallery: http://{host}:{port}/gallery/") + + print("=" * 60) + print("Backend is running! You can now:") + print(f" • Open home page: http://{host}:{port}") + print(f" • Open dashboard: http://{host}:{port}/dashboard") + print(f" • Check API status: http://{host}:{port}/status") + + if gallery_dir and os.path.exists(gallery_dir): + print(f" • Browse gallery: http://{host}:{port}/gallery/") + + print(" • Submit inference tasks via API") + print("=" * 60) + + uvicorn.run(app, host=host, port=port, log_level="info") + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description="Depth Anything 3 Backend Server") + parser.add_argument("--model-dir", required=True, help="Model directory path") + parser.add_argument("--device", default="cuda", help="Device to use") + parser.add_argument("--host", default="127.0.0.1", help="Host to bind to") + parser.add_argument("--port", type=int, default=8000, help="Port to bind to") + parser.add_argument("--gallery-dir", help="Gallery directory path (optional)") + + args = parser.parse_args() + start_server(args.model_dir, args.device, args.host, args.port, args.gallery_dir) diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/services/gallery.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/services/gallery.py new file mode 100644 index 0000000000000000000000000000000000000000..f72bb5e5f6defbc24cf2278a53b7162a8ad5519d --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/services/gallery.py @@ -0,0 +1,806 @@ +#!/usr/bin/env python3 +# flake8: noqa: E501 +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Depth Anything 3 Gallery Server (two-level, single-file) +Now supports paginated depth preview (4 per page). +""" + +import argparse +import json +import mimetypes +import os +import posixpath +import sys +from functools import partial +from http import HTTPStatus +from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer +from urllib.parse import quote, unquote + +# ------------------------------ Embedded HTML ------------------------------ # + +HTML_PAGE = r""" + + + + Depth Anything 3 Gallery + + + + + + + +
+
+ +

Depth Anything 3 Gallery

+ + +
+
Level 1 shows groups only; click a group to browse scenes and previews.
+
+ +
+ +
+

+ 🎯 Depth Anything 3 Gallery +

+

+ Explore 3D reconstructions and depth visualizations from Depth Anything 3. + Browse through groups of scenes, preview 3D models, and examine depth maps interactively. +

+
+ +
+
    + +
    + + +
    + + + +
    Depth Anything 3 Gallery. Copyright 2025 Depth Anything 3 authors.
    + + + + +""" + +# ------------------------------ Utilities ------------------------------ # + +IMAGE_EXTS = (".png", ".jpg", ".jpeg", ".webp", ".bmp") + + +def _url_join(*parts: str) -> str: + norm = posixpath.join(*[p.replace("\\", "/") for p in parts]) + segs = [s for s in norm.split("/") if s not in ("", ".")] + return "/".join(quote(s) for s in segs) + + +def _is_plain_name(name: str) -> bool: + return all(c not in name for c in ("/", "\\")) and name not in (".", "..") + + +def build_group_list(root_dir: str) -> dict: + groups = [] + try: + for gname in sorted(os.listdir(root_dir)): + gpath = os.path.join(root_dir, gname) + if not os.path.isdir(gpath): + continue + has_scene = False + try: + for sname in os.listdir(gpath): + spath = os.path.join(gpath, sname) + if not os.path.isdir(spath): + continue + if os.path.exists(os.path.join(spath, "scene.glb")) and os.path.exists( + os.path.join(spath, "scene.jpg") + ): + has_scene = True + break + except Exception: + pass + if has_scene: + groups.append({"id": gname, "title": gname}) + except Exception as e: + print(f"[warn] build_group_list failed: {e}", file=sys.stderr) + return {"groups": groups} + + +def build_group_manifest(root_dir: str, group: str) -> dict: + items = [] + gpath = os.path.join(root_dir, group) + try: + if not os.path.isdir(gpath): + return {"group": group, "items": []} + for sname in sorted(os.listdir(gpath)): + spath = os.path.join(gpath, sname) + if not os.path.isdir(spath): + continue + glb_fs = os.path.join(spath, "scene.glb") + jpg_fs = os.path.join(spath, "scene.jpg") + if not (os.path.exists(glb_fs) and os.path.exists(jpg_fs)): + continue + depth_images = [] + dpath = os.path.join(spath, "depth_vis") + if os.path.isdir(dpath): + files = [ + f for f in os.listdir(dpath) if os.path.splitext(f)[1].lower() in IMAGE_EXTS + ] + for fn in sorted(files): + depth_images.append("/" + _url_join(group, sname, "depth_vis", fn)) + items.append( + { + "id": sname, + "title": sname, + "model": "/" + _url_join(group, sname, "scene.glb"), + "thumbnail": "/" + _url_join(group, sname, "scene.jpg"), + "depth_images": depth_images, + } + ) + except Exception as e: + print(f"[warn] build_group_manifest failed for {group}: {e}", file=sys.stderr) + return {"group": group, "items": items} + + +class GalleryHandler(SimpleHTTPRequestHandler): + def __init__(self, *args, directory=None, **kwargs): + super().__init__(*args, directory=directory, **kwargs) + + def do_GET(self): + if self.path in ("/", "/index.html") or self.path.startswith("/?"): + content = HTML_PAGE.encode("utf-8") + self.send_response(HTTPStatus.OK) + self.send_header("Content-Type", "text/html; charset=utf-8") + self.send_header("Content-Length", str(len(content))) + self.send_header("Cache-Control", "no-store") + self.end_headers() + self.wfile.write(content) + return + if self.path == "/manifest.json": + data = json.dumps( + build_group_list(self.directory), ensure_ascii=False, indent=2 + ).encode("utf-8") + self.send_response(HTTPStatus.OK) + self.send_header("Content-Type", "application/json; charset=utf-8") + self.send_header("Content-Length", str(len(data))) + self.send_header("Cache-Control", "no-store") + self.end_headers() + self.wfile.write(data) + return + if self.path.startswith("/manifest/") and self.path.endswith(".json"): + group_enc = self.path[len("/manifest/") : -len(".json")] + try: + group = unquote(group_enc) + except Exception: + group = group_enc + if not _is_plain_name(group): + self.send_error(HTTPStatus.BAD_REQUEST, "Invalid group name") + return + data = json.dumps( + build_group_manifest(self.directory, group), ensure_ascii=False, indent=2 + ).encode("utf-8") + self.send_response(HTTPStatus.OK) + self.send_header("Content-Type", "application/json; charset=utf-8") + self.send_header("Content-Length", str(len(data))) + self.send_header("Cache-Control", "no-store") + self.end_headers() + self.wfile.write(data) + return + if self.path == "/favicon.ico": + self.send_response(HTTPStatus.NO_CONTENT) + self.end_headers() + return + return super().do_GET() + + def list_directory(self, path): + self.send_error(HTTPStatus.NOT_FOUND, "Directory listing disabled") + return None + + +def gallery(): + parser = argparse.ArgumentParser( + description="Depth Anything 3 Gallery Server (two-level, with pagination)" + ) + parser.add_argument( + "-d", "--dir", required=True, help="Gallery root directory (two-level: group/scene)" + ) + parser.add_argument("-p", "--port", type=int, default=8000, help="Port (default 8000)") + parser.add_argument("--host", default="127.0.0.1", help="Host address (default 127.0.0.1)") + parser.add_argument("--open", action="store_true", help="Open browser after launch") + args = parser.parse_args() + + root_dir = os.path.abspath(args.dir) + if not os.path.isdir(root_dir): + print(f"[error] Directory not found: {root_dir}", file=sys.stderr) + sys.exit(1) + + Handler = partial(GalleryHandler, directory=root_dir) + server = ThreadingHTTPServer((args.host, args.port), Handler) + + addr = f"http://{args.host}:{args.port}/" + print(f"[info] Serving gallery from: {root_dir}") + print(f"[info] Open: {addr}") + + if args.open: + try: + import webbrowser + + webbrowser.open(addr) + except Exception as e: + print(f"[warn] Failed to open browser: {e}", file=sys.stderr) + + try: + server.serve_forever() + except KeyboardInterrupt: + print("\n[info] Shutting down...") + finally: + server.server_close() + + +def main(): + """Main entry point for gallery server.""" + mimetypes.add_type("model/gltf-binary", ".glb") + gallery() + + +if __name__ == "__main__": + main() diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/services/inference_service.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/services/inference_service.py new file mode 100644 index 0000000000000000000000000000000000000000..2ec8dbc521bea02266adfcf42c0b50ac38dab342 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/services/inference_service.py @@ -0,0 +1,239 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Unified Inference Service +Provides unified interface for local and remote inference +""" + +from typing import Any, Dict, List, Optional, Union +import numpy as np +import requests +import typer + +from ..api import DepthAnything3 + + +class InferenceService: + """Unified inference service class""" + + def __init__(self, model_dir: str, device: str = "cuda"): + self.model_dir = model_dir + self.device = device + self.model = None + + def load_model(self): + """Load model""" + if self.model is None: + typer.echo(f"Loading model from {self.model_dir}...") + self.model = DepthAnything3.from_pretrained(self.model_dir).to(self.device) + return self.model + + def run_local_inference( + self, + image_paths: List[str], + export_dir: str, + export_format: str = "mini_npz-glb", + process_res: int = 504, + process_res_method: str = "upper_bound_resize", + export_feat_layers: List[int] = None, + extrinsics: Optional[np.ndarray] = None, + intrinsics: Optional[np.ndarray] = None, + align_to_input_ext_scale: bool = True, + use_ray_pose: bool = False, + ref_view_strategy: str = "saddle_balanced", + conf_thresh_percentile: float = 40.0, + num_max_points: int = 1_000_000, + show_cameras: bool = True, + feat_vis_fps: int = 15, + ) -> Any: + """Run local inference""" + if export_feat_layers is None: + export_feat_layers = [] + + model = self.load_model() + + # Prepare inference parameters + inference_kwargs = { + "image": image_paths, + "export_dir": export_dir, + "export_format": export_format, + "process_res": process_res, + "process_res_method": process_res_method, + "export_feat_layers": export_feat_layers, + "align_to_input_ext_scale": align_to_input_ext_scale, + "use_ray_pose": use_ray_pose, + "ref_view_strategy": ref_view_strategy, + "conf_thresh_percentile": conf_thresh_percentile, + "num_max_points": num_max_points, + "show_cameras": show_cameras, + "feat_vis_fps": feat_vis_fps, + } + + # Add pose data (if exists) + if extrinsics is not None: + inference_kwargs["extrinsics"] = extrinsics + if intrinsics is not None: + inference_kwargs["intrinsics"] = intrinsics + + # Run inference + typer.echo(f"Running inference on {len(image_paths)} images...") + prediction = model.inference(**inference_kwargs) + + typer.echo(f"Results saved to {export_dir}") + typer.echo(f"Export format: {export_format}") + + return prediction + + def run_backend_inference( + self, + image_paths: List[str], + export_dir: str, + backend_url: str, + export_format: str = "mini_npz-glb", + process_res: int = 504, + process_res_method: str = "upper_bound_resize", + export_feat_layers: List[int] = None, + extrinsics: Optional[np.ndarray] = None, + intrinsics: Optional[np.ndarray] = None, + align_to_input_ext_scale: bool = True, + use_ray_pose: bool = False, + ref_view_strategy: str = "saddle_balanced", + conf_thresh_percentile: float = 40.0, + num_max_points: int = 1_000_000, + show_cameras: bool = True, + feat_vis_fps: int = 15, + ) -> Dict[str, Any]: + """Run backend inference""" + if export_feat_layers is None: + export_feat_layers = [] + + # Check backend status + if not self._check_backend_status(backend_url): + raise typer.BadParameter(f"Backend service is not running at {backend_url}") + + # Prepare payload + payload = { + "image_paths": image_paths, + "export_dir": export_dir, + "export_format": export_format, + "process_res": process_res, + "process_res_method": process_res_method, + "export_feat_layers": export_feat_layers, + "align_to_input_ext_scale": align_to_input_ext_scale, + "use_ray_pose": use_ray_pose, + "ref_view_strategy": ref_view_strategy, + "conf_thresh_percentile": conf_thresh_percentile, + "num_max_points": num_max_points, + "show_cameras": show_cameras, + "feat_vis_fps": feat_vis_fps, + } + + # Add pose data (if exists) + if extrinsics is not None: + payload["extrinsics"] = [ext.astype(np.float64).tolist() for ext in extrinsics] + if intrinsics is not None: + payload["intrinsics"] = [intr.astype(np.float64).tolist() for intr in intrinsics] + + # Submit task + typer.echo("Submitting inference task to backend...") + try: + response = requests.post(f"{backend_url}/inference", json=payload, timeout=30) + response.raise_for_status() + result = response.json() + + if result["success"]: + task_id = result["task_id"] + typer.echo("Task submitted successfully!") + typer.echo(f"Task ID: {task_id}") + typer.echo(f"Results will be saved to: {export_dir}") + typer.echo(f"Check backend logs for progress updates with task ID: {task_id}") + return result + else: + raise typer.BadParameter( + f"Backend inference submission failed: {result['message']}" + ) + except requests.exceptions.RequestException as e: + raise typer.BadParameter(f"Backend inference submission failed: {e}") + + def _check_backend_status(self, backend_url: str) -> bool: + """Check backend status""" + try: + response = requests.get(f"{backend_url}/status", timeout=5) + return response.status_code == 200 + except Exception: + return False + + +def run_inference( + image_paths: List[str], + export_dir: str, + model_dir: str, + device: str = "cuda", + backend_url: Optional[str] = None, + export_format: str = "mini_npz-glb", + process_res: int = 504, + process_res_method: str = "upper_bound_resize", + export_feat_layers: List[int] = None, + extrinsics: Optional[np.ndarray] = None, + intrinsics: Optional[np.ndarray] = None, + align_to_input_ext_scale: bool = True, + use_ray_pose: bool = False, + ref_view_strategy: str = "saddle_balanced", + conf_thresh_percentile: float = 40.0, + num_max_points: int = 1_000_000, + show_cameras: bool = True, + feat_vis_fps: int = 15, +) -> Union[Any, Dict[str, Any]]: + """Unified inference interface""" + + service = InferenceService(model_dir, device) + + if backend_url: + return service.run_backend_inference( + image_paths=image_paths, + export_dir=export_dir, + backend_url=backend_url, + export_format=export_format, + process_res=process_res, + process_res_method=process_res_method, + export_feat_layers=export_feat_layers, + extrinsics=extrinsics, + intrinsics=intrinsics, + align_to_input_ext_scale=align_to_input_ext_scale, + use_ray_pose=use_ray_pose, + ref_view_strategy=ref_view_strategy, + conf_thresh_percentile=conf_thresh_percentile, + num_max_points=num_max_points, + show_cameras=show_cameras, + feat_vis_fps=feat_vis_fps, + ) + else: + return service.run_local_inference( + image_paths=image_paths, + export_dir=export_dir, + export_format=export_format, + process_res=process_res, + process_res_method=process_res_method, + export_feat_layers=export_feat_layers, + extrinsics=extrinsics, + intrinsics=intrinsics, + align_to_input_ext_scale=align_to_input_ext_scale, + use_ray_pose=use_ray_pose, + ref_view_strategy=ref_view_strategy, + conf_thresh_percentile=conf_thresh_percentile, + num_max_points=num_max_points, + show_cameras=show_cameras, + feat_vis_fps=feat_vis_fps, + ) diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/services/input_handlers.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/services/input_handlers.py new file mode 100644 index 0000000000000000000000000000000000000000..dc0536b51e5c71bb6fb9d10f8e74fbb12fc42d31 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/services/input_handlers.py @@ -0,0 +1,266 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Input Processing Service +Handles different types of inputs (image, images, colmap, video) +""" + +import glob +import os +from typing import List, Tuple +import cv2 +import numpy as np +import typer + +from ..utils.read_write_model import read_model + + +class InputHandler: + """Base input handler class""" + + @staticmethod + def validate_path(path: str, path_type: str = "file") -> str: + """Validate path""" + if not os.path.exists(path): + raise typer.BadParameter(f"{path_type} not found: {path}") + return path + + @staticmethod + def handle_export_dir(export_dir: str, auto_cleanup: bool = False) -> str: + """Handle export directory""" + if os.path.exists(export_dir): + if auto_cleanup: + typer.echo(f"Auto-cleaning existing export directory: {export_dir}") + import shutil + + shutil.rmtree(export_dir) + os.makedirs(export_dir, exist_ok=True) + else: + typer.echo(f"Export directory '{export_dir}' already exists.") + if typer.confirm("Do you want to clean it and continue?"): + import shutil + + shutil.rmtree(export_dir) + os.makedirs(export_dir, exist_ok=True) + typer.echo(f"Cleaned export directory: {export_dir}") + else: + typer.echo("Operation cancelled.") + raise typer.Exit(0) + else: + os.makedirs(export_dir, exist_ok=True) + return export_dir + + +class ImageHandler(InputHandler): + """Single image handler""" + + @staticmethod + def process(image_path: str) -> List[str]: + """Process single image""" + InputHandler.validate_path(image_path, "Image file") + return [image_path] + + +class ImagesHandler(InputHandler): + """Image directory handler""" + + @staticmethod + def process(images_dir: str, image_extensions: str = "png,jpg,jpeg") -> List[str]: + """Process image directory""" + InputHandler.validate_path(images_dir, "Images directory") + + # Parse extensions + extensions = [ext.strip().lower() for ext in image_extensions.split(",")] + extensions = [ext if ext.startswith(".") else f".{ext}" for ext in extensions] + + # Find image files + image_files = [] + for ext in extensions: + pattern = f"*{ext}" + image_files.extend(glob.glob(os.path.join(images_dir, pattern))) + image_files.extend(glob.glob(os.path.join(images_dir, pattern.upper()))) + + image_files = sorted(list(set(image_files))) # Remove duplicates and sort + + if not image_files: + raise typer.BadParameter( + f"No image files found in {images_dir} with extensions: {extensions}" + ) + + typer.echo(f"Found {len(image_files)} images to process") + return image_files + + +class ColmapHandler(InputHandler): + """COLMAP data handler""" + + @staticmethod + def process( + colmap_dir: str, sparse_subdir: str = "" + ) -> Tuple[List[str], np.ndarray, np.ndarray]: + """Process COLMAP data""" + InputHandler.validate_path(colmap_dir, "COLMAP directory") + + # Build paths + images_dir = os.path.join(colmap_dir, "images") + if sparse_subdir: + sparse_dir = os.path.join(colmap_dir, "sparse", sparse_subdir) + else: + sparse_dir = os.path.join(colmap_dir, "sparse") + + InputHandler.validate_path(images_dir, "Images directory") + InputHandler.validate_path(sparse_dir, "Sparse reconstruction directory") + + # Load COLMAP data + typer.echo("Loading COLMAP reconstruction data...") + try: + cameras, images, points3D = read_model(sparse_dir) + + typer.echo( + f"Loaded COLMAP data: {len(cameras)} cameras, {len(images)} images, " + f"{len(points3D)} 3D points." + ) + + # Get image files and pose data + image_files = [] + extrinsics = [] + intrinsics = [] + + for image_id, image_data in images.items(): + image_name = image_data.name + image_path = os.path.join(images_dir, image_name) + + if os.path.exists(image_path): + image_files.append(image_path) + + # Get camera parameters + camera = cameras[image_data.camera_id] + + # Convert quaternion to rotation matrix + R = image_data.qvec2rotmat() + t = image_data.tvec + + # Create extrinsic matrix (world to camera) + extrinsic = np.eye(4) + extrinsic[:3, :3] = R + extrinsic[:3, 3] = t + extrinsics.append(extrinsic) + + # Create intrinsic matrix + if camera.model == "PINHOLE": + fx, fy, cx, cy = camera.params + elif camera.model == "SIMPLE_PINHOLE": + f, cx, cy = camera.params + fx = fy = f + else: + # For other models, use basic pinhole approximation + fx = fy = camera.params[0] if len(camera.params) > 0 else 1000 + cx = camera.width / 2 + cy = camera.height / 2 + + intrinsic = np.array([[fx, 0, cx], [0, fy, cy], [0, 0, 1]]) + intrinsics.append(intrinsic) + + if not image_files: + raise typer.BadParameter("No valid images found in COLMAP data") + + typer.echo(f"Found {len(image_files)} valid images with pose data") + + return image_files, np.array(extrinsics), np.array(intrinsics) + + except Exception as e: + raise typer.BadParameter(f"Failed to load COLMAP data: {e}") + + +class VideoHandler(InputHandler): + """Video handler""" + + @staticmethod + def process(video_path: str, output_dir: str, fps: float = 1.0) -> List[str]: + """Process video, extract frames""" + InputHandler.validate_path(video_path, "Video file") + + cap = cv2.VideoCapture(video_path) + if not cap.isOpened(): + raise typer.BadParameter(f"Cannot open video: {video_path}") + + # Get video properties + video_fps = cap.get(cv2.CAP_PROP_FPS) + total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) + duration = total_frames / video_fps + + # Calculate frame interval (ensure at least 1) + frame_interval = max(1, int(video_fps / fps)) + actual_fps = video_fps / frame_interval + + typer.echo(f"Video FPS: {video_fps:.2f}, Duration: {duration:.2f}s") + + # Warn if requested FPS is higher than video FPS + if fps > video_fps: + typer.echo( + f"⚠️ Warning: Requested sampling FPS ({fps:.2f}) exceeds video FPS ({video_fps:.2f})", # noqa: E501 + err=True, + ) + typer.echo( + f"⚠️ Using maximum available FPS: {actual_fps:.2f} (extracting every frame)", + err=True, + ) + + typer.echo(f"Extracting frames at {actual_fps:.2f} FPS (every {frame_interval} frame(s))") + + # Create output directory + frames_dir = os.path.join(output_dir, "input_images") + os.makedirs(frames_dir, exist_ok=True) + + frame_count = 0 + saved_count = 0 + + while True: + ret, frame = cap.read() + if not ret: + break + + if frame_count % frame_interval == 0: + frame_path = os.path.join(frames_dir, f"{saved_count:06d}.png") + cv2.imwrite(frame_path, frame) + saved_count += 1 + + frame_count += 1 + + cap.release() + typer.echo(f"Extracted {saved_count} frames to {frames_dir}") + + # Get frame file list + frame_files = sorted( + [f for f in os.listdir(frames_dir) if f.endswith((".png", ".jpg", ".jpeg"))] + ) + if not frame_files: + raise typer.BadParameter("No frames extracted from video") + + return [os.path.join(frames_dir, f) for f in frame_files] + + +def parse_export_feat(export_feat_str: str) -> List[int]: + """Parse export_feat parameter""" + if not export_feat_str: + return [] + + try: + return [int(x.strip()) for x in export_feat_str.split(",") if x.strip()] + except ValueError: + raise typer.BadParameter( + f"Invalid export_feat format: {export_feat_str}. " + "Use comma-separated integers like '0,1,2'" + ) diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/specs.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/specs.py new file mode 100644 index 0000000000000000000000000000000000000000..fe5b30255e9fd48d988ff00c896fb3dbadf197ea --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/specs.py @@ -0,0 +1,45 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any, Optional +import numpy as np +import torch + + +@dataclass +class Gaussians: + """3DGS parameters, all in world space""" + + means: torch.Tensor # world points, "batch gaussian dim" + scales: torch.Tensor # scales_std, "batch gaussian 3" + rotations: torch.Tensor # world_quat_wxyz, "batch gaussian 4" + harmonics: torch.Tensor # world SH, "batch gaussian 3 d_sh" + opacities: torch.Tensor # opacity | opacity SH, "batch gaussian" | "batch gaussian 1 d_sh" + + +@dataclass +class Prediction: + depth: np.ndarray # N, H, W + is_metric: int + sky: np.ndarray | None = None # N, H, W + conf: np.ndarray | None = None # N, H, W + extrinsics: np.ndarray | None = None # N, 4, 4 + intrinsics: np.ndarray | None = None # N, 3, 3 + processed_images: np.ndarray | None = None # N, H, W, 3 - processed images for visualization + gaussians: Gaussians | None = None # 3D gaussians + aux: dict[str, Any] = None # + scale_factor: Optional[float] = None # metric scale diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/alignment.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/alignment.py new file mode 100644 index 0000000000000000000000000000000000000000..ceb8983fbb85fd8cad51fdd82b794aa3a114df78 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/alignment.py @@ -0,0 +1,163 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Alignment utilities for depth estimation and metric scaling. +""" + +from typing import Tuple +import torch + + +def least_squares_scale_scalar( + a: torch.Tensor, b: torch.Tensor, eps: float = 1e-12 +) -> torch.Tensor: + """ + Compute least squares scale factor s such that a ≈ s * b. + + Args: + a: First tensor + b: Second tensor + eps: Small epsilon for numerical stability + + Returns: + Scalar tensor containing the scale factor + + Raises: + ValueError: If tensors have mismatched shapes or devices + TypeError: If tensors are not floating point + """ + if a.shape != b.shape: + raise ValueError(f"Shape mismatch: {a.shape} vs {b.shape}") + if a.device != b.device: + raise ValueError(f"Device mismatch: {a.device} vs {b.device}") + if not a.is_floating_point() or not b.is_floating_point(): + raise TypeError("Tensors must be floating point type") + + # Compute dot products for least squares solution + num = torch.dot(a.reshape(-1), b.reshape(-1)) + den = torch.dot(b.reshape(-1), b.reshape(-1)).clamp_min(eps) + return num / den + + +def compute_sky_mask(sky_prediction: torch.Tensor, threshold: float = 0.3) -> torch.Tensor: + """ + Compute non-sky mask from sky prediction. + + Args: + sky_prediction: Sky prediction tensor + threshold: Threshold for sky classification + + Returns: + Boolean mask where True indicates non-sky regions + """ + return sky_prediction < threshold + + +def compute_alignment_mask( + depth_conf: torch.Tensor, + non_sky_mask: torch.Tensor, + depth: torch.Tensor, + metric_depth: torch.Tensor, + median_conf: torch.Tensor, + min_depth_threshold: float = 1e-3, + min_metric_depth_threshold: float = 1e-2, +) -> torch.Tensor: + """ + Compute mask for depth alignment based on confidence and depth thresholds. + + Args: + depth_conf: Depth confidence tensor + non_sky_mask: Non-sky region mask + depth: Predicted depth tensor + metric_depth: Metric depth tensor + median_conf: Median confidence threshold + min_depth_threshold: Minimum depth threshold + min_metric_depth_threshold: Minimum metric depth threshold + + Returns: + Boolean mask for valid alignment regions + """ + return ( + (depth_conf >= median_conf) + & non_sky_mask + & (metric_depth > min_metric_depth_threshold) + & (depth > min_depth_threshold) + ) + + +def sample_tensor_for_quantile(tensor: torch.Tensor, max_samples: int = 100000) -> torch.Tensor: + """ + Sample tensor elements for quantile computation to reduce memory usage. + + Args: + tensor: Input tensor to sample + max_samples: Maximum number of samples to take + + Returns: + Sampled tensor + """ + if tensor.numel() <= max_samples: + return tensor + + idx = torch.randperm(tensor.numel(), device=tensor.device)[:max_samples] + return tensor.flatten()[idx] + + +def apply_metric_scaling( + depth: torch.Tensor, intrinsics: torch.Tensor, scale_factor: float = 300.0 +) -> torch.Tensor: + """ + Apply metric scaling to depth based on camera intrinsics. + + Args: + depth: Input depth tensor + intrinsics: Camera intrinsics tensor + scale_factor: Scaling factor for metric conversion + + Returns: + Scaled depth tensor + """ + focal_length = (intrinsics[:, :, 0, 0] + intrinsics[:, :, 1, 1]) / 2 + return depth * (focal_length[:, :, None, None] / scale_factor) + + +def set_sky_regions_to_max_depth( + depth: torch.Tensor, + depth_conf: torch.Tensor, + non_sky_mask: torch.Tensor, + max_depth: float = 200.0, +) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Set sky regions to maximum depth and high confidence. + + Args: + depth: Depth tensor + depth_conf: Depth confidence tensor + non_sky_mask: Non-sky region mask + max_depth: Maximum depth value for sky regions + + Returns: + Tuple of (updated_depth, updated_depth_conf) + """ + depth = depth.clone() + + # Set sky regions to max depth and high confidence + depth[~non_sky_mask] = max_depth + if depth_conf is not None: + depth_conf = depth_conf.clone() + depth_conf[~non_sky_mask] = 1.0 + return depth, depth_conf + else: + return depth, None diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/api_helpers.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/api_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..b327331d9ec61a3047be3e330f41156eb124adc4 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/api_helpers.py @@ -0,0 +1,58 @@ +import argparse + + +def parse_scalar(s): + if not isinstance(s, str): + return s + t = s.strip() + l = t.lower() + if l == "true": + return True + if l == "false": + return False + if l in ("none", "null"): + return None + try: + return int(t, 10) + except Exception: + pass + try: + return float(t) + except Exception: + return s + + +def fn_kv_csv(s: str) -> dict[str, dict[str, object]]: + """ + Parse a string of comma-separated triplets: fn:key:value + + Returns: + dict[fn_name] -> dict[key] = parsed_value + + Example: + "fn1:width:1920,fn1:height:1080,fn2:quality:0.8" + -> {"fn1": {"width": 1920, "height": 1080}, "fn2": {"quality": 0.8}} + """ + result: dict[str, dict[str, object]] = {} + if not s: + return result + + for item in s.split(","): + if not item: + continue + parts = item.split(":", 2) # allow value to contain ":" beyond first two separators + if len(parts) < 3: + raise argparse.ArgumentTypeError(f"Bad item '{item}', expected FN:KEY:VALUE") + fn, key, raw_val = parts[0], parts[1], parts[2] + # If you need to allow colons in values, join leftover parts: + # fn, key, raw_val = parts[0], parts[1], ":".join(parts[2:]) + + if not fn: + raise argparse.ArgumentTypeError(f"Bad item '{item}': empty function name") + if not key: + raise argparse.ArgumentTypeError(f"Bad item '{item}': empty key") + + val = parse_scalar(raw_val) + bucket = result.setdefault(fn, {}) + bucket[key] = val + return result diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/camera_trj_helpers.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/camera_trj_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..83624f359553908abd28af2d59f2066a7f7a7b15 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/camera_trj_helpers.py @@ -0,0 +1,479 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import cv2 +import numpy as np +import torch +import torch.nn.functional as F +from einops import einsum, rearrange, reduce + +try: + from scipy.spatial.transform import Rotation as R +except ImportError: + from depth_anything_3.utils.logger import logger + + logger.warn("Dependency 'scipy' not found. Required for interpolating camera trajectory.") + +from depth_anything_3.utils.geometry import as_homogeneous + + +@torch.no_grad() +def render_stabilization_path(poses, k_size=45): + """Rendering stabilized camera path. + poses: [batch, 4, 4] or [batch, 3, 4], + return: + smooth path: [batch 4 4]""" + num_frames = poses.shape[0] + device = poses.device + dtype = poses.dtype + + # Early exit for trivial cases + if num_frames <= 1: + return as_homogeneous(poses) + + # Make k_size safe: positive odd and not larger than num_frames + # 1) Ensure odd + if k_size < 1: + k_size = 1 + if k_size % 2 == 0: + k_size += 1 + # 2) Cap to num_frames (keep odd) + max_odd = num_frames if (num_frames % 2 == 1) else (num_frames - 1) + if max_odd < 1: + max_odd = 1 # covers num_frames == 0 theoretically + k_size = min(k_size, max_odd) + # 3) enforce a minimum of 3 when possible (for better smoothing) + if num_frames >= 3 and k_size < 3: + k_size = 3 + + input_poses = [] + for i in range(num_frames): + input_poses.append( + torch.cat([poses[i, :3, 0:1], poses[i, :3, 1:2], poses[i, :3, 3:4]], dim=-1) + ) + input_poses = torch.stack(input_poses) # (num_frames, 3, 3) + + # Prepare Gaussian kernel + gaussian_kernel = cv2.getGaussianKernel(ksize=k_size, sigma=-1).astype(np.float32).squeeze() + gaussian_kernel = torch.tensor(gaussian_kernel, dtype=dtype, device=device).view(1, 1, -1) + pad = k_size // 2 + + output_vectors = [] + for idx in range(3): # For r1, r2, t + vec = ( + input_poses[:, :, idx].T.unsqueeze(0).unsqueeze(0) + ) # (1, 1, 3, num_frames) -> (1, 1, 3, num_frames) + # But actually, we want (batch=3, channel=1, width=num_frames) + # So: + vec = input_poses[:, :, idx].T.unsqueeze(1) # (3, 1, num_frames) + vec_padded = F.pad(vec, (pad, pad), mode="reflect") + filtered = F.conv1d(vec_padded, gaussian_kernel) + output_vectors.append(filtered.squeeze(1).T) # (num_frames, 3) + + output_r1, output_r2, output_t = output_vectors # Each is (num_frames, 3) + + # Normalize r1 and r2 + output_r1 = output_r1 / output_r1.norm(dim=-1, keepdim=True) + output_r2 = output_r2 / output_r2.norm(dim=-1, keepdim=True) + + output_poses = [] + for i in range(num_frames): + output_r3 = torch.linalg.cross(output_r1[i], output_r2[i]) + render_pose = torch.cat( + [ + output_r1[i].unsqueeze(-1), + output_r2[i].unsqueeze(-1), + output_r3.unsqueeze(-1), + output_t[i].unsqueeze(-1), + ], + dim=-1, + ) + output_poses.append(render_pose[:3, :]) + output_poses = as_homogeneous(torch.stack(output_poses, dim=0)) + + return output_poses + + +@torch.no_grad() +def render_wander_path( + cam2world: torch.Tensor, + intrinsic: torch.Tensor, + h: int, + w: int, + num_frames: int = 120, + max_disp: float = 48.0, +): + device, dtype = cam2world.device, cam2world.dtype + fx = intrinsic[0, 0] * w + r = max_disp / fx + th = torch.linspace(0, 2.0 * torch.pi, steps=num_frames, device=device, dtype=dtype) + x = r * torch.sin(th) + yz = r * torch.cos(th) / 3.0 + T = torch.eye(4, device=device, dtype=dtype).unsqueeze(0).repeat(num_frames, 1, 1) + T[:, :3, 3] = torch.stack([x, yz, yz], dim=-1) * -1.0 + c2ws = cam2world.unsqueeze(0) @ T + # Start at reference pose and end back at reference pose + c2ws = torch.cat([cam2world.unsqueeze(0), c2ws, cam2world.unsqueeze(0)], dim=0) + Ks = intrinsic.unsqueeze(0).repeat(c2ws.shape[0], 1, 1) + return c2ws, Ks + + +@torch.no_grad() +def render_dolly_zoom_path( + cam2world: torch.Tensor, + intrinsic: torch.Tensor, + h: int, + w: int, + num_frames: int = 120, + max_disp: float = 0.1, + D_focus: float = 10.0, +): + device, dtype = cam2world.device, cam2world.dtype + fx0, fy0 = intrinsic[0, 0] * w, intrinsic[1, 1] * h + t = torch.linspace(0.0, 2.0, steps=num_frames, device=device, dtype=dtype) + z = 0.5 * (1.0 - torch.cos(torch.pi * t)) * max_disp + T = torch.eye(4, device=device, dtype=dtype).unsqueeze(0).repeat(num_frames, 1, 1) + T[:, 2, 3] = -z + c2ws = cam2world.unsqueeze(0) @ T + Df = torch.as_tensor(D_focus, device=device, dtype=dtype) + scale = (Df / (Df + z)).clamp(min=1e-6) + Ks = intrinsic.unsqueeze(0).repeat(num_frames, 1, 1) + Ks[:, 0, 0] = (fx0 * scale) / w + Ks[:, 1, 1] = (fy0 * scale) / h + return c2ws, Ks + + +@torch.no_grad() +def interpolate_intrinsics( + initial: torch.Tensor, # "*#batch 3 3" + final: torch.Tensor, # "*#batch 3 3" + t: torch.Tensor, # " time_step" +) -> torch.Tensor: # "*batch time_step 3 3" + initial = rearrange(initial, "... i j -> ... () i j") + final = rearrange(final, "... i j -> ... () i j") + t = rearrange(t, "t -> t () ()") + return initial + (final - initial) * t + + +def intersect_rays( + a_origins: torch.Tensor, # "*#batch dim" + a_directions: torch.Tensor, # "*#batch dim" + b_origins: torch.Tensor, # "*#batch dim" + b_directions: torch.Tensor, # "*#batch dim" +) -> torch.Tensor: # "*batch dim" + """Compute the least-squares intersection of rays. Uses the math from here: + https://math.stackexchange.com/a/1762491/286022 + """ + + # Broadcast and stack the tensors. + a_origins, a_directions, b_origins, b_directions = torch.broadcast_tensors( + a_origins, a_directions, b_origins, b_directions + ) + origins = torch.stack((a_origins, b_origins), dim=-2) + directions = torch.stack((a_directions, b_directions), dim=-2) + + # Compute n_i * n_i^T - eye(3) from the equation. + n = einsum(directions, directions, "... n i, ... n j -> ... n i j") + n = n - torch.eye(3, dtype=origins.dtype, device=origins.device) + + # Compute the left-hand side of the equation. + lhs = reduce(n, "... n i j -> ... i j", "sum") + + # Compute the right-hand side of the equation. + rhs = einsum(n, origins, "... n i j, ... n j -> ... n i") + rhs = reduce(rhs, "... n i -> ... i", "sum") + + # Left-matrix-multiply both sides by the inverse of lhs to find p. + return torch.linalg.lstsq(lhs, rhs).solution + + +def normalize(a: torch.Tensor) -> torch.Tensor: # "*#batch dim" -> "*#batch dim" + return a / a.norm(dim=-1, keepdim=True) + + +def generate_coordinate_frame( + y: torch.Tensor, # "*#batch 3" + z: torch.Tensor, # "*#batch 3" +) -> torch.Tensor: # "*batch 3 3" + """Generate a coordinate frame given perpendicular, unit-length Y and Z vectors.""" + y, z = torch.broadcast_tensors(y, z) + return torch.stack([y.cross(z, dim=-1), y, z], dim=-1) + + +def generate_rotation_coordinate_frame( + a: torch.Tensor, # "*#batch 3" + b: torch.Tensor, # "*#batch 3" + eps: float = 1e-4, +) -> torch.Tensor: # "*batch 3 3" + """Generate a coordinate frame where the Y direction is normal to the plane defined + by unit vectors a and b. The other axes are arbitrary.""" + device = a.device + + # Replace every entry in b that's parallel to the corresponding entry in a with an + # arbitrary vector. + b = b.detach().clone() + parallel = (einsum(a, b, "... i, ... i -> ...").abs() - 1).abs() < eps + b[parallel] = torch.tensor([0, 0, 1], dtype=b.dtype, device=device) + parallel = (einsum(a, b, "... i, ... i -> ...").abs() - 1).abs() < eps + b[parallel] = torch.tensor([0, 1, 0], dtype=b.dtype, device=device) + + # Generate the coordinate frame. The initial cross product defines the plane. + return generate_coordinate_frame(normalize(torch.linalg.cross(a, b)), a) + + +def matrix_to_euler( + rotations: torch.Tensor, # "*batch 3 3" + pattern: str, +) -> torch.Tensor: # "*batch 3" + *batch, _, _ = rotations.shape + rotations = rotations.reshape(-1, 3, 3) + angles_np = R.from_matrix(rotations.detach().cpu().numpy()).as_euler(pattern) + rotations = torch.tensor(angles_np, dtype=rotations.dtype, device=rotations.device) + return rotations.reshape(*batch, 3) + + +def euler_to_matrix( + rotations: torch.Tensor, # "*batch 3" + pattern: str, +) -> torch.Tensor: # "*batch 3 3" + *batch, _ = rotations.shape + rotations = rotations.reshape(-1, 3) + matrix_np = R.from_euler(pattern, rotations.detach().cpu().numpy()).as_matrix() + rotations = torch.tensor(matrix_np, dtype=rotations.dtype, device=rotations.device) + return rotations.reshape(*batch, 3, 3) + + +def extrinsics_to_pivot_parameters( + extrinsics: torch.Tensor, # "*#batch 4 4" + pivot_coordinate_frame: torch.Tensor, # "*#batch 3 3" + pivot_point: torch.Tensor, # "*#batch 3" +) -> torch.Tensor: # "*batch 5" + """Convert the extrinsics to a representation with 5 degrees of freedom: + 1. Distance from pivot point in the "X" (look cross pivot axis) direction. + 2. Distance from pivot point in the "Y" (pivot axis) direction. + 3. Distance from pivot point in the Z (look) direction + 4. Angle in plane + 5. Twist (rotation not in plane) + """ + + # The pivot coordinate frame's Z axis is normal to the plane. + pivot_axis = pivot_coordinate_frame[..., :, 1] + + # Compute the translation elements of the pivot parametrization. + translation_frame = generate_coordinate_frame(pivot_axis, extrinsics[..., :3, 2]) + origin = extrinsics[..., :3, 3] + delta = pivot_point - origin + translation = einsum(translation_frame, delta, "... i j, ... i -> ... j") + + # Add the rotation elements of the pivot parametrization. + inverted = pivot_coordinate_frame.inverse() @ extrinsics[..., :3, :3] + y, _, z = matrix_to_euler(inverted, "YXZ").unbind(dim=-1) + + return torch.cat([translation, y[..., None], z[..., None]], dim=-1) + + +def pivot_parameters_to_extrinsics( + parameters: torch.Tensor, # "*#batch 5" + pivot_coordinate_frame: torch.Tensor, # "*#batch 3 3" + pivot_point: torch.Tensor, # "*#batch 3" +) -> torch.Tensor: # "*batch 4 4" + translation, y, z = parameters.split((3, 1, 1), dim=-1) + + euler = torch.cat((y, torch.zeros_like(y), z), dim=-1) + rotation = pivot_coordinate_frame @ euler_to_matrix(euler, "YXZ") + + # The pivot coordinate frame's Z axis is normal to the plane. + pivot_axis = pivot_coordinate_frame[..., :, 1] + + translation_frame = generate_coordinate_frame(pivot_axis, rotation[..., :3, 2]) + delta = einsum(translation_frame, translation, "... i j, ... j -> ... i") + origin = pivot_point - delta + + *batch, _ = origin.shape + extrinsics = torch.eye(4, dtype=parameters.dtype, device=parameters.device) + extrinsics = extrinsics.broadcast_to((*batch, 4, 4)).clone() + extrinsics[..., 3, 3] = 1 + extrinsics[..., :3, :3] = rotation + extrinsics[..., :3, 3] = origin + return extrinsics + + +def interpolate_circular( + a: torch.Tensor, # "*#batch" + b: torch.Tensor, # "*#batch" + t: torch.Tensor, # "*#batch" +) -> torch.Tensor: # " *batch" + a, b, t = torch.broadcast_tensors(a, b, t) + + tau = 2 * torch.pi + a = a % tau + b = b % tau + + # Consider piecewise edge cases. + d = (b - a).abs() + a_left = a - tau + d_left = (b - a_left).abs() + a_right = a + tau + d_right = (b - a_right).abs() + use_d = (d < d_left) & (d < d_right) + use_d_left = (d_left < d_right) & (~use_d) + use_d_right = (~use_d) & (~use_d_left) + + result = a + (b - a) * t + result[use_d_left] = (a_left + (b - a_left) * t)[use_d_left] + result[use_d_right] = (a_right + (b - a_right) * t)[use_d_right] + + return result + + +def interpolate_pivot_parameters( + initial: torch.Tensor, # "*#batch 5" + final: torch.Tensor, # "*#batch 5" + t: torch.Tensor, # " time_step" +) -> torch.Tensor: # "*batch time_step 5" + initial = rearrange(initial, "... d -> ... () d") + final = rearrange(final, "... d -> ... () d") + t = rearrange(t, "t -> t ()") + ti, ri = initial.split((3, 2), dim=-1) + tf, rf = final.split((3, 2), dim=-1) + + t_lerp = ti + (tf - ti) * t + r_lerp = interpolate_circular(ri, rf, t) + + return torch.cat((t_lerp, r_lerp), dim=-1) + + +@torch.no_grad() +def interpolate_extrinsics( + initial: torch.Tensor, # "*#batch 4 4" + final: torch.Tensor, # "*#batch 4 4" + t: torch.Tensor, # " time_step" + eps: float = 1e-4, +) -> torch.Tensor: # "*batch time_step 4 4" + """Interpolate extrinsics by rotating around their "focus point," which is the + least-squares intersection between the look vectors of the initial and final + extrinsics. + """ + + initial = initial.type(torch.float64) + final = final.type(torch.float64) + t = t.type(torch.float64) + + # Based on the dot product between the look vectors, pick from one of two cases: + # 1. Look vectors are parallel: interpolate about their origins' midpoint. + # 3. Look vectors aren't parallel: interpolate about their focus point. + initial_look = initial[..., :3, 2] + final_look = final[..., :3, 2] + dot_products = einsum(initial_look, final_look, "... i, ... i -> ...") + parallel_mask = (dot_products.abs() - 1).abs() < eps + + # Pick focus points. + initial_origin = initial[..., :3, 3] + final_origin = final[..., :3, 3] + pivot_point = 0.5 * (initial_origin + final_origin) + pivot_point[~parallel_mask] = intersect_rays( + initial_origin[~parallel_mask], + initial_look[~parallel_mask], + final_origin[~parallel_mask], + final_look[~parallel_mask], + ) + + # Convert to pivot parameters. + pivot_frame = generate_rotation_coordinate_frame(initial_look, final_look, eps=eps) + initial_params = extrinsics_to_pivot_parameters(initial, pivot_frame, pivot_point) + final_params = extrinsics_to_pivot_parameters(final, pivot_frame, pivot_point) + + # Interpolate the pivot parameters. + interpolated_params = interpolate_pivot_parameters(initial_params, final_params, t) + + # Convert back. + return pivot_parameters_to_extrinsics( + interpolated_params.type(torch.float32), + rearrange(pivot_frame, "... i j -> ... () i j").type(torch.float32), + rearrange(pivot_point, "... xyz -> ... () xyz").type(torch.float32), + ) + + +@torch.no_grad() +def generate_wobble_transformation( + radius: torch.Tensor, # "*#batch" + t: torch.Tensor, # " time_step" + num_rotations: int = 1, + scale_radius_with_t: bool = True, +) -> torch.Tensor: # "*batch time_step 4 4"]: + # Generate a translation in the image plane. + tf = torch.eye(4, dtype=torch.float32, device=t.device) + tf = tf.broadcast_to((*radius.shape, t.shape[0], 4, 4)).clone() + radius = radius[..., None] + if scale_radius_with_t: + radius = radius * t + tf[..., 0, 3] = torch.sin(2 * torch.pi * num_rotations * t) * radius + tf[..., 1, 3] = -torch.cos(2 * torch.pi * num_rotations * t) * radius + return tf + + +@torch.no_grad() +def render_wobble_inter_path( + cam2world: torch.Tensor, intr_normed: torch.Tensor, inter_len: int, n_skip: int = 3 +): + """ + cam2world: [batch, 4, 4], + intr_normed: [batch, 3, 3] + """ + frame_per_round = n_skip * inter_len + num_rotations = 1 + + t = torch.linspace(0, 1, frame_per_round, dtype=torch.float32, device=cam2world.device) + # t = (torch.cos(torch.pi * (t + 1)) + 1) / 2 + tgt_c2w_b = [] + tgt_intr_b = [] + for b_idx in range(cam2world.shape[0]): + tgt_c2w = [] + tgt_intr = [] + for cur_idx in range(0, cam2world.shape[1] - n_skip, n_skip): + origin_a = cam2world[b_idx, cur_idx, :3, 3] + origin_b = cam2world[b_idx, cur_idx + n_skip, :3, 3] + delta = (origin_a - origin_b).norm(dim=-1) + if cur_idx == 0: + delta_prev = delta + else: + delta = (delta_prev + delta) / 2 + delta_prev = delta + tf = generate_wobble_transformation( + radius=delta * 0.5, + t=t, + num_rotations=num_rotations, + scale_radius_with_t=False, + ) + cur_extrs = ( + interpolate_extrinsics( + cam2world[b_idx, cur_idx], + cam2world[b_idx, cur_idx + n_skip], + t, + ) + @ tf + ) + tgt_c2w.append(cur_extrs[(0 if cur_idx == 0 else 1) :]) + tgt_intr.append( + interpolate_intrinsics( + intr_normed[b_idx, cur_idx], + intr_normed[b_idx, cur_idx + n_skip], + t, + )[(0 if cur_idx == 0 else 1) :] + ) + tgt_c2w_b.append(torch.cat(tgt_c2w)) + tgt_intr_b.append(torch.cat(tgt_intr)) + tgt_c2w = torch.stack(tgt_c2w_b) # b v 4 4 + tgt_intr = torch.stack(tgt_intr_b) # b v 3 3 + return tgt_c2w, tgt_intr diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/constants.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..b48206dafffb73c83b5bcd0b3e7020f51d3c5790 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/constants.py @@ -0,0 +1,270 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +DEFAULT_MODEL = "depth-anything/DA3NESTED-GIANT-LARGE" +DEFAULT_EXPORT_DIR = "workspace/gallery/scene" +DEFAULT_GALLERY_DIR = "workspace/gallery" +DEFAULT_GRADIO_DIR = "workspace/gradio" +THRESH_FOR_REF_SELECTION = 3 + +# ============================================================================= +# Benchmark Evaluation Constants +# ============================================================================= + +# Default evaluation workspace directory +DEFAULT_EVAL_WORKSPACE = "workspace/evaluation" + +# Default reference view selection strategy for evaluation +# Use "first" for consistent and reproducible evaluation results +# Other options: "saddle_balanced", "auto", "mid" +EVAL_REF_VIEW_STRATEGY = "first" + +# ----------------------------------------------------------------------------- +# DTU Dataset Configuration +# Reference: https://roboimagedata.compute.dtu.dk/ +# Note: DepthAnything3 was never trained on any images from DTU. +# ----------------------------------------------------------------------------- + +# Root directory for DTU evaluation data (MVSNet format) +# Download from: https://drive.google.com/file/d/1rX0EXlUL4prRxrRu2DgLJv2j7-tpUD4D/view +DTU_EVAL_DATA_ROOT = "workspace/benchmark_dataset/dtu" + +# List of DTU evaluation scenes +DTU_SCENES = [ + "scan1", + "scan4", + "scan9", + "scan10", + "scan11", + "scan12", + "scan13", + "scan15", + "scan23", + "scan24", + "scan29", + "scan32", + "scan33", + "scan34", + "scan48", + "scan49", + "scan62", + "scan75", + "scan77", + "scan110", + "scan114", + "scan118", +] + +# Point cloud fusion hyperparameters +DTU_DIST_THRESH = 0.2 # Distance threshold for geometric consistency (mm) +DTU_NUM_CONSIST = 4 # Minimum number of consistent views for a point +DTU_MAX_POINTS = 4_000_000 # Maximum points in fused point cloud + +# 3D reconstruction evaluation hyperparameters +DTU_DOWN_DENSE = 0.2 # Downsample density for evaluation (mm) +DTU_PATCH_SIZE = 60 # Patch size for boundary handling +DTU_MAX_DIST = 20 # Outlier threshold for accuracy/completeness (mm) + +# ----------------------------------------------------------------------------- +# DTU-64 Dataset Configuration (Pose Evaluation Only) +# This is a subset of DTU with 64 images per scene for pose evaluation. +# Note: This dataset is ONLY for pose evaluation, not 3D reconstruction. +# ----------------------------------------------------------------------------- + +# Root directory for DTU-64 evaluation data +DTU64_EVAL_DATA_ROOT = "workspace/benchmark_dataset/dtu64" +DTU64_CAMERA_ROOT = "workspace/benchmark_dataset/dtu64/Cameras" + +# List of DTU-64 evaluation scenes (13 scenes) +DTU64_SCENES = [ + "scan105", + "scan114", + "scan118", + "scan122", + "scan24", + "scan37", + "scan40", + "scan55", + "scan63", + "scan65", + "scan69", + "scan83", + "scan97", +] + +# ----------------------------------------------------------------------------- +# ETH3D Dataset Configuration +# Reference: https://www.eth3d.net/ +# High-resolution multi-view stereo benchmark with laser-scanned ground truth. +# Note: DepthAnything3 was never trained on any images from ETH3D. +# ----------------------------------------------------------------------------- + +# Root directory for ETH3D evaluation data +ETH3D_EVAL_DATA_ROOT = "workspace/benchmark_dataset/eth3d" + +# List of ETH3D evaluation scenes (indoor and outdoor) +ETH3D_SCENES = [ + "courtyard", + "electro", + "kicker", + "pipes", + "relief", + # "terrace", # Excluded: known issues + "delivery_area", + "facade", + # "meadow", # Excluded: known issues + "office", + "playground", + "relief_2", + "terrains", +] + +# Images to filter out (known problematic views per scene) +ETH3D_FILTER_KEYS = { + "delivery_area": ["711.JPG", "712.JPG", "713.JPG", "714.JPG"], + "electro": ["9289.JPG", "9290.JPG", "9291.JPG", "9292.JPG", "9293.JPG", "9298.JPG"], + "playground": ["587.JPG", "588.JPG", "589.JPG", "590.JPG", "591.JPG", "592.JPG"], + "relief": [ + "427.JPG", "428.JPG", "429.JPG", "430.JPG", "431.JPG", "432.JPG", + "433.JPG", "434.JPG", "435.JPG", "436.JPG", "437.JPG", "438.JPG", + ], + "relief_2": [ + "458.JPG", "459.JPG", "460.JPG", "461.JPG", "462.JPG", "463.JPG", + "464.JPG", "465.JPG", "466.JPG", "467.JPG", "468.JPG", + ], +} + +# TSDF fusion hyperparameters (scaled for outdoor scenes) +ETH3D_VOXEL_LENGTH = 4.0 / 512.0 * 5 # Voxel size for TSDF (meters) +ETH3D_SDF_TRUNC = 0.04 * 5 # SDF truncation distance (meters) +ETH3D_MAX_DEPTH = 100000.0 # Maximum depth for integration (effectively no truncation) + +# Point cloud sampling +ETH3D_SAMPLING_NUMBER = 1_000_000 # Number of points to sample from mesh + +# 3D reconstruction evaluation hyperparameters +ETH3D_EVAL_THRESHOLD = 0.05 * 5 # Distance threshold for precision/recall (meters) +ETH3D_DOWN_SAMPLE = 4.0 / 512.0 * 5 # Voxel size for evaluation downsampling (meters) + + +# ============================================================================== +# 7Scenes Dataset Configuration +# ============================================================================== +# Reference: https://www.microsoft.com/en-us/research/project/rgb-d-dataset-7-scenes/ +# Note: Indoor RGB-D dataset with ground truth poses and meshes. + +# Root directory for 7Scenes evaluation data +SEVENSCENES_EVAL_DATA_ROOT = "workspace/benchmark_dataset/7scenes" + +# List of 7Scenes evaluation scenes +SEVENSCENES_SCENES = [ + "chess", + "fire", + "heads", + "office", + "pumpkin", + "redkitchen", + "stairs", +] + +# Fixed camera intrinsics for 7Scenes (all images share same intrinsics) +SEVENSCENES_FX = 585.0 +SEVENSCENES_FY = 585.0 +SEVENSCENES_CX = 320.0 +SEVENSCENES_CY = 240.0 + +# TSDF fusion hyperparameters (indoor scenes, smaller voxels) +SEVENSCENES_VOXEL_LENGTH = 4.0 / 512.0 # Voxel size for TSDF (meters) +SEVENSCENES_SDF_TRUNC = 0.04 # SDF truncation distance (meters) +SEVENSCENES_MAX_DEPTH = 1000000.0 # Maximum depth for integration (no truncation) + +# Point cloud sampling +SEVENSCENES_SAMPLING_NUMBER = 1_000_000 # Number of points to sample from mesh + +# 3D reconstruction evaluation hyperparameters +SEVENSCENES_EVAL_THRESHOLD = 0.05 # Distance threshold for precision/recall (meters) +SEVENSCENES_DOWN_SAMPLE = 4.0 / 512.0 # Voxel size for evaluation downsampling (meters) + + +# ============================================================================== +# ScanNet++ Dataset Configuration +# ============================================================================== +# Reference: https://kaldir.vc.in.tum.de/scannetpp/ +# Note: High-quality indoor RGB-D dataset with iPhone and DSLR images. + +# Root directory for ScanNet++ evaluation data +SCANNETPP_EVAL_DATA_ROOT = "workspace/benchmark_dataset/scannetpp" + +# List of ScanNet++ evaluation scenes +SCANNETPP_SCENES = [ + "09c1414f1b", + "1ada7a0617", + "40aec5fffa", + "3e8bba0176", + "acd95847c5", + "578511c8a9", + "5f99900f09", + "c4c04e6d6c", + "f3d64c30f8", + "7bc286c1b6", + "c5439f4607", + "286b55a2bf", + "fb5a96b1a2", + "7831862f02", + "38d58a7a31", + "bde1e479ad", + "9071e139d9", + "21d970d8de", + "bcd2436daf", + "cc5237fd77", +] + +# Input resolution for ScanNet++ (after undistortion and resize) +SCANNETPP_INPUT_H = 768 +SCANNETPP_INPUT_W = 1024 + +# TSDF fusion hyperparameters (indoor scenes) +SCANNETPP_VOXEL_LENGTH = 0.02 # Voxel size for TSDF (meters) +SCANNETPP_SDF_TRUNC = 0.15 # SDF truncation distance (meters) +SCANNETPP_MAX_DEPTH = 5.0 # Maximum depth for integration (meters) + +# Point cloud sampling +SCANNETPP_SAMPLING_NUMBER = 1_000_000 # Number of points to sample from mesh + +# 3D reconstruction evaluation hyperparameters +SCANNETPP_EVAL_THRESHOLD = 0.05 # Distance threshold for precision/recall (meters) +SCANNETPP_DOWN_SAMPLE = 0.02 # Voxel size for evaluation downsampling (meters) + + +# ============================================================================== +# HiRoom Dataset Configuration +# ============================================================================== +# Note: Indoor RGB-D dataset. + +# Root directory for HiRoom evaluation data +HIROOM_EVAL_DATA_ROOT = "workspace/benchmark_dataset/hiroom/data" +HIROOM_GT_ROOT_PATH = "workspace/benchmark_dataset/hiroom/fused_pcd" +HIROOM_SCENE_LIST_PATH = "workspace/benchmark_dataset/hiroom/selected_scene_list_val.txt" + +# TSDF fusion hyperparameters (indoor scenes) +HIROOM_VOXEL_LENGTH = 4.0 / 512.0 # Voxel size for TSDF (meters) +HIROOM_SDF_TRUNC = 0.04 # SDF truncation distance (meters) +HIROOM_MAX_DEPTH = 10000.0 # Maximum depth for integration (no truncation) + +# Point cloud sampling +HIROOM_SAMPLING_NUMBER = 1_000_000 # Number of points to sample from mesh + +# 3D reconstruction evaluation hyperparameters +HIROOM_EVAL_THRESHOLD = 0.05 # Distance threshold for precision/recall (meters) +HIROOM_DOWN_SAMPLE = 4.0 / 512.0 # Voxel size for evaluation downsampling (meters) diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/export/__init__.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/export/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e3e4c657983b19a75865ad7d3329f9f037f60cd6 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/export/__init__.py @@ -0,0 +1,59 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from depth_anything_3.specs import Prediction +from depth_anything_3.utils.export.gs import export_to_gs_ply, export_to_gs_video + +from .colmap import export_to_colmap +from .depth_vis import export_to_depth_vis +from .feat_vis import export_to_feat_vis +from .glb import export_to_glb +from .npz import export_to_mini_npz, export_to_npz + + +def export( + prediction: Prediction, + export_format: str, + export_dir: str, + **kwargs, +): + if "-" in export_format: + export_formats = export_format.split("-") + for export_format in export_formats: + export(prediction, export_format, export_dir, **kwargs) + return # Prevent falling through to single-format handling + + if export_format == "glb": + export_to_glb(prediction, export_dir, **kwargs.get(export_format, {})) + elif export_format == "mini_npz": + export_to_mini_npz(prediction, export_dir) + elif export_format == "npz": + export_to_npz(prediction, export_dir) + elif export_format == "feat_vis": + export_to_feat_vis(prediction, export_dir, **kwargs.get(export_format, {})) + elif export_format == "depth_vis": + export_to_depth_vis(prediction, export_dir) + elif export_format == "gs_ply": + export_to_gs_ply(prediction, export_dir, **kwargs.get(export_format, {})) + elif export_format == "gs_video": + export_to_gs_video(prediction, export_dir, **kwargs.get(export_format, {})) + elif export_format == "colmap": + export_to_colmap(prediction, export_dir, **kwargs.get(export_format, {})) + else: + raise ValueError(f"Unsupported export format: {export_format}") + + +__all__ = [ + export, +] diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/export/colmap.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/export/colmap.py new file mode 100644 index 0000000000000000000000000000000000000000..e57964cc3302d3f348d91d0b0ecb5d4fe8c0a54b --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/export/colmap.py @@ -0,0 +1,150 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +import pycolmap +import cv2 as cv +import numpy as np + +from PIL import Image + +from depth_anything_3.specs import Prediction +from depth_anything_3.utils.logger import logger + +from .glb import _depths_to_world_points_with_colors + + +def export_to_colmap( + prediction: Prediction, + export_dir: str, + image_paths: list[str], + conf_thresh_percentile: float = 40.0, + process_res_method: str = "upper_bound_resize", +) -> None: + # 1. Data preparation + conf_thresh = np.percentile(prediction.conf, conf_thresh_percentile) + points, colors = _depths_to_world_points_with_colors( + prediction.depth, + prediction.intrinsics, + prediction.extrinsics, # w2c + prediction.processed_images, + prediction.conf, + conf_thresh, + ) + num_points = len(points) + logger.info(f"Exporting to COLMAP with {num_points} points") + num_frames = len(prediction.processed_images) + h, w = prediction.processed_images.shape[1:3] + points_xyf = _create_xyf(num_frames, h, w) + points_xyf = points_xyf[prediction.conf >= conf_thresh] + + # 2. Set Reconstruction + reconstruction = pycolmap.Reconstruction() + + point3d_ids = [] + for vidx in range(num_points): + point3d_id = reconstruction.add_point3D(points[vidx], pycolmap.Track(), colors[vidx]) + point3d_ids.append(point3d_id) + + for fidx in range(num_frames): + orig_w, orig_h = Image.open(image_paths[fidx]).size + + intrinsic = prediction.intrinsics[fidx] + if process_res_method.endswith("resize"): + intrinsic[:1] *= orig_w / w + intrinsic[1:2] *= orig_h / h + elif process_res_method == "crop": + raise NotImplementedError("COLMAP export for crop method is not implemented") + else: + raise ValueError(f"Unknown process_res_method: {process_res_method}") + + pycolmap_intri = np.array( + [intrinsic[0, 0], intrinsic[1, 1], intrinsic[0, 2], intrinsic[1, 2]] + ) + + extrinsic = prediction.extrinsics[fidx] + cam_from_world = pycolmap.Rigid3d(pycolmap.Rotation3d(extrinsic[:3, :3]), extrinsic[:3, 3]) + + # set and add camera + camera = pycolmap.Camera() + camera.camera_id = fidx + 1 + camera.model = pycolmap.CameraModelId.PINHOLE + camera.width = orig_w + camera.height = orig_h + camera.params = pycolmap_intri + reconstruction.add_camera(camera) + + # set and add rig (from camera) + rig = pycolmap.Rig() + rig.rig_id = camera.camera_id + rig.add_ref_sensor(camera.sensor_id) + reconstruction.add_rig(rig) + + # set image + image = pycolmap.Image() + image.image_id = fidx + 1 + image.camera_id = camera.camera_id + + # set and add frame (from image) + frame = pycolmap.Frame() + frame.frame_id = image.image_id + frame.rig_id = camera.camera_id + frame.add_data_id(image.data_id) + frame.rig_from_world = cam_from_world + reconstruction.add_frame(frame) + + # set point2d and update track + point2d_list = [] + points_in_frame = points_xyf[:, 2].astype(np.int32) == fidx + for vidx in np.where(points_in_frame)[0]: + point2d = points_xyf[vidx][:2] + point2d[0] *= orig_w / w + point2d[1] *= orig_h / h + point3d_id = point3d_ids[vidx] + point2d_list.append(pycolmap.Point2D(point2d, point3d_id)) + reconstruction.point3D(point3d_id).track.add_element( + image.image_id, len(point2d_list) - 1 + ) + + # set and add image + image.frame_id = image.image_id + image.name = os.path.basename(image_paths[fidx]) + image.points2D = pycolmap.Point2DList(point2d_list) + reconstruction.add_image(image) + + # 3. Export + reconstruction.write(export_dir) + + +def _create_xyf(num_frames, height, width): + """ + Creates a grid of pixel coordinates and frame indices (fidx) for all frames. + """ + # Create coordinate grids for a single frame + y_grid, x_grid = np.indices((height, width), dtype=np.int32) + x_grid = x_grid[np.newaxis, :, :] + y_grid = y_grid[np.newaxis, :, :] + + # Broadcast to all frames + x_coords = np.broadcast_to(x_grid, (num_frames, height, width)) + y_coords = np.broadcast_to(y_grid, (num_frames, height, width)) + + # Create frame indices and broadcast + f_idx = np.arange(num_frames, dtype=np.int32)[:, np.newaxis, np.newaxis] + f_coords = np.broadcast_to(f_idx, (num_frames, height, width)) + + # Stack coordinates and frame indices + points_xyf = np.stack((x_coords, y_coords, f_coords), axis=-1) + + return points_xyf diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/export/depth_vis.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/export/depth_vis.py new file mode 100644 index 0000000000000000000000000000000000000000..8accc04e92985e26b8d78a56db80989be515aac7 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/export/depth_vis.py @@ -0,0 +1,41 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +import imageio +import numpy as np + +from depth_anything_3.specs import Prediction +from depth_anything_3.utils.visualize import visualize_depth + + +def export_to_depth_vis( + prediction: Prediction, + export_dir: str, +): + # Use prediction.processed_images, which is already processed image data + if prediction.processed_images is None: + raise ValueError("prediction.processed_images is required but not available") + + images_u8 = prediction.processed_images # (N,H,W,3) uint8 + + os.makedirs(os.path.join(export_dir, "depth_vis"), exist_ok=True) + for idx in range(prediction.depth.shape[0]): + depth_vis = visualize_depth(prediction.depth[idx]) + image_vis = images_u8[idx] + depth_vis = depth_vis.astype(np.uint8) + image_vis = image_vis.astype(np.uint8) + vis_image = np.concatenate([image_vis, depth_vis], axis=1) + save_path = os.path.join(export_dir, f"depth_vis/{idx:04d}.jpg") + imageio.imwrite(save_path, vis_image, quality=95) diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/export/feat_vis.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/export/feat_vis.py new file mode 100644 index 0000000000000000000000000000000000000000..e3dc780ea509d8b5f4660212c2914d3e81f2364a --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/export/feat_vis.py @@ -0,0 +1,65 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +import cv2 +import imageio +import numpy as np +from tqdm.auto import tqdm + +from depth_anything_3.utils.parallel_utils import async_call +from depth_anything_3.utils.pca_utils import PCARGBVisualizer + + +@async_call +def export_to_feat_vis( + prediction, + export_dir, + fps=15, +): + """Export feature visualization with PCA. + + Args: + prediction: Model prediction containing feature maps + export_dir: Directory to export results + fps: Frame rate for output video (default: 15) + """ + out_dir = os.path.join(export_dir, "feat_vis") + os.makedirs(out_dir, exist_ok=True) + + images = prediction.processed_images + for k, v in prediction.aux.items(): + if not k.startswith("feat_layer_"): + continue + os.makedirs(os.path.join(out_dir, k), exist_ok=True) + viz = PCARGBVisualizer(basis_mode="fixed", percentile_mode="global", clip_percent=10.0) + viz.fit_reference(v) + feats_vis = viz.transform_video(v) + for idx in tqdm(range(len(feats_vis))): + img = images[idx] + feat_vis = (feats_vis[idx] * 255).astype(np.uint8) + feat_vis = cv2.resize( + feat_vis, (img.shape[1], img.shape[0]), interpolation=cv2.INTER_NEAREST + ) + save_path = os.path.join(out_dir, f"{k}/{idx:06d}.jpg") + save = np.concatenate([img, feat_vis], axis=1) + imageio.imwrite(save_path, save, quality=95) + cmd = ( + "ffmpeg -loglevel error -hide_banner -y " + f"-framerate {fps} -start_number 0 " + f"-i {out_dir}/{k}/%06d.jpg " + f"-c:v libx264 -pix_fmt yuv420p " + f"{out_dir}/{k}.mp4" + ) + os.system(cmd) diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/export/glb.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/export/glb.py new file mode 100644 index 0000000000000000000000000000000000000000..ece1379d98fedceba03cb53ee4cb62bd49a1ae4f --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/export/glb.py @@ -0,0 +1,432 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import os +import numpy as np +import trimesh + +from depth_anything_3.specs import Prediction +from depth_anything_3.utils.logger import logger + +from .depth_vis import export_to_depth_vis + + +def set_sky_depth(prediction: Prediction, sky_mask: np.ndarray, sky_depth_def: float = 98.0): + non_sky_mask = ~sky_mask + valid_depth = prediction.depth[non_sky_mask] + if valid_depth.size > 0: + max_depth = np.percentile(valid_depth, sky_depth_def) + prediction.depth[sky_mask] = max_depth + + +def get_conf_thresh( + prediction: Prediction, + sky_mask: np.ndarray, + conf_thresh: float, + conf_thresh_percentile: float = 10.0, + ensure_thresh_percentile: float = 90.0, +): + if sky_mask is not None and (~sky_mask).sum() > 10: + conf_pixels = prediction.conf[~sky_mask] + else: + conf_pixels = prediction.conf + lower = np.percentile(conf_pixels, conf_thresh_percentile) + upper = np.percentile(conf_pixels, ensure_thresh_percentile) + conf_thresh = min(max(conf_thresh, lower), upper) + return conf_thresh + + +def export_to_glb( + prediction: Prediction, + export_dir: str, + num_max_points: int = 1_000_000, + conf_thresh: float = 1.05, + filter_black_bg: bool = False, + filter_white_bg: bool = False, + conf_thresh_percentile: float = 40.0, + ensure_thresh_percentile: float = 90.0, + sky_depth_def: float = 98.0, + show_cameras: bool = True, + camera_size: float = 0.03, + export_depth_vis: bool = True, +) -> str: + """Generate a 3D point cloud and camera wireframes and export them as a ``.glb`` file. + + The function builds a point cloud from the predicted depth maps, aligns it to the + first camera in glTF coordinates (X-right, Y-up, Z-backward), optionally draws + camera wireframes, and writes the result to ``scene.glb``. Auxiliary assets such as + depth visualizations can also be generated alongside the main export. + + Args: + prediction: Model prediction containing depth, confidence, intrinsics, extrinsics, + and pre-processed images. + export_dir: Output directory where the glTF assets will be written. + num_max_points: Maximum number of points retained after downsampling. + conf_thresh: Base confidence threshold used before percentile adjustments. + filter_black_bg: Mark near-black background pixels for removal during confidence filtering. + filter_white_bg: Mark near-white background pixels for removal during confidence filtering. + conf_thresh_percentile: Lower percentile used when adapting the confidence threshold. + ensure_thresh_percentile: Upper percentile clamp for the adaptive threshold. + sky_depth_def: Percentile used to fill sky pixels with plausible depth values. + show_cameras: Whether to render camera wireframes in the exported scene. + camera_size: Relative camera wireframe scale as a fraction of the scene diagonal. + export_depth_vis: Whether to export raster depth visualisations alongside the glTF. + + Returns: + Path to the exported ``scene.glb`` file. + """ + # 1) Use prediction.processed_images, which is already processed image data + assert ( + prediction.processed_images is not None + ), "Export to GLB: prediction.processed_images is required but not available" + assert ( + prediction.depth is not None + ), "Export to GLB: prediction.depth is required but not available" + assert ( + prediction.intrinsics is not None + ), "Export to GLB: prediction.intrinsics is required but not available" + assert ( + prediction.extrinsics is not None + ), "Export to GLB: prediction.extrinsics is required but not available" + assert ( + prediction.conf is not None + ), "Export to GLB: prediction.conf is required but not available" + logger.info(f"conf_thresh_percentile: {conf_thresh_percentile}") + logger.info(f"num max points: {num_max_points}") + logger.info(f"Exporting to GLB with num_max_points: {num_max_points}") + if prediction.processed_images is None: + raise ValueError("prediction.processed_images is required but not available") + + images_u8 = prediction.processed_images # (N,H,W,3) uint8 + + # 2) Sky processing (if sky_mask is provided) + if getattr(prediction, "sky_mask", None) is not None: + set_sky_depth(prediction, prediction.sky_mask, sky_depth_def) + + # 3) Confidence threshold (if no conf, then no filtering) + if filter_black_bg: + prediction.conf[(prediction.processed_images < 16).all(axis=-1)] = 1.0 + if filter_white_bg: + prediction.conf[(prediction.processed_images >= 240).all(axis=-1)] = 1.0 + conf_thr = get_conf_thresh( + prediction, + getattr(prediction, "sky_mask", None), + conf_thresh, + conf_thresh_percentile, + ensure_thresh_percentile, + ) + + # 4) Back-project to world coordinates and get colors (world frame) + points, colors = _depths_to_world_points_with_colors( + prediction.depth, + prediction.intrinsics, + prediction.extrinsics, # w2c + images_u8, + prediction.conf, + conf_thr, + ) + + # 5) Based on first camera orientation + glTF axis system, center by point cloud, + # construct alignment transform, and apply to point cloud + A = _compute_alignment_transform_first_cam_glTF_center_by_points( + prediction.extrinsics[0], points + ) # (4,4) + + if points.shape[0] > 0: + points = trimesh.transform_points(points, A) + + # 6) Clean + downsample + points, colors = _filter_and_downsample(points, colors, num_max_points) + + # 7) Assemble scene (add point cloud first) + scene = trimesh.Scene() + if scene.metadata is None: + scene.metadata = {} + scene.metadata["hf_alignment"] = A # For camera wireframes and external reuse + + if points.shape[0] > 0: + pc = trimesh.points.PointCloud(vertices=points, colors=colors) + scene.add_geometry(pc) + + # 8) Draw cameras (wireframe pyramids), using the same transform A + if show_cameras and prediction.intrinsics is not None and prediction.extrinsics is not None: + scene_scale = _estimate_scene_scale(points, fallback=1.0) + H, W = prediction.depth.shape[1:] + _add_cameras_to_scene( + scene=scene, + K=prediction.intrinsics, + ext_w2c=prediction.extrinsics, + image_sizes=[(H, W)] * prediction.depth.shape[0], + scale=scene_scale * camera_size, + ) + + # 9) Export + os.makedirs(export_dir, exist_ok=True) + out_path = os.path.join(export_dir, "scene.glb") + scene.export(out_path) + + if export_depth_vis: + export_to_depth_vis(prediction, export_dir) + os.system(f"cp -r {export_dir}/depth_vis/0000.jpg {export_dir}/scene.jpg") + return out_path + + +# ========================= +# utilities +# ========================= + + +def _as_homogeneous44(ext: np.ndarray) -> np.ndarray: + """ + Accept (4,4) or (3,4) extrinsic parameters, return (4,4) homogeneous matrix. + """ + if ext.shape == (4, 4): + return ext + if ext.shape == (3, 4): + H = np.eye(4, dtype=ext.dtype) + H[:3, :4] = ext + return H + raise ValueError(f"extrinsic must be (4,4) or (3,4), got {ext.shape}") + + +def _depths_to_world_points_with_colors( + depth: np.ndarray, + K: np.ndarray, + ext_w2c: np.ndarray, + images_u8: np.ndarray, + conf: np.ndarray | None, + conf_thr: float, +) -> tuple[np.ndarray, np.ndarray]: + """ + For each frame, transform (u,v,1) through K^{-1} to get rays, + multiply by depth to camera frame, then use (w2c)^{-1} to transform to world frame. + Simultaneously extract colors. + """ + N, H, W = depth.shape + us, vs = np.meshgrid(np.arange(W), np.arange(H)) + ones = np.ones_like(us) + pix = np.stack([us, vs, ones], axis=-1).reshape(-1, 3) # (H*W,3) + + pts_all, col_all = [], [] + + for i in range(N): + d = depth[i] # (H,W) + valid = np.isfinite(d) & (d > 0) + if conf is not None: + valid &= conf[i] >= conf_thr + if not np.any(valid): + continue + + d_flat = d.reshape(-1) + vidx = np.flatnonzero(valid.reshape(-1)) + + K_inv = np.linalg.inv(K[i]) # (3,3) + c2w = np.linalg.inv(_as_homogeneous44(ext_w2c[i])) # (4,4) + + rays = K_inv @ pix[vidx].T # (3,M) + Xc = rays * d_flat[vidx][None, :] # (3,M) + Xc_h = np.vstack([Xc, np.ones((1, Xc.shape[1]))]) + Xw = (c2w @ Xc_h)[:3].T.astype(np.float32) # (M,3) + + cols = images_u8[i].reshape(-1, 3)[vidx].astype(np.uint8) # (M,3) + + pts_all.append(Xw) + col_all.append(cols) + + if len(pts_all) == 0: + return np.zeros((0, 3), dtype=np.float32), np.zeros((0, 3), dtype=np.uint8) + + return np.concatenate(pts_all, 0), np.concatenate(col_all, 0) + + +def _filter_and_downsample(points: np.ndarray, colors: np.ndarray, num_max: int): + if points.shape[0] == 0: + return points, colors + finite = np.isfinite(points).all(axis=1) + points, colors = points[finite], colors[finite] + if points.shape[0] > num_max: + idx = np.random.choice(points.shape[0], num_max, replace=False) + points, colors = points[idx], colors[idx] + return points, colors + + +def _estimate_scene_scale(points: np.ndarray, fallback: float = 1.0) -> float: + if points.shape[0] < 2: + return fallback + lo = np.percentile(points, 5, axis=0) + hi = np.percentile(points, 95, axis=0) + diag = np.linalg.norm(hi - lo) + return float(diag if np.isfinite(diag) and diag > 0 else fallback) + + +def _compute_alignment_transform_first_cam_glTF_center_by_points( + ext_w2c0: np.ndarray, + points_world: np.ndarray, +) -> np.ndarray: + """Computes the transformation matrix to align the scene with glTF standards. + + This function calculates a 4x4 homogeneous matrix that centers the scene's + point cloud and transforms its coordinate system from the computer vision (CV) + standard to the glTF standard. + + The transformation process involves three main steps: + 1. **Initial Alignment**: Orients the world coordinate system to match the + first camera's view (x-right, y-down, z-forward). + 2. **Coordinate System Conversion**: Converts the CV camera frame to the + glTF frame (x-right, y-up, z-backward) by flipping the Y and Z axes. + 3. **Centering**: Translates the entire scene so that the median of the + point cloud becomes the new origin (0,0,0). + + Returns: + A 4x4 homogeneous transformation matrix (torch.Tensor or np.ndarray) + that applies these transformations. A: X' = A @ [X;1] + """ + + w2c0 = _as_homogeneous44(ext_w2c0).astype(np.float64) + + # CV -> glTF axis transformation + M = np.eye(4, dtype=np.float64) + M[1, 1] = -1.0 # flip Y + M[2, 2] = -1.0 # flip Z + + # Don't center first + A_no_center = M @ w2c0 + + # Calculate point cloud center in new coordinate system (use median to resist outliers) + if points_world.shape[0] > 0: + pts_tmp = trimesh.transform_points(points_world, A_no_center) + center = np.median(pts_tmp, axis=0) + else: + center = np.zeros(3, dtype=np.float64) + + T_center = np.eye(4, dtype=np.float64) + T_center[:3, 3] = -center + + A = T_center @ A_no_center + return A + + +def _add_cameras_to_scene( + scene: trimesh.Scene, + K: np.ndarray, + ext_w2c: np.ndarray, + image_sizes: list[tuple[int, int]], + scale: float, +) -> None: + """Draws camera frustums to visualize their position and orientation. + + This function renders each camera as a wireframe pyramid, originating from + the camera's center and extending to the corners of its imaging plane. + + It reads the 'hf_alignment' metadata from the scene to ensure the + wireframes are correctly aligned with the 3D point cloud. + """ + N = K.shape[0] + if N == 0: + return + + # Alignment matrix consistent with point cloud (use identity matrix if missing) + A = None + try: + A = scene.metadata.get("hf_alignment", None) if scene.metadata else None + except Exception: + A = None + if A is None: + A = np.eye(4, dtype=np.float64) + + for i in range(N): + H, W = image_sizes[i] + segs = _camera_frustum_lines(K[i], ext_w2c[i], W, H, scale) # (8,2,3) world frame + # Apply unified transformation + segs = trimesh.transform_points(segs.reshape(-1, 3), A).reshape(-1, 2, 3) + path = trimesh.load_path(segs) + color = _index_color_rgb(i, N) + if hasattr(path, "colors"): + path.colors = np.tile(color, (len(path.entities), 1)) + scene.add_geometry(path) + + +def _camera_frustum_lines( + K: np.ndarray, ext_w2c: np.ndarray, W: int, H: int, scale: float +) -> np.ndarray: + corners = np.array( + [ + [0, 0, 1.0], + [W - 1, 0, 1.0], + [W - 1, H - 1, 1.0], + [0, H - 1, 1.0], + ], + dtype=float, + ) # (4,3) + + K_inv = np.linalg.inv(K) + c2w = np.linalg.inv(_as_homogeneous44(ext_w2c)) + + # camera center in world + Cw = (c2w @ np.array([0, 0, 0, 1.0]))[:3] + + # rays -> z=1 plane points (camera frame) + rays = (K_inv @ corners.T).T + z = rays[:, 2:3] + z[z == 0] = 1.0 + plane_cam = (rays / z) * scale # (4,3) + + # to world + plane_w = [] + for p in plane_cam: + pw = (c2w @ np.array([p[0], p[1], p[2], 1.0]))[:3] + plane_w.append(pw) + plane_w = np.stack(plane_w, 0) # (4,3) + + segs = [] + # center to corners + for k in range(4): + segs.append(np.stack([Cw, plane_w[k]], 0)) + # rectangle edges + order = [0, 1, 2, 3, 0] + for a, b in zip(order[:-1], order[1:]): + segs.append(np.stack([plane_w[a], plane_w[b]], 0)) + + return np.stack(segs, 0) # (8,2,3) + + +def _index_color_rgb(i: int, n: int) -> np.ndarray: + h = (i + 0.5) / max(n, 1) + s, v = 0.85, 0.95 + r, g, b = _hsv_to_rgb(h, s, v) + return (np.array([r, g, b]) * 255).astype(np.uint8) + + +def _hsv_to_rgb(h: float, s: float, v: float) -> tuple[float, float, float]: + i = int(h * 6.0) + f = h * 6.0 - i + p = v * (1.0 - s) + q = v * (1.0 - f * s) + t = v * (1.0 - (1.0 - f) * s) + i = i % 6 + if i == 0: + r, g, b = v, t, p + elif i == 1: + r, g, b = q, v, p + elif i == 2: + r, g, b = p, v, t + elif i == 3: + r, g, b = p, q, v + elif i == 4: + r, g, b = t, p, v + else: + r, g, b = v, p, q + return r, g, b diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/export/gs.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/export/gs.py new file mode 100644 index 0000000000000000000000000000000000000000..90077cf25651c7977c1c1da320b7c0931fdb18ba --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/export/gs.py @@ -0,0 +1,154 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +from typing import Literal, Optional +import moviepy.editor as mpy +import torch + +from depth_anything_3.model.utils.gs_renderer import run_renderer_in_chunk_w_trj_mode +from depth_anything_3.specs import Prediction +from depth_anything_3.utils.gsply_helpers import save_gaussian_ply +from depth_anything_3.utils.layout_helpers import hcat, vcat +from depth_anything_3.utils.visualize import vis_depth_map_tensor + +VIDEO_QUALITY_MAP = { + "low": {"crf": "28", "preset": "veryfast"}, + "medium": {"crf": "23", "preset": "medium"}, + "high": {"crf": "18", "preset": "slow"}, +} + + +def export_to_gs_ply( + prediction: Prediction, + export_dir: str, + gs_views_interval: Optional[ + int + ] = 1, # export GS every N views, useful for extremely dense inputs +): + gs_world = prediction.gaussians + pred_depth = torch.from_numpy(prediction.depth).unsqueeze(-1).to(gs_world.means) # v h w 1 + idx = 0 + os.makedirs(os.path.join(export_dir, "gs_ply"), exist_ok=True) + save_path = os.path.join(export_dir, f"gs_ply/{idx:04d}.ply") + if gs_views_interval is None: # select around 12 views in total + gs_views_interval = max(pred_depth.shape[0] // 12, 1) + save_gaussian_ply( + gaussians=gs_world, + save_path=save_path, + ctx_depth=pred_depth, + shift_and_scale=False, + save_sh_dc_only=True, + gs_views_interval=gs_views_interval, + inv_opacity=True, + prune_by_depth_percent=0.9, + prune_border_gs=True, + match_3dgs_mcmc_dev=False, + ) + + +def export_to_gs_video( + prediction: Prediction, + export_dir: str, + extrinsics: Optional[torch.Tensor] = None, # render views' world2cam, "b v 4 4" + intrinsics: Optional[torch.Tensor] = None, # render views' unnormed intrinsics, "b v 3 3" + out_image_hw: Optional[tuple[int, int]] = None, # render views' resolution, (h, w) + chunk_size: Optional[int] = 4, + trj_mode: Literal[ + "original", + "smooth", + "interpolate", + "interpolate_smooth", + "wander", + "dolly_zoom", + "extend", + "wobble_inter", + ] = "extend", + color_mode: Literal["RGB+D", "RGB+ED"] = "RGB+ED", + vis_depth: Optional[Literal["hcat", "vcat"]] = "hcat", + enable_tqdm: Optional[bool] = True, + output_name: Optional[str] = None, + video_quality: Literal["low", "medium", "high"] = "high", +) -> None: + gs_world = prediction.gaussians + # if target poses are not provided, render the (smooth/interpolate) input poses + if extrinsics is not None: + tgt_extrs = extrinsics + else: + tgt_extrs = torch.from_numpy(prediction.extrinsics).unsqueeze(0).to(gs_world.means) + if prediction.is_metric: + scale_factor = prediction.scale_factor + if scale_factor is not None: + tgt_extrs[:, :, :3, 3] /= scale_factor + tgt_intrs = ( + intrinsics + if intrinsics is not None + else torch.from_numpy(prediction.intrinsics).unsqueeze(0).to(gs_world.means) + ) + # if render resolution is not provided, render the input ones + if out_image_hw is not None: + H, W = out_image_hw + else: + H, W = prediction.depth.shape[-2:] + # if single views, render wander trj + if tgt_extrs.shape[1] <= 1: + trj_mode = "wander" + # trj_mode = "dolly_zoom" + + color, depth = run_renderer_in_chunk_w_trj_mode( + gaussians=gs_world, + extrinsics=tgt_extrs, + intrinsics=tgt_intrs, + image_shape=(H, W), + chunk_size=chunk_size, + trj_mode=trj_mode, + use_sh=True, + color_mode=color_mode, + enable_tqdm=enable_tqdm, + ) + + # save as video + ffmpeg_params = [ + "-crf", + VIDEO_QUALITY_MAP[video_quality]["crf"], + "-preset", + VIDEO_QUALITY_MAP[video_quality]["preset"], + "-pix_fmt", + "yuv420p", + ] # best compatibility + + os.makedirs(os.path.join(export_dir, "gs_video"), exist_ok=True) + for idx in range(color.shape[0]): + video_i = color[idx] + if vis_depth is not None: + depth_i = vis_depth_map_tensor(depth[0]) + cat_fn = hcat if vis_depth == "hcat" else vcat + video_i = torch.stack([cat_fn(c, d) for c, d in zip(video_i, depth_i)]) + frames = list( + (video_i.clamp(0, 1) * 255).byte().permute(0, 2, 3, 1).cpu().numpy() + ) # T x H x W x C, uint8, numpy() + + fps = 24 + clip = mpy.ImageSequenceClip(frames, fps=fps) + output_name = f"{idx:04d}_{trj_mode}" if output_name is None else output_name + save_path = os.path.join(export_dir, f"gs_video/{output_name}.mp4") + # clip.write_videofile(save_path, codec="libx264", audio=False, bitrate="4000k") + clip.write_videofile( + save_path, + codec="libx264", + audio=False, + fps=fps, + ffmpeg_params=ffmpeg_params, + ) + return diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/export/npz.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/export/npz.py new file mode 100644 index 0000000000000000000000000000000000000000..75df4f5194066c76a177f679e54721cb39739dd7 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/export/npz.py @@ -0,0 +1,73 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +import numpy as np + +from depth_anything_3.specs import Prediction +from depth_anything_3.utils.parallel_utils import async_call + + +@async_call +def export_to_npz( + prediction: Prediction, + export_dir: str, +): + output_file = os.path.join(export_dir, "exports", "npz", "results.npz") + os.makedirs(os.path.dirname(output_file), exist_ok=True) + + # Use prediction.processed_images, which is already processed image data + if prediction.processed_images is None: + raise ValueError("prediction.processed_images is required but not available") + + image = prediction.processed_images # (N,H,W,3) uint8 + + # Build save dict with only non-None values + save_dict = { + "image": image, + "depth": np.round(prediction.depth, 6), + } + + if prediction.conf is not None: + save_dict["conf"] = np.round(prediction.conf, 2) + if prediction.extrinsics is not None: + save_dict["extrinsics"] = prediction.extrinsics + if prediction.intrinsics is not None: + save_dict["intrinsics"] = prediction.intrinsics + + # aux = {k: np.round(v, 4) for k, v in prediction.aux.items()} + np.savez_compressed(output_file, **save_dict) + + +@async_call +def export_to_mini_npz( + prediction: Prediction, + export_dir: str, +): + output_file = os.path.join(export_dir, "exports", "mini_npz", "results.npz") + os.makedirs(os.path.dirname(output_file), exist_ok=True) + + # Build save dict with only non-None values + save_dict = { + "depth": np.round(prediction.depth, 8), + } + + if prediction.conf is not None: + save_dict["conf"] = np.round(prediction.conf, 2) + if prediction.extrinsics is not None: + save_dict["extrinsics"] = prediction.extrinsics + if prediction.intrinsics is not None: + save_dict["intrinsics"] = prediction.intrinsics + + np.savez_compressed(output_file, **save_dict) diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/export/utils.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/export/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..81f45fb563ce595bf547bebe829c9b83eb175f1c --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/export/utils.py @@ -0,0 +1,30 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import numpy as np +import torch + + +def _denorm_and_to_uint8(image_tensor: torch.Tensor) -> np.ndarray: + """Denormalize to [0,255] and output (N, H, W, 3) uint8.""" + resnet_mean = torch.tensor( + [0.485, 0.456, 0.406], dtype=image_tensor.dtype, device=image_tensor.device + ) + resnet_std = torch.tensor( + [0.229, 0.224, 0.225], dtype=image_tensor.dtype, device=image_tensor.device + ) + img = image_tensor * resnet_std[None, :, None, None] + resnet_mean[None, :, None, None] + img = torch.clamp(img, 0.0, 1.0) + img = (img.permute(0, 2, 3, 1).cpu().numpy() * 255.0).round().astype(np.uint8) # (N,H,W,3) + return img diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/geometry.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/geometry.py new file mode 100644 index 0000000000000000000000000000000000000000..41a42190d637ef25db3599cc90f9a4f40be3b8d7 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/geometry.py @@ -0,0 +1,498 @@ +# flake8: noqa: F722 +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from types import SimpleNamespace +from typing import Optional +import numpy as np +import torch +import torch.nn.functional as F +from einops import einsum + + +def as_homogeneous(ext): + """ + Accept (..., 3,4) or (..., 4,4) extrinsics, return (...,4,4) homogeneous matrix. + Supports torch.Tensor or np.ndarray. + """ + if isinstance(ext, torch.Tensor): + # If already in homogeneous form + if ext.shape[-2:] == (4, 4): + return ext + elif ext.shape[-2:] == (3, 4): + # Create a new homogeneous matrix + ones = torch.zeros_like(ext[..., :1, :4]) + ones[..., 0, 3] = 1.0 + return torch.cat([ext, ones], dim=-2) + else: + raise ValueError(f"Invalid shape for torch.Tensor: {ext.shape}") + + elif isinstance(ext, np.ndarray): + if ext.shape[-2:] == (4, 4): + return ext + elif ext.shape[-2:] == (3, 4): + ones = np.zeros_like(ext[..., :1, :4]) + ones[..., 0, 3] = 1.0 + return np.concatenate([ext, ones], axis=-2) + else: + raise ValueError(f"Invalid shape for np.ndarray: {ext.shape}") + + else: + raise TypeError("Input must be a torch.Tensor or np.ndarray.") + + +@torch.jit.script +def affine_inverse(A: torch.Tensor): + R = A[..., :3, :3] # ..., 3, 3 + T = A[..., :3, 3:] # ..., 3, 1 + P = A[..., 3:, :] # ..., 1, 4 + return torch.cat([torch.cat([R.mT, -R.mT @ T], dim=-1), P], dim=-2) + + +def transpose_last_two_axes(arr): + """ + for np < 2 + """ + if arr.ndim < 2: + return arr + axes = list(range(arr.ndim)) + # swap the last two + axes[-2], axes[-1] = axes[-1], axes[-2] + return arr.transpose(axes) + + +def affine_inverse_np(A: np.ndarray): + R = A[..., :3, :3] + T = A[..., :3, 3:] + P = A[..., 3:, :] + return np.concatenate( + [ + np.concatenate([transpose_last_two_axes(R), -transpose_last_two_axes(R) @ T], axis=-1), + P, + ], + axis=-2, + ) + + +def quat_to_mat(quaternions: torch.Tensor) -> torch.Tensor: + """ + Quaternion Order: XYZW or say ijkr, scalar-last + + Convert rotations given as quaternions to rotation matrices. + Args: + quaternions: quaternions with real part last, + as tensor of shape (..., 4). + + Returns: + Rotation matrices as tensor of shape (..., 3, 3). + """ + i, j, k, r = torch.unbind(quaternions, -1) + # pyre-fixme[58]: `/` is not supported for operand types `float` and `Tensor`. + two_s = 2.0 / (quaternions * quaternions).sum(-1) + + o = torch.stack( + ( + 1 - two_s * (j * j + k * k), + two_s * (i * j - k * r), + two_s * (i * k + j * r), + two_s * (i * j + k * r), + 1 - two_s * (i * i + k * k), + two_s * (j * k - i * r), + two_s * (i * k - j * r), + two_s * (j * k + i * r), + 1 - two_s * (i * i + j * j), + ), + -1, + ) + return o.reshape(quaternions.shape[:-1] + (3, 3)) + + +def mat_to_quat(matrix: torch.Tensor) -> torch.Tensor: + """ + Convert rotations given as rotation matrices to quaternions. + + Args: + matrix: Rotation matrices as tensor of shape (..., 3, 3). + + Returns: + quaternions with real part last, as tensor of shape (..., 4). + Quaternion Order: XYZW or say ijkr, scalar-last + """ + if matrix.size(-1) != 3 or matrix.size(-2) != 3: + raise ValueError(f"Invalid rotation matrix shape {matrix.shape}.") + + batch_dim = matrix.shape[:-2] + m00, m01, m02, m10, m11, m12, m20, m21, m22 = torch.unbind( + matrix.reshape(batch_dim + (9,)), dim=-1 + ) + + q_abs = _sqrt_positive_part( + torch.stack( + [ + 1.0 + m00 + m11 + m22, + 1.0 + m00 - m11 - m22, + 1.0 - m00 + m11 - m22, + 1.0 - m00 - m11 + m22, + ], + dim=-1, + ) + ) + + # we produce the desired quaternion multiplied by each of r, i, j, k + quat_by_rijk = torch.stack( + [ + # pyre-fixme[58]: `**` is not supported for operand types `Tensor` and + # `int`. + torch.stack([q_abs[..., 0] ** 2, m21 - m12, m02 - m20, m10 - m01], dim=-1), + # pyre-fixme[58]: `**` is not supported for operand types `Tensor` and + # `int`. + torch.stack([m21 - m12, q_abs[..., 1] ** 2, m10 + m01, m02 + m20], dim=-1), + # pyre-fixme[58]: `**` is not supported for operand types `Tensor` and + # `int`. + torch.stack([m02 - m20, m10 + m01, q_abs[..., 2] ** 2, m12 + m21], dim=-1), + # pyre-fixme[58]: `**` is not supported for operand types `Tensor` and + # `int`. + torch.stack([m10 - m01, m20 + m02, m21 + m12, q_abs[..., 3] ** 2], dim=-1), + ], + dim=-2, + ) + + # We floor here at 0.1 but the exact level is not important; if q_abs is small, + # the candidate won't be picked. + flr = torch.tensor(0.1).to(dtype=q_abs.dtype, device=q_abs.device) + quat_candidates = quat_by_rijk / (2.0 * q_abs[..., None].max(flr)) + + # if not for numerical problems, quat_candidates[i] should be same (up to a sign), + # forall i; we pick the best-conditioned one (with the largest denominator) + out = quat_candidates[F.one_hot(q_abs.argmax(dim=-1), num_classes=4) > 0.5, :].reshape( + batch_dim + (4,) + ) + + # Convert from rijk to ijkr + out = out[..., [1, 2, 3, 0]] + + out = standardize_quaternion(out) + + return out + + +def _sqrt_positive_part(x: torch.Tensor) -> torch.Tensor: + """ + Returns torch.sqrt(torch.max(0, x)) + but with a zero subgradient where x is 0. + """ + ret = torch.zeros_like(x) + positive_mask = x > 0 + if torch.is_grad_enabled(): + ret[positive_mask] = torch.sqrt(x[positive_mask]) + else: + ret = torch.where(positive_mask, torch.sqrt(x), ret) + return ret + + +def standardize_quaternion(quaternions: torch.Tensor) -> torch.Tensor: + """ + Convert a unit quaternion to a standard form: one in which the real + part is non negative. + + Args: + quaternions: Quaternions with real part last, + as tensor of shape (..., 4). + + Returns: + Standardized quaternions as tensor of shape (..., 4). + """ + return torch.where(quaternions[..., 3:4] < 0, -quaternions, quaternions) + + +def sample_image_grid( + shape: tuple[int, ...], + device: torch.device = torch.device("cpu"), +) -> tuple[ + torch.Tensor, # float coordinates (xy indexing), "*shape dim" + torch.Tensor, # integer indices (ij indexing), "*shape dim" +]: + """Get normalized (range 0 to 1) coordinates and integer indices for an image.""" + + # Each entry is a pixel-wise integer coordinate. In the 2D case, each entry is a + # (row, col) coordinate. + indices = [torch.arange(length, device=device) for length in shape] + stacked_indices = torch.stack(torch.meshgrid(*indices, indexing="ij"), dim=-1) + + # Each entry is a floating-point coordinate in the range (0, 1). In the 2D case, + # each entry is an (x, y) coordinate. + coordinates = [(idx + 0.5) / length for idx, length in zip(indices, shape)] + coordinates = reversed(coordinates) + coordinates = torch.stack(torch.meshgrid(*coordinates, indexing="xy"), dim=-1) + + return coordinates, stacked_indices + + +def homogenize_points(points: torch.Tensor) -> torch.Tensor: # "*batch dim" # "*batch dim+1" + """Convert batched points (xyz) to (xyz1).""" + return torch.cat([points, torch.ones_like(points[..., :1])], dim=-1) + + +def homogenize_vectors(vectors: torch.Tensor) -> torch.Tensor: # "*batch dim" # "*batch dim+1" + """Convert batched vectors (xyz) to (xyz0).""" + return torch.cat([vectors, torch.zeros_like(vectors[..., :1])], dim=-1) + + +def transform_rigid( + homogeneous_coordinates: torch.Tensor, # "*#batch dim" + transformation: torch.Tensor, # "*#batch dim dim" +) -> torch.Tensor: # "*batch dim" + """Apply a rigid-body transformation to points or vectors.""" + return einsum( + transformation, + homogeneous_coordinates.to(transformation.dtype), + "... i j, ... j -> ... i", + ) + + +def transform_cam2world( + homogeneous_coordinates: torch.Tensor, # "*#batch dim" + extrinsics: torch.Tensor, # "*#batch dim dim" +) -> torch.Tensor: # "*batch dim" + """Transform points from 3D camera coordinates to 3D world coordinates.""" + return transform_rigid(homogeneous_coordinates, extrinsics) + + +def unproject( + coordinates: torch.Tensor, # "*#batch dim" + z: torch.Tensor, # "*#batch" + intrinsics: torch.Tensor, # "*#batch dim+1 dim+1" +) -> torch.Tensor: # "*batch dim+1" + """Unproject 2D camera coordinates with the given Z values.""" + + # Apply the inverse intrinsics to the coordinates. + coordinates = homogenize_points(coordinates) + ray_directions = einsum( + intrinsics.float().inverse().to(intrinsics), + coordinates.to(intrinsics.dtype), + "... i j, ... j -> ... i", + ) + + # Apply the supplied depth values. + return ray_directions * z[..., None] + + +def get_world_rays( + coordinates: torch.Tensor, # "*#batch dim" + extrinsics: torch.Tensor, # "*#batch dim+2 dim+2" + intrinsics: torch.Tensor, # "*#batch dim+1 dim+1" +) -> tuple[ + torch.Tensor, # origins, "*batch dim+1" + torch.Tensor, # directions, "*batch dim+1" +]: + # Get camera-space ray directions. + directions = unproject( + coordinates, + torch.ones_like(coordinates[..., 0]), + intrinsics, + ) + directions = directions / directions.norm(dim=-1, keepdim=True) + + # Transform ray directions to world coordinates. + directions = homogenize_vectors(directions) + directions = transform_cam2world(directions, extrinsics)[..., :-1] + + # Tile the ray origins to have the same shape as the ray directions. + origins = extrinsics[..., :-1, -1].broadcast_to(directions.shape) + + return origins, directions + + +def get_fov(intrinsics: torch.Tensor) -> torch.Tensor: # "batch 3 3" -> "batch 2" + intrinsics_inv = intrinsics.float().inverse().to(intrinsics) + + def process_vector(vector): + vector = torch.tensor(vector, dtype=intrinsics.dtype, device=intrinsics.device) + vector = einsum(intrinsics_inv, vector, "b i j, j -> b i") + return vector / vector.norm(dim=-1, keepdim=True) + + left = process_vector([0, 0.5, 1]) + right = process_vector([1, 0.5, 1]) + top = process_vector([0.5, 0, 1]) + bottom = process_vector([0.5, 1, 1]) + fov_x = (left * right).sum(dim=-1).acos() + fov_y = (top * bottom).sum(dim=-1).acos() + return torch.stack((fov_x, fov_y), dim=-1) + + +def map_pdf_to_opacity( + pdf: torch.Tensor, # " *batch" + global_step: int = 0, + opacity_mapping: Optional[dict] = None, +) -> torch.Tensor: # " *batch" + # https://www.desmos.com/calculator/opvwti3ba9 + + # Figure out the exponent. + if opacity_mapping is not None: + cfg = SimpleNamespace(**opacity_mapping) + x = cfg.initial + min(global_step / cfg.warm_up, 1) * (cfg.final - cfg.initial) + else: + x = 0.0 + exponent = 2**x + + # Map the probability density to an opacity. + return 0.5 * (1 - (1 - pdf) ** exponent + pdf ** (1 / exponent)) + +def normalize_homogenous_points(points): + """Normalize the point vectors""" + return points / points[..., -1:] + +def inverse_intrinsic_matrix(ixts): + """ """ + return torch.inverse(ixts) + +def pixel_space_to_camera_space(pixel_space_points, depth, intrinsics): + """ + Convert pixel space points to camera space points. + + Args: + pixel_space_points (torch.Tensor): Pixel space points with shape (h, w, 2) + depth (torch.Tensor): Depth map with shape (b, v, h, w, 1) + intrinsics (torch.Tensor): Camera intrinsics with shape (b, v, 3, 3) + + Returns: + torch.Tensor: Camera space points with shape (b, v, h, w, 3). + """ + pixel_space_points = homogenize_points(pixel_space_points) + # camera_space_points = torch.einsum( + # "b v i j , h w j -> b v h w i", intrinsics.inverse(), pixel_space_points + # ) + camera_space_points = torch.einsum( + "b v i j , h w j -> b v h w i", inverse_intrinsic_matrix(intrinsics), pixel_space_points + ) + camera_space_points = camera_space_points * depth + return camera_space_points + + +def camera_space_to_world_space(camera_space_points, c2w): + """ + Convert camera space points to world space points. + + Args: + camera_space_points (torch.Tensor): Camera space points with shape (b, v, h, w, 3) + c2w (torch.Tensor): Camera to world extrinsics matrix with shape (b, v, 4, 4) + + Returns: + torch.Tensor: World space points with shape (b, v, h, w, 3). + """ + camera_space_points = homogenize_points(camera_space_points) + world_space_points = torch.einsum("b v i j , b v h w j -> b v h w i", c2w, camera_space_points) + return world_space_points[..., :3] + + +def camera_space_to_pixel_space(camera_space_points, intrinsics): + """ + Convert camera space points to pixel space points. + + Args: + camera_space_points (torch.Tensor): Camera space points with shape (b, v1, v2, h, w, 3) + c2w (torch.Tensor): Camera to world extrinsics matrix with shape (b, v2, 3, 3) + + Returns: + torch.Tensor: World space points with shape (b, v1, v2, h, w, 2). + """ + camera_space_points = normalize_homogenous_points(camera_space_points) + pixel_space_points = torch.einsum( + "b u i j , b v u h w j -> b v u h w i", intrinsics, camera_space_points + ) + return pixel_space_points[..., :2] + + +def world_space_to_camera_space(world_space_points, c2w): + """ + Convert world space points to pixel space points. + + Args: + world_space_points (torch.Tensor): World space points with shape (b, v1, h, w, 3) + c2w (torch.Tensor): Camera to world extrinsics matrix with shape (b, v2, 4, 4) + + Returns: + torch.Tensor: Camera space points with shape (b, v1, v2, h, w, 3). + """ + world_space_points = homogenize_points(world_space_points) + camera_space_points = torch.einsum( + "b u i j , b v h w j -> b v u h w i", c2w.inverse(), world_space_points + ) + return camera_space_points[..., :3] + + +def unproject_depth( + depth, intrinsics, c2w=None, ixt_normalized=False, num_patches_x=None, num_patches_y=None +): + """ + Turn the depth map into a 3D point cloud in world space + + Args: + depth: (b, v, h, w, 1) + intrinsics: (b, v, 3, 3) + c2w: (b, v, 4, 4) + + Returns: + torch.Tensor: World space points with shape (b, v, h, w, 3). + """ + if c2w is None: + c2w = torch.eye(4, device=depth.device, dtype=depth.dtype) + c2w = c2w[None, None].repeat(depth.shape[0], depth.shape[1], 1, 1) + + if not ixt_normalized: + # Compute indices of pixels + h, w = depth.shape[-3], depth.shape[-2] + x_grid, y_grid = torch.meshgrid( + torch.arange(w, device=depth.device, dtype=depth.dtype), + torch.arange(h, device=depth.device, dtype=depth.dtype), + indexing="xy", + ) # (h, w), (h, w) + else: + # ixt_normalized: h=w=2.0. cx, cy, fx, fy are normalized according to h=w=2.0 + assert num_patches_x is not None and num_patches_y is not None + dx = 1 / num_patches_x + dy = 1 / num_patches_y + max_y = 1 - dy + min_y = -max_y + max_x = 1 - dx + min_x = -max_x + + grid_shift = 1.0 + y_grid, x_grid = torch.meshgrid( + torch.linspace( + min_y + grid_shift, + max_y + grid_shift, + num_patches_y, + dtype=torch.float32, + device=depth.device, + ), + torch.linspace( + min_x + grid_shift, + max_x + grid_shift, + num_patches_x, + dtype=torch.float32, + device=depth.device, + ), + indexing="ij", + ) + + # Compute coordinates of pixels in camera space + pixel_space_points = torch.stack((x_grid, y_grid), dim=-1) # (..., h, w, 2) + camera_points = pixel_space_to_camera_space( + pixel_space_points, depth, intrinsics + ) # (..., h, w, 3) + + # Convert points to world space + world_points = camera_space_to_world_space(camera_points, c2w) # (..., h, w, 3) + + return world_points \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/gsply_helpers.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/gsply_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..5733009e4e91ad80ab59179c80e2df8a0430ab5f --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/gsply_helpers.py @@ -0,0 +1,173 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from pathlib import Path +from typing import Optional +import numpy as np +import torch +from einops import rearrange, repeat +from plyfile import PlyData, PlyElement +from torch import Tensor + +from depth_anything_3.specs import Gaussians + + +def construct_list_of_attributes(num_rest: int) -> list[str]: + attributes = ["x", "y", "z", "nx", "ny", "nz"] + for i in range(3): + attributes.append(f"f_dc_{i}") + for i in range(num_rest): + attributes.append(f"f_rest_{i}") + attributes.append("opacity") + for i in range(3): + attributes.append(f"scale_{i}") + for i in range(4): + attributes.append(f"rot_{i}") + return attributes + + +def export_ply( + means: Tensor, # "gaussian 3" + scales: Tensor, # "gaussian 3" + rotations: Tensor, # "gaussian 4" + harmonics: Tensor, # "gaussian 3 d_sh" + opacities: Tensor, # "gaussian" + path: Path, + shift_and_scale: bool = False, + save_sh_dc_only: bool = True, + match_3dgs_mcmc_dev: Optional[bool] = False, +): + if shift_and_scale: + # Shift the scene so that the median Gaussian is at the origin. + means = means - means.median(dim=0).values + + # Rescale the scene so that most Gaussians are within range [-1, 1]. + scale_factor = means.abs().quantile(0.95, dim=0).max() + means = means / scale_factor + scales = scales / scale_factor + + rotations = rotations.detach().cpu().numpy() + + # Since current model use SH_degree = 4, + # which require large memory to store, we can only save the DC band to save memory. + f_dc = harmonics[..., 0] + f_rest = harmonics[..., 1:].flatten(start_dim=1) + + if match_3dgs_mcmc_dev: + sh_degree = 3 + n_rest = 3 * (sh_degree + 1) ** 2 - 3 + f_rest = repeat( + torch.zeros_like(harmonics[..., :1]), "... i -> ... (n i)", n=(n_rest // 3) + ).flatten(start_dim=1) + dtype_full = [ + (attribute, "f4") + for attribute in construct_list_of_attributes(num_rest=n_rest) + if attribute not in ("nx", "ny", "nz") + ] + else: + dtype_full = [ + (attribute, "f4") + for attribute in construct_list_of_attributes( + 0 if save_sh_dc_only else f_rest.shape[1] + ) + ] + elements = np.empty(means.shape[0], dtype=dtype_full) + attributes = [ + means.detach().cpu().numpy(), + torch.zeros_like(means).detach().cpu().numpy(), + f_dc.detach().cpu().contiguous().numpy(), + f_rest.detach().cpu().contiguous().numpy(), + opacities[..., None].detach().cpu().numpy(), + scales.log().detach().cpu().numpy(), + rotations, + ] + if match_3dgs_mcmc_dev: + attributes.pop(1) # dummy normal is not needed + elif save_sh_dc_only: + attributes.pop(3) # remove f_rest from attributes + + attributes = np.concatenate(attributes, axis=1) + elements[:] = list(map(tuple, attributes)) + path.parent.mkdir(exist_ok=True, parents=True) + PlyData([PlyElement.describe(elements, "vertex")]).write(path) + + +def inverse_sigmoid(x): + return torch.log(x / (1 - x)) + + +def save_gaussian_ply( + gaussians: Gaussians, + save_path: str, + ctx_depth: torch.Tensor, # depth of input views; for getting shape and filtering, "v h w 1" + shift_and_scale: bool = False, + save_sh_dc_only: bool = True, + gs_views_interval: int = 1, + inv_opacity: Optional[bool] = True, + prune_by_depth_percent: Optional[float] = 1.0, + prune_border_gs: Optional[bool] = True, + match_3dgs_mcmc_dev: Optional[bool] = False, +): + b = gaussians.means.shape[0] + assert b == 1, "must set batch_size=1 when exporting 3D gaussians" + src_v, out_h, out_w, _ = ctx_depth.shape + + # extract gs params + world_means = gaussians.means + world_shs = gaussians.harmonics + world_rotations = gaussians.rotations + gs_scales = gaussians.scales + gs_opacities = inverse_sigmoid(gaussians.opacities) if inv_opacity else gaussians.opacities + + # Create a mask to filter the Gaussians. + + # TODO: prune the sky region here + + # throw away Gaussians at the borders, since they're generally of lower quality. + if prune_border_gs: + mask = torch.zeros_like(ctx_depth, dtype=torch.bool) + gstrim_h = int(8 / 256 * out_h) + gstrim_w = int(8 / 256 * out_w) + mask[:, gstrim_h:-gstrim_h, gstrim_w:-gstrim_w, :] = 1 + else: + mask = torch.ones_like(ctx_depth, dtype=torch.bool) + + # trim the far away point based on depth; + if prune_by_depth_percent is not None and prune_by_depth_percent < 1: + in_depths = ctx_depth + d_percentile = torch.quantile( + in_depths.view(in_depths.shape[0], -1), q=prune_by_depth_percent, dim=1 + ).view(-1, 1, 1) + d_mask = (in_depths[..., 0] <= d_percentile).unsqueeze(-1) + mask = mask & d_mask + mask = mask.squeeze(-1) # v h w + + # helper fn, must place after mask + def trim_select_reshape(element): + selected_element = rearrange( + element[0], "(v h w) ... -> v h w ...", v=src_v, h=out_h, w=out_w + ) + selected_element = selected_element[::gs_views_interval][mask[::gs_views_interval]] + return selected_element + + export_ply( + means=trim_select_reshape(world_means), + scales=trim_select_reshape(gs_scales), + rotations=trim_select_reshape(world_rotations), + harmonics=trim_select_reshape(world_shs), + opacities=trim_select_reshape(gs_opacities), + path=Path(save_path), + shift_and_scale=shift_and_scale, + save_sh_dc_only=save_sh_dc_only, + match_3dgs_mcmc_dev=match_3dgs_mcmc_dev, + ) diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/io/input_processor.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/io/input_processor.py new file mode 100644 index 0000000000000000000000000000000000000000..fa60194123c22c84a0cdeb577cbf10e2704278bb --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/io/input_processor.py @@ -0,0 +1,501 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Input processor for Depth Anything 3 (parallelized). + +This version removes the square center-crop step for "*crop" methods (same as your note). +In addition, it parallelizes per-image preprocessing using the provided `parallel_execution`. +""" + +from __future__ import annotations + +from typing import Sequence +import cv2 +import numpy as np +import torch +import torchvision.transforms as T +from PIL import Image + +from depth_anything_3.utils.logger import logger +from depth_anything_3.utils.parallel_utils import parallel_execution + + +class InputProcessor: + """Prepares a batch of images for model inference. + This processor converts a list of image file paths into a single, model-ready + tensor. The processing pipeline is executed in parallel across multiple workers + for efficiency. + + Pipeline: + 1) Load image and convert to RGB + 2) Boundary resize (upper/lower bound, preserving aspect ratio) + 3) Enforce divisibility by PATCH_SIZE: + - "*resize" methods: each dimension is rounded to nearest multiple + (may up/downscale a few px) + - "*crop" methods: each dimension is floored to nearest multiple via center crop + 4) Convert to tensor and apply ImageNet normalization + 5) Stack into (1, N, 3, H, W) + + Parallelization: + - Each image is processed independently in a worker. + - Order of outputs matches the input order. + """ + + NORMALIZE = T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) + PATCH_SIZE = 14 + + def __init__(self): + pass + + # ----------------------------- + # Public API + # ----------------------------- + def __call__( + self, + image: list[np.ndarray | Image.Image | str], + extrinsics: np.ndarray | None = None, + intrinsics: np.ndarray | None = None, + process_res: int = 504, + process_res_method: str = "upper_bound_resize", + *, + num_workers: int = 8, + print_progress: bool = False, + sequential: bool | None = None, + desc: str | None = "Preprocess", + ) -> tuple[torch.Tensor, torch.Tensor | None, torch.Tensor | None]: + """ + Returns: + (tensor, extrinsics_list, intrinsics_list) + tensor shape: (1, N, 3, H, W) + """ + sequential = self._resolve_sequential(sequential, num_workers) + exts_list, ixts_list = self._validate_and_pack_meta(image, extrinsics, intrinsics) + + results = self._run_parallel( + image=image, + exts_list=exts_list, + ixts_list=ixts_list, + process_res=process_res, + process_res_method=process_res_method, + num_workers=num_workers, + print_progress=print_progress, + sequential=sequential, + desc=desc, + ) + + proc_imgs, out_sizes, out_ixts, out_exts = self._unpack_results(results) + proc_imgs, out_sizes, out_ixts = self._unify_batch_shapes(proc_imgs, out_sizes, out_ixts) + + batch_tensor = self._stack_batch(proc_imgs) + out_exts = ( + torch.from_numpy(np.asarray(out_exts)).float() + if out_exts is not None and out_exts[0] is not None + else None + ) + out_ixts = ( + torch.from_numpy(np.asarray(out_ixts)).float() + if out_ixts is not None and out_ixts[0] is not None + else None + ) + return (batch_tensor, out_exts, out_ixts) + + # ----------------------------- + # __call__ helpers + # ----------------------------- + def _resolve_sequential(self, sequential: bool | None, num_workers: int) -> bool: + return (num_workers <= 1) if sequential is None else sequential + + def _validate_and_pack_meta( + self, + images: list[np.ndarray | Image.Image | str], + extrinsics: np.ndarray | None, + intrinsics: np.ndarray | None, + ) -> tuple[list[np.ndarray | None] | None, list[np.ndarray | None] | None]: + if extrinsics is not None and len(extrinsics) != len(images): + raise ValueError("Length of extrinsics must match images when provided.") + if intrinsics is not None and len(intrinsics) != len(images): + raise ValueError("Length of intrinsics must match images when provided.") + exts_list = [e for e in extrinsics] if extrinsics is not None else None + ixts_list = [k for k in intrinsics] if intrinsics is not None else None + return exts_list, ixts_list + + def _run_parallel( + self, + *, + image: list[np.ndarray | Image.Image | str], + exts_list: list[np.ndarray | None] | None, + ixts_list: list[np.ndarray | None] | None, + process_res: int, + process_res_method: str, + num_workers: int, + print_progress: bool, + sequential: bool, + desc: str | None, + ): + results = parallel_execution( + image, + exts_list, + ixts_list, + action=self._process_one, # (img, extrinsic, intrinsic, ...) + num_processes=num_workers, + print_progress=print_progress, + sequential=sequential, + desc=desc, + process_res=process_res, + process_res_method=process_res_method, + ) + if not results: + raise RuntimeError( + "No preprocessing results returned. Check inputs and parallel_execution." + ) + return results + + def _unpack_results(self, results): + """ + results: List[Tuple[torch.Tensor, Tuple[H, W], Optional[np.ndarray], Optional[np.ndarray]]] + -> processed_images, out_sizes, out_intrinsics, out_extrinsics + """ + try: + processed_images, out_sizes, out_intrinsics, out_extrinsics = zip(*results) + except Exception as e: + raise RuntimeError( + "Unexpected results structure from parallel_execution: " + f"{type(results)} / sample: {results[0]}" + ) from e + + return list(processed_images), list(out_sizes), list(out_intrinsics), list(out_extrinsics) + + def _unify_batch_shapes( + self, + processed_images: list[torch.Tensor], + out_sizes: list[tuple[int, int]], + out_intrinsics: list[np.ndarray | None], + ) -> tuple[list[torch.Tensor], list[tuple[int, int]], list[np.ndarray | None]]: + """Center-crop all tensors to the smallest H, W; adjust intrinsics' cx, cy accordingly.""" + if len(set(out_sizes)) <= 1: + return processed_images, out_sizes, out_intrinsics + + min_h = min(h for h, _ in out_sizes) + min_w = min(w for _, w in out_sizes) + logger.warn( + f"Images in batch have different sizes {out_sizes}; " + f"center-cropping all to smallest ({min_h},{min_w})" + ) + + center_crop = T.CenterCrop((min_h, min_w)) + new_imgs, new_sizes, new_ixts = [], [], [] + for img_t, (H, W), K in zip(processed_images, out_sizes, out_intrinsics): + crop_top = max(0, (H - min_h) // 2) + crop_left = max(0, (W - min_w) // 2) + new_imgs.append(center_crop(img_t)) + new_sizes.append((min_h, min_w)) + if K is None: + new_ixts.append(None) + else: + K_adj = K.copy() + K_adj[0, 2] -= crop_left + K_adj[1, 2] -= crop_top + new_ixts.append(K_adj) + return new_imgs, new_sizes, new_ixts + + def _stack_batch(self, processed_images: list[torch.Tensor]) -> torch.Tensor: + return torch.stack(processed_images) + + # ----------------------------- + # Per-item worker + # ----------------------------- + def _process_one( + self, + img: np.ndarray | Image.Image | str, + extrinsic: np.ndarray | None = None, + intrinsic: np.ndarray | None = None, + *, + process_res: int, + process_res_method: str, + ) -> tuple[torch.Tensor, tuple[int, int], np.ndarray | None, np.ndarray | None]: + # Load & remember original size + pil_img = self._load_image(img) + orig_w, orig_h = pil_img.size + + # Boundary resize + pil_img = self._resize_image(pil_img, process_res, process_res_method) + w, h = pil_img.size + intrinsic = self._resize_ixt(intrinsic, orig_w, orig_h, w, h) + + # Enforce divisibility by PATCH_SIZE + if process_res_method.endswith("resize"): + pil_img = self._make_divisible_by_resize(pil_img, self.PATCH_SIZE) + new_w, new_h = pil_img.size + intrinsic = self._resize_ixt(intrinsic, w, h, new_w, new_h) + w, h = new_w, new_h + elif process_res_method.endswith("crop"): + pil_img = self._make_divisible_by_crop(pil_img, self.PATCH_SIZE) + new_w, new_h = pil_img.size + intrinsic = self._crop_ixt(intrinsic, w, h, new_w, new_h) + w, h = new_w, new_h + else: + raise ValueError(f"Unsupported process_res_method: {process_res_method}") + + # Convert to tensor & normalize + img_tensor = self._normalize_image(pil_img) + _, H, W = img_tensor.shape + assert (W, H) == (w, h), "Tensor size mismatch with PIL image size after processing." + + # Return: (img_tensor, (H, W), intrinsic, extrinsic) + return img_tensor, (H, W), intrinsic, extrinsic + + # ----------------------------- + # Intrinsics transforms + # ----------------------------- + def _resize_ixt( + self, + intrinsic: np.ndarray | None, + orig_w: int, + orig_h: int, + w: int, + h: int, + ) -> np.ndarray | None: + if intrinsic is None: + return None + K = intrinsic.copy() + # scale fx, cx by w ratio; fy, cy by h ratio + K[:1] *= w / float(orig_w) + K[1:2] *= h / float(orig_h) + return K + + def _crop_ixt( + self, + intrinsic: np.ndarray | None, + orig_w: int, + orig_h: int, + w: int, + h: int, + ) -> np.ndarray | None: + if intrinsic is None: + return None + K = intrinsic.copy() + crop_h = (orig_h - h) // 2 + crop_w = (orig_w - w) // 2 + K[0, 2] -= crop_w + K[1, 2] -= crop_h + return K + + # ----------------------------- + # I/O & normalization + # ----------------------------- + def _load_image(self, img: np.ndarray | Image.Image | str) -> Image.Image: + if isinstance(img, str): + return Image.open(img).convert("RGB") + elif isinstance(img, np.ndarray): + # Assume HxWxC uint8/RGB + return Image.fromarray(img).convert("RGB") + elif isinstance(img, Image.Image): + return img.convert("RGB") + else: + raise ValueError(f"Unsupported image type: {type(img)}") + + def _normalize_image(self, img: Image.Image) -> torch.Tensor: + img_tensor = T.ToTensor()(img) + return self.NORMALIZE(img_tensor) + + # ----------------------------- + # Boundary resizing + # ----------------------------- + def _resize_image(self, img: Image.Image, target_size: int, method: str) -> Image.Image: + if method in ("upper_bound_resize", "upper_bound_crop"): + return self._resize_longest_side(img, target_size) + elif method in ("lower_bound_resize", "lower_bound_crop"): + return self._resize_shortest_side(img, target_size) + else: + raise ValueError(f"Unsupported resize method: {method}") + + def _resize_longest_side(self, img: Image.Image, target_size: int) -> Image.Image: + w, h = img.size + longest = max(w, h) + if longest == target_size: + return img + scale = target_size / float(longest) + new_w = max(1, int(round(w * scale))) + new_h = max(1, int(round(h * scale))) + interpolation = cv2.INTER_CUBIC if scale > 1.0 else cv2.INTER_AREA + arr = cv2.resize(np.asarray(img), (new_w, new_h), interpolation=interpolation) + return Image.fromarray(arr) + + def _resize_shortest_side(self, img: Image.Image, target_size: int) -> Image.Image: + w, h = img.size + shortest = min(w, h) + if shortest == target_size: + return img + scale = target_size / float(shortest) + new_w = max(1, int(round(w * scale))) + new_h = max(1, int(round(h * scale))) + interpolation = cv2.INTER_CUBIC if scale > 1.0 else cv2.INTER_AREA + arr = cv2.resize(np.asarray(img), (new_w, new_h), interpolation=interpolation) + return Image.fromarray(arr) + + # ----------------------------- + # Make divisible by PATCH_SIZE + # ----------------------------- + def _make_divisible_by_crop(self, img: Image.Image, patch: int) -> Image.Image: + """ + Floor each dimension to the nearest multiple of PATCH_SIZE via center crop. + Example: 504x377 -> 504x364 + """ + w, h = img.size + new_w = (w // patch) * patch + new_h = (h // patch) * patch + if new_w == w and new_h == h: + return img + left = (w - new_w) // 2 + top = (h - new_h) // 2 + return img.crop((left, top, left + new_w, top + new_h)) + + def _make_divisible_by_resize(self, img: Image.Image, patch: int) -> Image.Image: + """ + Round each dimension to nearest multiple of PATCH_SIZE via small resize. + """ + w, h = img.size + + def nearest_multiple(x: int, p: int) -> int: + down = (x // p) * p + up = down + p + return up if abs(up - x) <= abs(x - down) else down + + new_w = max(1, nearest_multiple(w, patch)) + new_h = max(1, nearest_multiple(h, patch)) + if new_w == w and new_h == h: + return img + upscale = (new_w > w) or (new_h > h) + interpolation = cv2.INTER_CUBIC if upscale else cv2.INTER_AREA + arr = cv2.resize(np.asarray(img), (new_w, new_h), interpolation=interpolation) + return Image.fromarray(arr) + + +# Backward compatibility alias +InputAdapter = InputProcessor + + +# =========================== +# Minimal test runner (parallel execution) +# =========================== +if __name__ == "__main__": + """ + Minimal test suite: + - Creates pairs of images so batch shapes match. + - Tests all four process_res_methods. + - Prints fx fy cx cy IN->OUT per image. + - Includes cases with K/E provided and with None. + """ + + def fmt_k_line(K: np.ndarray | None) -> str: + if K is None: + return "None" + fx, fy, cx, cy = float(K[0, 0]), float(K[1, 1]), float(K[0, 2]), float(K[1, 2]) + return f"fx={fx:.3f} fy={fy:.3f} cx={cx:.3f} cy={cy:.3f}" + + def show_result( + tag: str, + tensor: torch.Tensor, + Ks_in: Sequence[np.ndarray | None] | None = None, + Ks_out: Sequence[np.ndarray | None] | None = None, + ): + B, N, C, H, W = tensor.shape + print(f"[{tag}] shape={tuple(tensor.shape)} HxW=({H},{W}) div14=({H%14==0},{W%14==0})") + assert H % 14 == 0 and W % 14 == 0, f"{tag}: output size not divisible by 14!" + if Ks_in is not None or Ks_out is not None: + Ks_in = Ks_in or [None] * N + Ks_out = Ks_out or [None] * N + for i in range(N): + print(f" K[{i}]: {fmt_k_line(Ks_in[i])} -> {fmt_k_line(Ks_out[i])}") + + proc = InputProcessor() + process_res = 504 + methods = ["upper_bound_resize", "upper_bound_crop", "lower_bound_resize", "lower_bound_crop"] + + # Example sizes (two orientations) + small_sizes = [(680, 1208), (1208, 680)] + large_sizes = [(1208, 680), (680, 1208)] + + def make_K(w, h, fx=1200.0, fy=1100.0): + cx, cy = w / 2.0, h / 2.0 + K = np.array([[fx, 0, cx], [0, fy, cy], [0, 0, 1]], dtype=np.float32) + return K + + def run_suite(suite_name: str, sizes: list[tuple[int, int]]): + print(f"\n===== {suite_name} =====") + for w, h in sizes: + img = Image.new("RGB", (w, h), color=(123, 222, 100)) + batch_imgs = [img, img] + + # intrinsics / extrinsics examples + Ks_in = [make_K(w, h), make_K(w, h)] + Es_in = [np.eye(4, dtype=np.float32), np.eye(4, dtype=np.float32)] + + for m in methods: + tensor, Es_out, Ks_out = proc( + image=batch_imgs, + process_res=process_res, + process_res_method=m, + num_workers=8, + print_progress=False, + intrinsics=Ks_in, # test with non-None + extrinsics=Es_in, + ) + show_result(f"{suite_name} size=({w},{h}) | {m}", tensor, Ks_in, Ks_out) + + # Also test None path + tensor2, Es_out2, Ks_out2 = proc( + image=batch_imgs, + process_res=process_res, + process_res_method="upper_bound_resize", + num_workers=8, + intrinsics=None, + extrinsics=None, + ) + show_result( + f"{suite_name} size=({w},{h}) | upper_bound_resize | no K/E", + tensor2, + None, + Ks_out2, + ) + + run_suite("SMALL", small_sizes) + run_suite("LARGE", large_sizes) + + # Extra sanity for 504x376 + print("\n===== EXTRA sanity for 504x376 =====") + img_example = Image.new("RGB", (504, 376), color=(10, 20, 30)) + Ks_in_extra = [make_K(504, 376, fx=900.0, fy=900.0), make_K(504, 376, fx=900.0, fy=900.0)] + + out_r, _, Ks_out_r = proc( + image=[img_example, img_example], + process_res=504, + process_res_method="upper_bound_resize", + num_workers=8, + intrinsics=Ks_in_extra, + ) + out_c, _, Ks_out_c = proc( + image=[img_example, img_example], + process_res=504, + process_res_method="upper_bound_crop", + num_workers=8, + intrinsics=Ks_in_extra, + ) + _, _, _, Hr, Wr = out_r.shape + _, _, _, Hc, Wc = out_c.shape + print(f"upper_bound_resize -> ({Hr},{Wr}) (rounded to nearest multiple of 14)") + show_result("Ks after upper_bound_resize", out_r, Ks_in_extra, Ks_out_r) + print(f"upper_bound_crop -> ({Hc},{Wc}) (floored to multiple of 14)") + show_result("Ks after upper_bound_crop", out_c, Ks_in_extra, Ks_out_c) diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/io/output_processor.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/io/output_processor.py new file mode 100644 index 0000000000000000000000000000000000000000..c317eb9d596c1687b5281891a035993868cc5f8c --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/io/output_processor.py @@ -0,0 +1,172 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Output processor for Depth Anything 3. + +This module handles model output processing, including tensor-to-numpy conversion, +batch dimension removal, and Prediction object creation. +""" + +from __future__ import annotations + +import numpy as np +import torch +from addict import Dict as AddictDict + +from depth_anything_3.specs import Prediction + + +class OutputProcessor: + """ + Output processor for converting model outputs to Prediction objects. + + Handles tensor-to-numpy conversion, batch dimension removal, + and creates structured Prediction objects with proper data types. + """ + + def __init__(self) -> None: + """Initialize the output processor.""" + + def __call__(self, model_output: dict[str, torch.Tensor]) -> Prediction: + """ + Convert model output to Prediction object. + + Args: + model_output: Model output dictionary containing depth, conf, extrinsics, intrinsics + Expected shapes: depth (B, N, 1, H, W), conf (B, N, 1, H, W), + extrinsics (B, N, 4, 4), intrinsics (B, N, 3, 3) + + Returns: + Prediction: Object containing depth estimation results with shapes: + depth (N, H, W), conf (N, H, W), extrinsics (N, 4, 4), intrinsics (N, 3, 3) + """ + # Extract data from batch dimension (B=1, N=number of images) + depth = self._extract_depth(model_output) + conf = self._extract_conf(model_output) + extrinsics = self._extract_extrinsics(model_output) + intrinsics = self._extract_intrinsics(model_output) + sky = self._extract_sky(model_output) + aux = self._extract_aux(model_output) + gaussians = model_output.get("gaussians", None) + scale_factor = model_output.get("scale_factor", None) + + return Prediction( + depth=depth, + sky=sky, + conf=conf, + extrinsics=extrinsics, + intrinsics=intrinsics, + is_metric=getattr(model_output, "is_metric", 0), + gaussians=gaussians, + aux=aux, + scale_factor=scale_factor, + ) + + def _extract_depth(self, model_output: dict[str, torch.Tensor]) -> np.ndarray: + """ + Extract depth tensor from model output and convert to numpy. + + Args: + model_output: Model output dictionary + + Returns: + Depth array with shape (N, H, W) + """ + depth = model_output["depth"].squeeze(0).squeeze(-1).cpu().numpy() # (N, H, W) + return depth + + def _extract_conf(self, model_output: dict[str, torch.Tensor]) -> np.ndarray | None: + """ + Extract confidence tensor from model output and convert to numpy. + + Args: + model_output: Model output dictionary + + Returns: + Confidence array with shape (N, H, W) or None + """ + conf = model_output.get("depth_conf", None) + if conf is not None: + conf = conf.squeeze(0).cpu().numpy() # (N, H, W) + return conf + + def _extract_extrinsics(self, model_output: dict[str, torch.Tensor]) -> np.ndarray | None: + """ + Extract extrinsics tensor from model output and convert to numpy. + + Args: + model_output: Model output dictionary + + Returns: + Extrinsics array with shape (N, 4, 4) or None + """ + extrinsics = model_output.get("extrinsics", None) + if extrinsics is not None: + extrinsics = extrinsics.squeeze(0).cpu().numpy() # (N, 4, 4) + return extrinsics + + def _extract_intrinsics(self, model_output: dict[str, torch.Tensor]) -> np.ndarray | None: + """ + Extract intrinsics tensor from model output and convert to numpy. + + Args: + model_output: Model output dictionary + + Returns: + Intrinsics array with shape (N, 3, 3) or None + """ + intrinsics = model_output.get("intrinsics", None) + if intrinsics is not None: + intrinsics = intrinsics.squeeze(0).cpu().numpy() # (N, 3, 3) + return intrinsics + + def _extract_sky(self, model_output: dict[str, torch.Tensor]) -> np.ndarray | None: + """ + Extract sky tensor from model output and convert to numpy. + + Args: + model_output: Model output dictionary + + Returns: + Sky mask array with shape (N, H, W) or None + """ + sky = model_output.get("sky", None) + if sky is not None: + sky = sky.squeeze(0).cpu().numpy() >= 0.5 # (N, H, W) + return sky + + def _extract_aux(self, model_output: dict[str, torch.Tensor]) -> AddictDict: + """ + Extract auxiliary data from model output and convert to numpy. + + Args: + model_output: Model output dictionary + + Returns: + Dictionary containing auxiliary data + """ + aux = model_output.get("aux", None) + ret = AddictDict() + if aux is not None: + for k in aux.keys(): + if isinstance(aux[k], torch.Tensor): + ret[k] = aux[k].squeeze(0).cpu().numpy() + else: + ret[k] = aux[k] + return ret + + +# Backward compatibility alias +OutputAdapter = OutputProcessor diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/layout_helpers.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/layout_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..189c170b2007c979e580b69ca929638560923fb2 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/layout_helpers.py @@ -0,0 +1,216 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""This file contains useful layout utilities for images. They are: + +- add_border: Add a border to an image. +- cat/hcat/vcat: Join images by arranging them in a line. If the images have different + sizes, they are aligned as specified (start, end, center). Allows you to specify a gap + between images. + +Images are assumed to be float32 tensors with shape (channel, height, width). +""" + +from typing import Any, Generator, Iterable, Literal, Union +import torch +from torch import Tensor + +Alignment = Literal["start", "center", "end"] +Axis = Literal["horizontal", "vertical"] +Color = Union[ + int, + float, + Iterable[int], + Iterable[float], + Tensor, + Tensor, +] + + +def _sanitize_color(color: Color) -> Tensor: # "#channel" + # Convert tensor to list (or individual item). + if isinstance(color, torch.Tensor): + color = color.tolist() + + # Turn iterators and individual items into lists. + if isinstance(color, Iterable): + color = list(color) + else: + color = [color] + + return torch.tensor(color, dtype=torch.float32) + + +def _intersperse(iterable: Iterable, delimiter: Any) -> Generator[Any, None, None]: + it = iter(iterable) + yield next(it) + for item in it: + yield delimiter + yield item + + +def _get_main_dim(main_axis: Axis) -> int: + return { + "horizontal": 2, + "vertical": 1, + }[main_axis] + + +def _get_cross_dim(main_axis: Axis) -> int: + return { + "horizontal": 1, + "vertical": 2, + }[main_axis] + + +def _compute_offset(base: int, overlay: int, align: Alignment) -> slice: + assert base >= overlay + offset = { + "start": 0, + "center": (base - overlay) // 2, + "end": base - overlay, + }[align] + return slice(offset, offset + overlay) + + +def overlay( + base: Tensor, # "channel base_height base_width" + overlay: Tensor, # "channel overlay_height overlay_width" + main_axis: Axis, + main_axis_alignment: Alignment, + cross_axis_alignment: Alignment, +) -> Tensor: # "channel base_height base_width" + # The overlay must be smaller than the base. + _, base_height, base_width = base.shape + _, overlay_height, overlay_width = overlay.shape + assert base_height >= overlay_height and base_width >= overlay_width + + # Compute spacing on the main dimension. + main_dim = _get_main_dim(main_axis) + main_slice = _compute_offset( + base.shape[main_dim], overlay.shape[main_dim], main_axis_alignment + ) + + # Compute spacing on the cross dimension. + cross_dim = _get_cross_dim(main_axis) + cross_slice = _compute_offset( + base.shape[cross_dim], overlay.shape[cross_dim], cross_axis_alignment + ) + + # Combine the slices and paste the overlay onto the base accordingly. + selector = [..., None, None] + selector[main_dim] = main_slice + selector[cross_dim] = cross_slice + result = base.clone() + result[selector] = overlay + return result + + +def cat( + main_axis: Axis, + *images: Iterable[Tensor], # "channel _ _" + align: Alignment = "center", + gap: int = 8, + gap_color: Color = 1, +) -> Tensor: # "channel height width" + """Arrange images in a line. The interface resembles a CSS div with flexbox.""" + device = images[0].device + gap_color = _sanitize_color(gap_color).to(device) + + # Find the maximum image side length in the cross axis dimension. + cross_dim = _get_cross_dim(main_axis) + cross_axis_length = max(image.shape[cross_dim] for image in images) + + # Pad the images. + padded_images = [] + for image in images: + # Create an empty image with the correct size. + padded_shape = list(image.shape) + padded_shape[cross_dim] = cross_axis_length + base = torch.ones(padded_shape, dtype=torch.float32, device=device) + base = base * gap_color[:, None, None] + padded_images.append(overlay(base, image, main_axis, "start", align)) + + # Intersperse separators if necessary. + if gap > 0: + # Generate a separator. + c, _, _ = images[0].shape + separator_size = [gap, gap] + separator_size[cross_dim - 1] = cross_axis_length + separator = torch.ones((c, *separator_size), dtype=torch.float32, device=device) + separator = separator * gap_color[:, None, None] + + # Intersperse the separator between the images. + padded_images = list(_intersperse(padded_images, separator)) + + return torch.cat(padded_images, dim=_get_main_dim(main_axis)) + + +def hcat( + *images: Iterable[Tensor], # "channel _ _" + align: Literal["start", "center", "end", "top", "bottom"] = "start", + gap: int = 8, + gap_color: Color = 1, +): + """Shorthand for a horizontal linear concatenation.""" + return cat( + "horizontal", + *images, + align={ + "start": "start", + "center": "center", + "end": "end", + "top": "start", + "bottom": "end", + }[align], + gap=gap, + gap_color=gap_color, + ) + + +def vcat( + *images: Iterable[Tensor], # "channel _ _" + align: Literal["start", "center", "end", "left", "right"] = "start", + gap: int = 8, + gap_color: Color = 1, +): + """Shorthand for a horizontal linear concatenation.""" + return cat( + "vertical", + *images, + align={ + "start": "start", + "center": "center", + "end": "end", + "left": "start", + "right": "end", + }[align], + gap=gap, + gap_color=gap_color, + ) + + +def add_border( + image: Tensor, # "channel height width" + border: int = 8, + color: Color = 1, +) -> Tensor: # "channel new_height new_width" + color = _sanitize_color(color).to(image) + c, h, w = image.shape + result = torch.empty( + (c, h + 2 * border, w + 2 * border), dtype=torch.float32, device=image.device + ) + result[:] = color[:, None, None] + result[:, border : h + border, border : w + border] = image + return result diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/logger.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/logger.py new file mode 100644 index 0000000000000000000000000000000000000000..0eb4f60696a085001cf4866ccfe1654170702a2d --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/logger.py @@ -0,0 +1,82 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +import sys + + +class Color: + RED = "\033[91m" + YELLOW = "\033[93m" + WHITE = "\033[97m" + GREEN = "\033[92m" + RESET = "\033[0m" + + +LOG_LEVELS = {"ERROR": 0, "WARN": 1, "INFO": 2, "DEBUG": 3} + +COLOR_MAP = {"ERROR": Color.RED, "WARN": Color.YELLOW, "INFO": Color.WHITE, "DEBUG": Color.GREEN} + + +def get_env_log_level(): + level = os.environ.get("DA3_LOG_LEVEL", "INFO").upper() + return LOG_LEVELS.get(level, LOG_LEVELS["INFO"]) + + +class Logger: + def __init__(self): + self.level = get_env_log_level() + + def log(self, level_str, *args, **kwargs): + level_key = level_str.split(":")[0].strip() + level_val = LOG_LEVELS.get(level_key) + if level_val is None: + raise ValueError(f"Unknown log level: {level_str}") + if self.level >= level_val: + color = COLOR_MAP[level_key] + msg = " ".join(str(arg) for arg in args) + + # Align log level output in square brackets + # ERROR and DEBUG are 5 characters, INFO and WARN have an extra space for alignment + tag = level_key + if tag in ("INFO", "WARN"): + tag += " " + print( + f"{color}[{tag}] {msg}{Color.RESET}", + file=sys.stderr if level_key == "ERROR" else sys.stdout, + **kwargs, + ) + + def error(self, *args, **kwargs): + self.log("ERROR:", *args, **kwargs) + + def warn(self, *args, **kwargs): + self.log("WARN:", *args, **kwargs) + + def info(self, *args, **kwargs): + self.log("INFO:", *args, **kwargs) + + def debug(self, *args, **kwargs): + self.log("DEBUG:", *args, **kwargs) + + +logger = Logger() + +__all__ = ["logger"] + +if __name__ == "__main__": + logger.info("This is an info message") + logger.warn("This is a warning message") + logger.error("This is an error message") + logger.debug("This is a debug message") diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/memory.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/memory.py new file mode 100644 index 0000000000000000000000000000000000000000..682dad76b2fccd606246144788cec0198eed2a62 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/memory.py @@ -0,0 +1,127 @@ +""" +GPU memory utility helpers. + +Shared cleanup and memory checking logic used by both the backend API and +the Gradio UI to keep memory-management behavior consistent. +""" +from __future__ import annotations + +import gc + +from typing import Any, Dict, Optional + +import torch + + +def get_gpu_memory_info() -> Optional[Dict[str, Any]]: + """Return a snapshot of current GPU memory usage or None if CUDA not available. + + Keys in returned dict: total_gb, allocated_gb, reserved_gb, free_gb, utilization + """ + if not torch.cuda.is_available(): + return None + + try: + device = torch.cuda.current_device() + total_memory = torch.cuda.get_device_properties(device).total_memory + allocated_memory = torch.cuda.memory_allocated(device) + reserved_memory = torch.cuda.memory_reserved(device) + free_memory = total_memory - reserved_memory + + return { + "total_gb": total_memory / 1024 ** 3, + "allocated_gb": allocated_memory / 1024 ** 3, + "reserved_gb": reserved_memory / 1024 ** 3, + "free_gb": free_memory / 1024 ** 3, + "utilization": (reserved_memory / total_memory) * 100, + } + except Exception: + return None + + +def cleanup_cuda_memory() -> None: + """Perform a robust GPU cleanup sequence. + + This includes synchronizing, emptying caches, collecting IPC handles and + running the Python garbage collector. Use this instead of a raw + ``torch.cuda.empty_cache()`` where you need reliable freeing of GPU memory + between model loads or in error handling paths. + """ + try: + if torch.cuda.is_available(): + mem_before = get_gpu_memory_info() + + torch.cuda.synchronize() + torch.cuda.empty_cache() + # Collect cross-process cuda resources + try: + torch.cuda.ipc_collect() + except Exception: + # Older PyTorch versions or non-cuda devices may not support + # ipc_collect (no-op if not available) + pass + gc.collect() + + mem_after = get_gpu_memory_info() + if mem_before and mem_after: + freed = mem_before["reserved_gb"] - mem_after["reserved_gb"] + print( + f"CUDA cleanup: freed {freed:.2f}GB, " + f"available: {mem_after['free_gb']:.2f}GB/{mem_after['total_gb']:.2f}GB" + ) + else: + print("CUDA memory cleanup completed") + except Exception as e: + print(f"Warning: CUDA cleanup failed: {e}") + + +def check_memory_availability(required_gb: float = 2.0) -> tuple[bool, str]: + """Return whether at least ``required_gb`` seems available on the current GPU. + + The returned tuple is (is_available, message) with a human-friendly message. + """ + try: + if not torch.cuda.is_available(): + return False, "CUDA is not available" + + mem_info = get_gpu_memory_info() + if mem_info is None: + return True, "Cannot check memory, proceeding anyway" + + if mem_info["free_gb"] < required_gb: + return ( + False, + ( + f"Insufficient GPU memory: {mem_info['free_gb']:.2f}GB available, " + f"{required_gb:.2f}GB required. Total: {mem_info['total_gb']:.2f}GB, " + f"Used: {mem_info['reserved_gb']:.2f}GB ({mem_info['utilization']:.1f}%)" + ), + ) + + return ( + True, + ( + f"Memory check passed: {mem_info['free_gb']:.2f}GB available, " + f"{required_gb:.2f}GB required" + ), + ) + except Exception as e: + return True, f"Memory check failed: {e}, proceeding anyway" +def estimate_memory_requirement(num_images: int, process_res: int) -> float: + """Heuristic estimate for memory usage (GB) based on image count and resolution. + + This mirrors the simple policy used by the backend service so other code + (e.g., Gradio UI) can make consistent decisions when checking available + memory before loading a model or running inference. + + Args: + num_images: Number of images to process. + process_res: Processing resolution. + + Returns: + Estimated memory requirement in GB. + """ + base_memory = 2.0 + per_image_memory = (process_res / 504) ** 2 * 0.5 + total_memory = base_memory + (num_images * per_image_memory * 0.1) + return total_memory diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/model_loading.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/model_loading.py new file mode 100644 index 0000000000000000000000000000000000000000..b6d43b5bbab5a0989eae272422192103cd4d5bee --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/model_loading.py @@ -0,0 +1,149 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Model loading and state dict conversion utilities. +""" + +from typing import Dict, Tuple +import torch + +from depth_anything_3.utils.logger import logger + + +def convert_general_state_dict(state_dict: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]: + """ + Convert general model state dict to match current model architecture. + + Args: + state_dict: Original state dictionary + + Returns: + Converted state dictionary + """ + # Replace module prefixes + state_dict = {k.replace("module.", "model."): v for k, v in state_dict.items()} + state_dict = {k.replace(".net.", ".backbone."): v for k, v in state_dict.items()} + + # Remove camera token if present + if "model.backbone.pretrained.camera_token" in state_dict: + del state_dict["model.backbone.pretrained.camera_token"] + + # Replace camera token naming + state_dict = { + k.replace(".camera_token_extra", ".camera_token"): v for k, v in state_dict.items() + } + + # Replace head naming + state_dict = { + k.replace("model.all_heads.camera_cond_head", "model.cam_enc"): v + for k, v in state_dict.items() + } + state_dict = { + k.replace("model.all_heads.camera_head", "model.cam_dec"): v for k, v in state_dict.items() + } + state_dict = {k.replace(".more_mlps.", ".backbone."): v for k, v in state_dict.items()} + state_dict = {k.replace(".fc_rot.", ".fc_qvec."): v for k, v in state_dict.items()} + state_dict = { + k.replace("model.all_heads.head", "model.head"): v for k, v in state_dict.items() + } + + # Replace output naming + state_dict = { + k.replace("output_conv2_additional.sky_mask", "sky_output_conv2"): v + for k, v in state_dict.items() + } + state_dict = {k.replace("_ray.", "_aux."): v for k, v in state_dict.items()} + + # Update GS-DPT head naming and value + state_dict = {k.replace("gaussian_param_head.", "gs_head."): v for k, v in state_dict.items()} + + return state_dict + + +def convert_metric_state_dict(state_dict: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]: + """ + Convert metric model state dict to match current model architecture. + + Args: + state_dict: Original metric state dictionary + + Returns: + Converted state dictionary + """ + # Add module prefix for metric models + state_dict = {"module." + k: v for k, v in state_dict.items()} + return convert_general_state_dict(state_dict) + + +def load_pretrained_weights(model, model_path: str, is_metric: bool = False) -> Tuple[list, list]: + """ + Load pretrained weights for a single model. + + Args: + model: Model instance to load weights into + model_path: Path to the pretrained weights + is_metric: Whether this is a metric model + + Returns: + Tuple of (missed_keys, unexpected_keys) + """ + state_dict = torch.load(model_path, map_location="cpu") + + if is_metric: + state_dict = convert_metric_state_dict(state_dict) + else: + state_dict = convert_general_state_dict(state_dict) + + missed, unexpected = model.load_state_dict(state_dict, strict=False) + logger.info("Missed keys:", missed) + logger.info("Unexpected keys:", unexpected) + + return missed, unexpected + + +def load_pretrained_nested_weights( + model, main_model_path: str, metric_model_path: str +) -> Tuple[list, list]: + """ + Load pretrained weights for a nested model with both main and metric branches. + + Args: + model: Nested model instance + main_model_path: Path to main model weights + metric_model_path: Path to metric model weights + + Returns: + Tuple of (missed_keys, unexpected_keys) + """ + # Load main model weights + state_dict0 = torch.load(main_model_path, map_location="cpu") + state_dict0 = convert_general_state_dict(state_dict0) + state_dict0 = {k.replace("model.", "model.da3."): v for k, v in state_dict0.items()} + + # Load metric model weights + state_dict1 = torch.load(metric_model_path, map_location="cpu") + state_dict1 = convert_metric_state_dict(state_dict1) + state_dict1 = {k.replace("model.", "model.da3_metric."): v for k, v in state_dict1.items()} + + # Combine state dictionaries + combined_state_dict = state_dict0.copy() + combined_state_dict.update(state_dict1) + + missed, unexpected = model.load_state_dict(combined_state_dict, strict=False) + + print("Missed keys:", missed) + print("Unexpected keys:", unexpected) + + return missed, unexpected diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/parallel_utils.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/parallel_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..9ff108e95d205097f9f2012ab87ad9e265d58d8d --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/parallel_utils.py @@ -0,0 +1,133 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import asyncio +import os +from functools import wraps +from multiprocessing.pool import ThreadPool +from threading import Thread +from typing import Callable, Dict, List +import imageio +from tqdm import tqdm + + +def async_call_func(func): + @wraps(func) + async def wrapper(*args, **kwargs): + loop = asyncio.get_event_loop() + # Use run_in_executor to run the blocking function in a separate thread + return await loop.run_in_executor(None, func, *args, **kwargs) + + return wrapper + + +slice_func = lambda chunk_index, chunk_dim, chunk_size: [slice(None)] * chunk_dim + [ + slice(chunk_index, chunk_index + chunk_size) +] + + +def async_call(fn): + def wrapper(*args, **kwargs): + Thread(target=fn, args=args, kwargs=kwargs).start() + + return wrapper + + +def _save_image_impl(save_img, save_path): + """Common implementation for saving images synchronously or asynchronously""" + os.makedirs(os.path.dirname(save_path), exist_ok=True) + imageio.imwrite(save_path, save_img) + + +@async_call +def save_image_async(save_img, save_path): + """Save image asynchronously""" + _save_image_impl(save_img, save_path) + + +def save_image(save_img, save_path): + """Save image synchronously""" + _save_image_impl(save_img, save_path) + + +def parallel_execution( + *args, + action: Callable, + num_processes=32, + print_progress=False, + sequential=False, + async_return=False, + desc=None, + **kwargs, +): + # Partially copy from EasyVolumetricVideo (parallel_execution) + # NOTE: we expect first arg / or kwargs to be distributed + # NOTE: print_progress arg is reserved. + # `*args` packs all positional arguments passed to the function into a tuple + args = list(args) + + def get_length(args: List, kwargs: Dict): + for a in args: + if isinstance(a, list): + return len(a) + for v in kwargs.values(): + if isinstance(v, list): + return len(v) + raise NotImplementedError + + def get_action_args(length: int, args: List, kwargs: Dict, i: int): + action_args = [ + (arg[i] if isinstance(arg, list) and len(arg) == length else arg) for arg in args + ] + # TODO: Support all types of iterable + action_kwargs = { + key: ( + kwargs[key][i] + if isinstance(kwargs[key], list) and len(kwargs[key]) == length + else kwargs[key] + ) + for key in kwargs + } + return action_args, action_kwargs + + if not sequential: + # Create ThreadPool + pool = ThreadPool(processes=num_processes) + + # Spawn threads + results = [] + asyncs = [] + length = get_length(args, kwargs) + for i in range(length): + action_args, action_kwargs = get_action_args(length, args, kwargs, i) + async_result = pool.apply_async(action, action_args, action_kwargs) + asyncs.append(async_result) + + # Join threads and get return values + if not async_return: + for async_result in tqdm(asyncs, desc=desc, disable=not print_progress): + results.append(async_result.get()) # will sync the corresponding thread + pool.close() + pool.join() + return results + else: + return pool + else: + results = [] + length = get_length(args, kwargs) + for i in tqdm(range(length), desc=desc, disable=not print_progress): + action_args, action_kwargs = get_action_args(length, args, kwargs, i) + async_result = action(*action_args, **action_kwargs) + results.append(async_result) + return results diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/pca_utils.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/pca_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..2b9eee268cd8692d885bf093700a5752077b9d7d --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/pca_utils.py @@ -0,0 +1,284 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +PCA utilities for feature visualization and dimensionality reduction (video-friendly). +- Support frame-by-frame: transform_frame / transform_video +- Support one-time global PCA fitting and reuse (mean, V3) for stable colors +- Support Procrustes alignment (solving principal component order/sign/rotation jumps) +- Support global fixed or temporal EMA for percentiles (time dimension only, no spatial) +""" + +import numpy as np +import torch + + +def pca_to_rgb_4d_bf16_percentile( + x_np: np.ndarray, + device=None, + q_oversample: int = 6, + clip_percent: float = 10.0, # Percentage to clip from top and bottom (0~49.9) + return_uint8: bool = False, + enable_autocast_bf16: bool = True, +): + """ + Reduce numpy array of shape (49, 27, 36, 3072) to 3D via PCA and visualize as (49, 27, 36, 3). + - PCA uses torch.pca_lowrank (randomized SVD), defaults to GPU. + - Uses CUDA bf16 autocast in computation (if available), + then per-channel percentile clipping and normalization. + - Default removes 5% outliers from top and bottom (adjustable via clip_percent) to + improve visualization contrast. + + Parameters + ---------- + x_np : np.ndarray + Shape must be (49, 27, 36, 3072). dtype recommended float32/float64. + device : str | None + Specify 'cuda' or 'cpu'. Auto-select if None (prefer cuda). + q_oversample : int + Oversampling q for pca_lowrank, must be >= 3. + Slightly larger than target dim (3) is more stable, default 6. + clip_percent : float + Percentage to clip from top and bottom (0~49.9), + e.g. 5.0 means clip lowest 5% and highest 5% per channel. + return_uint8 : bool + True returns uint8(0~255), otherwise returns float32(0~1). + enable_autocast_bf16 : bool + Enable bf16 autocast on CUDA. + + Returns + ------- + np.ndarray + Array of shape (49, 27, 36, 3), float32[0,1] or uint8[0,255]. + """ + assert ( + x_np.ndim == 4 + ) # and x_np.shape[-1] == 3072, f"expect (49,27,36,3072), got {x_np.shape}" + B1, B2, B3, D = x_np.shape + N = B1 * B2 * B3 + + # Device selection + if device is None: + device = "cuda" if torch.cuda.is_available() else "cpu" + + # Convert input to torch, unified float32 + X = torch.from_numpy(x_np.reshape(N, D)).to(device=device, dtype=torch.float32) + + # Parameter and safety checks + k = 3 + q = max(int(q_oversample), k) + clip_percent = float(clip_percent) + if not (0.0 <= clip_percent < 50.0): + raise ValueError( + "clip_percent must be in [0, 50), e.g. 5.0 means clip 5% from top and bottom" + ) + low = clip_percent / 100.0 + high = 1.0 - low + + with torch.no_grad(): + # Zero mean + mean = X.mean(dim=0, keepdim=True) + Xc = X - mean + + # Main computation: PCA + projection, try to use bf16 + # (auto-fallback if operator not supported) + device.startswith("cuda") and enable_autocast_bf16 + U, S, V = torch.pca_lowrank(Xc, q=q, center=False) # V: (D, q) + V3 = V[:, :k] # (3072, 3) + PCs = Xc @ V3 # (N, 3) + + # === Per-channel percentile clipping and normalization to [0,1] === + # Vectorized one-time calculation of low/high percentiles for each channel + qs = torch.tensor([low, high], device=PCs.device, dtype=PCs.dtype) + qvals = torch.quantile(PCs, q=qs, dim=0) # Shape (2, 3) + lo = qvals[0] # (3,) + hi = qvals[1] # (3,) + + # Avoid degenerate case where hi==lo + denom = torch.clamp(hi - lo, min=1e-8) + + # Broadcast clipping + normalization + PCs = torch.clamp(PCs, lo, hi) + PCs = (PCs - lo) / denom # (N, 3) in [0,1] + + # Restore 4D + PCs = PCs.reshape(B1, B2, B3, k) + + # Output + if return_uint8: + out = (PCs * 255.0).round().clamp(0, 255).to(torch.uint8).cpu().numpy() + else: + out = PCs.clamp(0, 1).to(torch.float32).cpu().numpy() + + return out + + +class PCARGBVisualizer: + """ + Stable PCA→RGB for video features shaped (T, H, W, D) or a single frame (H, W, D). + - Global mean/V3 reference for stable colors + - Per-frame PCA with Procrustes alignment to V3_ref (basis_mode='procrustes') + - Percentile normalization with global or EMA stats (time-only, no spatial smoothing) + """ + + def __init__( + self, + device=None, + q_oversample: int = 16, + clip_percent: float = 10.0, + return_uint8: bool = False, + enable_autocast_bf16: bool = True, + basis_mode: str = "procrustes", # 'fixed' | 'procrustes' + percentile_mode: str = "ema", # 'global' | 'ema' + ema_alpha: float = 0.1, + denom_eps: float = 1e-4, + ): + assert 0.0 <= clip_percent < 50.0 + assert basis_mode in ("fixed", "procrustes") + assert percentile_mode in ("global", "ema") + self.device = device or ("cuda" if torch.cuda.is_available() else "cpu") + self.q = max(int(q_oversample), 6) + self.clip_percent = float(clip_percent) + self.return_uint8 = return_uint8 + self.enable_autocast_bf16 = enable_autocast_bf16 + self.basis_mode = basis_mode + self.percentile_mode = percentile_mode + self.ema_alpha = float(ema_alpha) + self.denom_eps = float(denom_eps) + + # reference state + self.mean_ref = None # (1, D) + self.V3_ref = None # (D, 3) + self.lo_ref = None # (3,) + self.hi_ref = None # (3,) + + @torch.no_grad() + def fit_reference(self, frames): + """ + Fit global mean/V3 and initialize percentiles from a reference set. + frames: ndarray (T,H,W,D) or list of (H,W,D) + """ + if isinstance(frames, np.ndarray): + if frames.ndim != 4: + raise ValueError("fit_reference expects (T,H,W,D) ndarray.") + T, H, W, D = frames.shape + X = torch.from_numpy(frames.reshape(T * H * W, D)) + else: # list of (H,W,D) + xs = [torch.from_numpy(x.reshape(-1, x.shape[-1])) for x in frames] + D = xs[0].shape[-1] + X = torch.cat(xs, dim=0) + + X = X.to(self.device, dtype=torch.float32) + X = torch.nan_to_num(X, nan=0.0, posinf=1e6, neginf=-1e6) + + mean = X.mean(0, keepdim=True) + Xc = X - mean + + U, S, V = torch.pca_lowrank(Xc, q=max(self.q, 8), center=False) + V3 = V[:, :3] # (D,3) + + PCs = Xc @ V3 + low = self.clip_percent / 100.0 + high = 1.0 - low + qs = torch.tensor([low, high], device=PCs.device, dtype=PCs.dtype) + qvals = torch.quantile(PCs, q=qs, dim=0) + lo, hi = qvals[0], qvals[1] + + self.mean_ref = mean + self.V3_ref = V3 + if self.percentile_mode == "global": + self.lo_ref, self.hi_ref = lo, hi + else: + self.lo_ref = lo.clone() + self.hi_ref = hi.clone() + + @torch.no_grad() + def _project_with_stable_colors(self, X: torch.Tensor) -> torch.Tensor: + """ + X: (N,D) where N = H*W + Returns PCs_raw: (N,3) using stable basis (fixed or Procrustes-aligned) + """ + assert self.mean_ref is not None and self.V3_ref is not None, "Call fit_reference() first." + X = torch.nan_to_num(X, nan=0.0, posinf=1e6, neginf=-1e6) + Xc = X - self.mean_ref + + if self.basis_mode == "fixed": + V3_used = self.V3_ref + else: + U, S, V = torch.pca_lowrank(Xc, q=max(self.q, 6), center=False) + V3 = V[:, :3] # (D,3) + M = V3.T @ self.V3_ref + Uo, So, Vh = torch.linalg.svd(M) + R = Uo @ Vh + V3_used = V3 @ R + # Optional polarity fix via anchor + a = self.V3_ref.mean(0, keepdim=True) + sign = torch.sign((V3_used * a).sum(0, keepdim=True)).clamp(min=-1) + V3_used = V3_used * sign + + return Xc @ V3_used + + @torch.no_grad() + def _normalize_rgb(self, PCs_raw: torch.Tensor) -> torch.Tensor: + assert self.lo_ref is not None and self.hi_ref is not None + if self.percentile_mode == "global": + lo, hi = self.lo_ref, self.hi_ref + else: + low = self.clip_percent / 100.0 + high = 1.0 - low + qs = torch.tensor([low, high], device=PCs_raw.device, dtype=PCs_raw.dtype) + qvals = torch.quantile(PCs_raw, q=qs, dim=0) + lo_now, hi_now = qvals[0], qvals[1] + a = self.ema_alpha + self.lo_ref = (1 - a) * self.lo_ref + a * lo_now + self.hi_ref = (1 - a) * self.hi_ref + a * hi_now + lo, hi = self.lo_ref, self.hi_ref + + denom = torch.clamp(hi - lo, min=self.denom_eps) + PCs = torch.clamp(PCs_raw, lo, hi) + PCs = (PCs - lo) / denom + return PCs.clamp_(0, 1) + + @torch.no_grad() + def transform_frame(self, frame: np.ndarray) -> np.ndarray: + """ + frame: (H,W,D) -> (H,W,3) + """ + if frame.ndim != 3: + raise ValueError("transform_frame expects (H,W,D).") + H, W, D = frame.shape + X = torch.from_numpy(frame.reshape(H * W, D)).to(self.device, dtype=torch.float32) + PCs_raw = self._project_with_stable_colors(X) + PCs = self._normalize_rgb(PCs_raw).reshape(H, W, 3) + if self.return_uint8: + return (PCs * 255.0).round().clamp(0, 255).to(torch.uint8).cpu().numpy() + return PCs.to(torch.float32).cpu().numpy() + + @torch.no_grad() + def transform_video(self, frames) -> np.ndarray: + """ + frames: (T,H,W,D) or list of (H,W,D) + returns: (T,H,W,3) + """ + outs = [] + if isinstance(frames, np.ndarray): + if frames.ndim != 4: + raise ValueError("transform_video expects (T,H,W,D).") + T, H, W, D = frames.shape + for t in range(T): + outs.append(self.transform_frame(frames[t])) + else: + for f in frames: + outs.append(self.transform_frame(f)) + return np.stack(outs, axis=0) diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/pose_align.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/pose_align.py new file mode 100644 index 0000000000000000000000000000000000000000..695d07fc1210e3cc3614c9b22c56d765b1106500 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/pose_align.py @@ -0,0 +1,347 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import List +import numpy as np +import torch +from evo.core.trajectory import PosePath3D + +from depth_anything_3.utils.geometry import affine_inverse, affine_inverse_np + + +def batch_apply_alignment_to_enc( + rots: torch.Tensor, trans: torch.Tensor, scales: torch.Tensor, enc_list: List[torch.Tensor] +): + pass + + +def batch_apply_alignment_to_ext( + rots: torch.Tensor, trans: torch.Tensor, scales: torch.Tensor, ext: torch.Tensor +): + device, _ = ext.device, ext.dtype + if ext.shape[-2:] == (3, 4): + pad = torch.zeros((*ext.shape[:-2], 4, 4), dtype=ext.dtype, device=device) + pad[..., :3, :4] = ext + pad[..., 3, 3] = 1.0 + ext = pad + pose_est = affine_inverse(ext) + pose_new_align_rot = rots[:, None] @ pose_est[..., :3, :3] + pose_new_align_trans = ( + scales[:, None, None] * (rots[:, None] @ pose_est[..., :3, 3:])[..., 0] + trans[:, None] + ) + pose_new_align = torch.zeros_like(ext) + pose_new_align[..., :3, :3] = pose_new_align_rot + pose_new_align[..., :3, 3] = pose_new_align_trans + pose_new_align[..., 3, 3] = 1.0 + return affine_inverse(pose_new_align)[:, :3] + + +def batch_align_poses_umeyama(ext_ref: torch.Tensor, ext_est: torch.Tensor): + device, dtype = ext_ref.device, ext_ref.dtype + assert ext_ref.dtype in [torch.float32, torch.float64] + assert ext_est.dtype in [torch.float32, torch.float64] + assert ext_ref.requires_grad is False + assert ext_est.requires_grad is False + rots, trans, scales = [], [], [] + for b in range(ext_ref.shape[0]): + r, t, s = align_poses_umeyama(ext_ref[b].cpu().numpy(), ext_est[b].cpu().numpy()) + rots.append(torch.from_numpy(r).to(device=device, dtype=dtype)) + trans.append(torch.from_numpy(t).to(device=device, dtype=dtype)) + scales.append(torch.tensor(s, device=device, dtype=dtype)) + return torch.stack(rots), torch.stack(trans), torch.stack(scales) + + +# Dependencies: affine_inverse_np, PosePath3D (maintain consistency with your existing project) + + +def _to44(ext): + if ext.shape[1] == 3: + out = np.eye(4)[None].repeat(len(ext), 0) + out[:, :3, :4] = ext + return out + return ext + + +def _poses_from_ext(ext_ref, ext_est): + ext_ref = _to44(ext_ref) + ext_est = _to44(ext_est) + pose_ref = affine_inverse_np(ext_ref) + pose_est = affine_inverse_np(ext_est) + return pose_ref, pose_est + + +def _umeyama_sim3_from_paths(pose_ref, pose_est): + path_ref = PosePath3D(poses_se3=pose_ref.copy()) + path_est = PosePath3D(poses_se3=pose_est.copy()) + r, t, s = path_est.align(path_ref, correct_scale=True) + pose_est_aligned = np.stack(path_est.poses_se3) + return r, t, s, pose_est_aligned + + +def _apply_sim3_to_poses(poses, r, t, s): + out = poses.copy() + Ri = poses[:, :3, :3] + ti = poses[:, :3, 3] + out[:, :3, :3] = r @ Ri + out[:, :3, 3] = (r @ (s * ti.T)).T + t + return out + + +def _median_nn_thresh(pose_ref, pose_est_aligned): + P_ref = pose_ref[:, :3, 3] + P_est = pose_est_aligned[:, :3, 3] + dists = [] + for p in P_est: + dd = np.linalg.norm(P_ref - p[None, :], axis=1) + dists.append(dd.min()) + return float(np.median(dists)) if dists else 0.0 + + +def _ransac_align_sim3( + pose_ref, pose_est, sub_n=None, inlier_thresh=None, max_iters=10, random_state=None +): + rng = np.random.default_rng(random_state) + N = pose_ref.shape[0] + idx_all = np.arange(N) + if sub_n is None: + sub_n = max(3, (N + 1) // 2) + else: + sub_n = max(3, min(sub_n, N)) + + # Pre-alignment + default threshold + r0, t0, s0, pose_est0 = _umeyama_sim3_from_paths(pose_ref, pose_est) + if inlier_thresh is None: + inlier_thresh = _median_nn_thresh(pose_ref, pose_est0) + + P_ref_all = pose_ref[:, :3, 3] + + best_model = (r0, t0, s0) + best_inliers = None + best_score = (-1, np.inf) # (num_inliers, mean_err) + + for _ in range(max_iters): + sample = rng.choice(idx_all, size=sub_n, replace=False) + try: + r, t, s, _ = _umeyama_sim3_from_paths(pose_ref[sample], pose_est[sample]) + except Exception: + continue + pose_h = _apply_sim3_to_poses(pose_est, r, t, s) + P_h = pose_h[:, :3, 3] + errs = np.linalg.norm(P_h - P_ref_all, axis=1) # Match by same index + inliers = errs <= inlier_thresh + k = int(inliers.sum()) + mean_err = float(errs[inliers].mean()) if k > 0 else np.inf + if (k > best_score[0]) or (k == best_score[0] and mean_err < best_score[1]): + best_score = (k, mean_err) + best_model = (r, t, s) + best_inliers = inliers + + # Fit again with best inliers + if best_inliers is not None and best_inliers.sum() >= 3: + r, t, s, _ = _umeyama_sim3_from_paths(pose_ref[best_inliers], pose_est[best_inliers]) + else: + r, t, s = best_model + return r, t, s + + +def align_poses_umeyama( + ext_ref: np.ndarray, + ext_est: np.ndarray, + return_aligned=False, + ransac=False, + sub_n=None, + inlier_thresh=None, + ransac_max_iters=10, + random_state=None, +): + """ + Align estimated trajectory to reference using Umeyama Sim(3). + Default no RANSAC; if ransac=True, use RANSAC (max iterations default 10). + - sub_n defaults to half the number of frames (rounded up, at least 3) + - inlier_thresh defaults to median of "distance from each estimated pose to + nearest reference pose after pre-alignment" + Returns rotation (3x3), translation (3,), scale; optionally returns aligned extrinsics (4x4). + """ + pose_ref, pose_est = _poses_from_ext(ext_ref, ext_est) + + if not ransac: + r, t, s, pose_est_aligned = _umeyama_sim3_from_paths(pose_ref, pose_est) + else: + r, t, s = _ransac_align_sim3( + pose_ref, + pose_est, + sub_n=sub_n, + inlier_thresh=inlier_thresh, + max_iters=ransac_max_iters, + random_state=random_state, + ) + pose_est_aligned = _apply_sim3_to_poses(pose_est, r, t, s) + + if return_aligned: + ext_est_aligned = affine_inverse_np(pose_est_aligned) + return r, t, s, ext_est_aligned + return r, t, s + + +# def align_poses_umeyama(ext_ref: np.ndarray, ext_est: np.ndarray, return_aligned=False): +# """ +# Align estimated trajectory to reference trajectory using Umeyama Sim(3) +# alignment (via evo PosePath3D). # noqa +# Returns rotation, translation, and scale. +# """ +# # If input extrinsics are 3x4, convert to 4x4 by padding +# if ext_ref.shape[1] == 3: +# ext_ref_ = np.eye(4)[None].repeat(len(ext_ref), 0) +# ext_ref_[:, :3] = ext_ref +# ext_ref = ext_ref_ +# if ext_est.shape[1] == 3: +# ext_est_ = np.eye(4)[None].repeat(len(ext_est), 0) +# ext_est_[:, :3] = ext_est +# ext_est = ext_est_ + +# # Convert to camera poses (inverse extrinsics) +# pose_ref = affine_inverse_np(ext_ref) +# pose_est = affine_inverse_np(ext_est) + +# # Create evo PosePath3D objects +# path_ref = PosePath3D(poses_se3=pose_ref) +# path_est = PosePath3D(poses_se3=pose_est) +# r, t, s = path_est.align(path_ref, correct_scale=True) +# if return_aligned: +# return r, t, s, affine_inverse_np(np.stack(path_est.poses_se3)) +# else: +# return r, t, s + + +def apply_umeyama_alignment_to_ext( + rot: np.ndarray, # (3,3) + trans: np.ndarray, # (3,) or (1,3) + scale: float, + ext_est: np.ndarray, # (...,4,4) or (...,3,4) +) -> np.ndarray: + """ + Apply Sim(3) (R, t, s) to a batch of world-to-camera extrinsics ext_est. + Returns the aligned extrinsics, with the same shape as input. + """ + + # Allow 3x4 extrinsics: pad to 4x4 + if ext_est.shape[-2:] == (3, 4): + pad = np.zeros((*ext_est.shape[:-2], 4, 4), dtype=ext_est.dtype) + pad[..., :3, :4] = ext_est + pad[..., 3, 3] = 1.0 + ext_est = pad + + # Convert world-to-camera to camera-to-world + pose_est = affine_inverse_np(ext_est) # (...,4,4) + R_e = pose_est[..., :3, :3] # (...,3,3) + t_e = pose_est[..., :3, 3] # (...,3) + + # Apply Sim(3) transformation + R_a = np.einsum("ij,...jk->...ik", rot, R_e) # (...,3,3) + t_a = scale * np.einsum("ij,...j->...i", rot, t_e) + trans # (...,3) + + # Assemble the transformed pose + pose_a = np.zeros_like(pose_est) + pose_a[..., :3, :3] = R_a + pose_a[..., :3, 3] = t_a + pose_a[..., 3, 3] = 1.0 + + # Convert back to world-to-camera + return affine_inverse_np(pose_a) + + +def transform_points_sim3(points, rot, trans, scale, inverse=False): + """ + Sim(3) transform point cloud + points: (N, 3) + rot: (3, 3) + trans: (3,) or (1, 3) + scale: float + inverse: Whether to do inverse transform (ref->est) + Returns: (N, 3) + """ + if not inverse: + # Forward: est -> ref + return scale * (points @ rot.T) + trans + else: + # Inverse: ref -> est + return ((points - trans) @ rot) / scale + + +def _rand_rot(): + u1, u2, u3 = np.random.rand(3) + q = np.array( + [ + np.sqrt(1 - u1) * np.sin(2 * np.math.pi * u2), + np.sqrt(1 - u1) * np.cos(2 * np.math.pi * u2), + np.sqrt(u1) * np.sin(2 * np.math.pi * u3), + np.sqrt(u1) * np.cos(2 * np.math.pi * u3), + ] + ) + w, x, y, z = q + return np.array( + [ + [1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)], + [2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)], + [2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)], + ] + ) + + +def _rand_pose(): + R, t = _rand_rot(), np.random.randn(3) + P = np.eye(4) + P[:3, :3] = R + P[:3, 3] = t + return P + + +if __name__ == "__main__": + np.random.seed(42) + # 1. Randomly generate reference trajectory and Sim(3) + N = 8 + pose_ref = np.stack([_rand_pose() for _ in range(N)]) # (N,4,4) cam→world + rot_gt = _rand_rot() + scale_gt = 2.3 + trans_gt = np.random.randn(3) + # 2. Generate estimated trajectory (apply Sim(3)) + pose_est = np.zeros_like(pose_ref) + for i in range(N): + R = pose_ref[i][:3, :3] + t = pose_ref[i][:3, 3] + pose_est[i][:3, :3] = rot_gt @ R + pose_est[i][:3, 3] = scale_gt * (rot_gt @ t) + trans_gt + pose_est[i][3, 3] = 1.0 + # 3. Get extrinsics (world->cam) + ext_ref = affine_inverse_np(pose_ref) + ext_est = affine_inverse_np(pose_est) + # 4. Use umeyama alignment, estimate Sim(3) + r_est, t_est, s_est = align_poses_umeyama(ext_ref, ext_est) + print("GT scale:", scale_gt, "Estimated:", s_est) + print("GT trans:", trans_gt, "Estimated:", t_est) + print("GT rot:\n", rot_gt, "\nEstimated:\n", r_est) + # 5. Random point cloud, in ref frame + num_points = 100 + points_ref = np.random.randn(num_points, 3) + # 6. Use GT Sim(3) inverse transform to est frame + points_est = transform_points_sim3(points_ref, rot_gt, trans_gt, scale_gt, inverse=True) + # 7. Use estimated Sim(3) forward transform back to ref frame + points_ref_recovered = transform_points_sim3(points_est, r_est, t_est, s_est, inverse=False) + # 8. Check error + err = np.abs(points_ref_recovered - points_ref) + print("Point cloud sim3 transform error (mean abs):", err.mean()) + print("Point cloud sim3 transform error (max abs):", err.max()) + assert err.mean() < 1e-6, "Mean sim3 transform error too large!" + assert err.max() < 1e-5, "Max sim3 transform error too large!" + print("Sim(3) point cloud transform & alignment test passed!") diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/ray_utils.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/ray_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..6244dc40089a7bfda7889ddc153d48c44f717da7 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/ray_utils.py @@ -0,0 +1,523 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import torch +from einops import repeat +from .geometry import unproject_depth + + +def compute_optimal_rotation_intrinsics_batch( + rays_origin, rays_target, z_threshold=1e-4, reproj_threshold=0.2, weights=None, + n_sample = None, + n_iter=100, + num_sample_for_ransac=8, + rand_sample_iters_idx=None, +): + """ + Args: + rays_origin (torch.Tensor): (B, N, 3) + rays_target (torch.Tensor): (B, N, 3) + z_threshold (float): Threshold for z value to be considered valid. + + Returns: + R (torch.tensor): (3, 3) + focal_length (torch.tensor): (2,) + principal_point (torch.tensor): (2,) + """ + device = rays_origin.device + B, N, _ = rays_origin.shape + z_mask = torch.logical_and( + torch.abs(rays_target[:, :, 2]) > z_threshold, torch.abs(rays_origin[:, :, 2]) > z_threshold + ) # (B, N, 1) + rays_origin = rays_origin.clone() + rays_target = rays_target.clone() + rays_origin[:, :, 0][z_mask] /= rays_origin[:, :, 2][z_mask] + rays_origin[:, :, 1][z_mask] /= rays_origin[:, :, 2][z_mask] + rays_target[:, :, 0][z_mask] /= rays_target[:, :, 2][z_mask] + rays_target[:, :, 1][z_mask] /= rays_target[:, :, 2][z_mask] + + rays_origin = rays_origin[:, :, :2] + rays_target = rays_target[:, :, :2] + assert weights is not None, "weights must be provided" + weights[~z_mask] = 0 + + A_list = [] + max_chunk_size = 2 + for i in range(0, rays_origin.shape[0], max_chunk_size): + A = ransac_find_homography_weighted_fast_batch( + rays_origin[i:i+max_chunk_size], + rays_target[i:i+max_chunk_size], + weights[i:i+max_chunk_size], + n_iter=n_iter, + n_sample = n_sample, + num_sample_for_ransac=num_sample_for_ransac, + reproj_threshold=reproj_threshold, + rand_sample_iters_idx=rand_sample_iters_idx, + max_inlier_num=8000, + ) + A = A.to(device) + A_need_inv_mask = torch.linalg.det(A) < 0 + A[A_need_inv_mask] = -A[A_need_inv_mask] + A_list.append(A) + + A = torch.cat(A_list, dim=0) + + R_list = [] + f_list = [] + pp_list = [] + for i in range(A.shape[0]): + R, L = ql_decomposition(A[i]) + L = L / L[2][2] + + f = torch.stack((L[0][0], L[1][1])) + pp = torch.stack((L[2][0], L[2][1])) + R_list.append(R) + f_list.append(f) + pp_list.append(pp) + + R = torch.stack(R_list) + f = torch.stack(f_list) + pp = torch.stack(pp_list) + + return R, f, pp + + +# https://www.reddit.com/r/learnmath/comments/v1crd7/linear_algebra_qr_to_ql_decomposition/ +def ql_decomposition(A): + P = torch.tensor([[0, 0, 1], [0, 1, 0], [1, 0, 0]], device=A.device).float() + A_tilde = torch.matmul(A, P) + Q_tilde, R_tilde = torch.linalg.qr(A_tilde) + Q = torch.matmul(Q_tilde, P) + L = torch.matmul(torch.matmul(P, R_tilde), P) + d = torch.diag(L) + Q[:, 0] *= torch.sign(d[0]) + Q[:, 1] *= torch.sign(d[1]) + Q[:, 2] *= torch.sign(d[2]) + L[0] *= torch.sign(d[0]) + L[1] *= torch.sign(d[1]) + L[2] *= torch.sign(d[2]) + return Q, L + +def find_homography_least_squares_weighted_torch(src_pts, dst_pts, confident_weight): + """ + src_pts: (N,2) source points (torch.Tensor, float32/float64) + dst_pts: (N,2) target points (torch.Tensor, float32/float64) + confident_weight: (N,) weights (torch.Tensor) + Returns: (3,3) homography matrix H (torch.Tensor) + """ + assert src_pts.shape == dst_pts.shape + N = src_pts.shape[0] + if N < 4: + raise ValueError("At least 4 points are required to compute homography.") + assert confident_weight.shape == (N,) + + w = confident_weight.sqrt().unsqueeze(1) # (N,1) + + x = src_pts[:, 0:1] # (N,1) + y = src_pts[:, 1:2] # (N,1) + u = dst_pts[:, 0:1] + v = dst_pts[:, 1:2] + + zeros = torch.zeros_like(x) + + # Construct A matrix (2N, 9) + A1 = torch.cat([-x * w, -y * w, -w, zeros, zeros, zeros, x * u * w, y * u * w, u * w], dim=1) + A2 = torch.cat([zeros, zeros, zeros, -x * w, -y * w, -w, x * v * w, y * v * w, v * w], dim=1) + A = torch.cat([A1, A2], dim=0) # (2N, 9) + + # SVD + # Note: torch.linalg.svd returns U, S, Vh, where Vh is the transpose of V + _, _, Vh = torch.linalg.svd(A) + H = Vh[-1].reshape(3, 3) + H = H / H[-1, -1] + return H + + +def ransac_find_homography_weighted( + src_pts, + dst_pts, + confident_weight, + n_iter=100, + sample_ratio=0.2, + reproj_threshold=3.0, + num_sample_for_ransac=16, + random_seed=None, +): + """ + RANSAC version of weighted Homography estimation. + Sample 4 points from the top 50% weighted points each time. + reproj_threshold: points with reprojection error less than this value are inliers + Returns: best_H + """ + if random_seed is not None: + torch.manual_seed(random_seed) + N = src_pts.shape[0] + assert N >= 4 + # 1. Select top 50% weighted points + sorted_idx = torch.argsort(confident_weight, descending=True) + n_sample = max(num_sample_for_ransac, int(N * sample_ratio)) + candidate_idx = sorted_idx[:n_sample] + best_inlier_mask = None + best_score = 0 + for _ in range(n_iter): + # 2. Randomly sample 4 points + idx = candidate_idx[torch.randperm(n_sample)[:num_sample_for_ransac]] + # 3. Compute Homography + try: + H = find_homography_least_squares_weighted_torch( + src_pts[idx], dst_pts[idx], confident_weight[idx] + ) + except Exception: + H = torch.eye(3, dtype=src_pts.dtype, device=src_pts.device) + # 4. Compute reprojection error for all points + src_homo = torch.cat( + [src_pts, torch.ones(N, 1, dtype=src_pts.dtype, device=src_pts.device)], dim=1 + ) + proj = (H @ src_homo.T).T + proj = proj[:, :2] / proj[:, 2:3] + error = ((proj - dst_pts) ** 2).sum(dim=1).sqrt() # Euclidean distance + inlier_mask = error < reproj_threshold + total_score = (inlier_mask * confident_weight).sum().item() + n_inlier = inlier_mask.sum().item() + if n_inlier < 4: + continue # At least 4 inliers required for fitting + + if total_score > best_score: + best_score = total_score + best_inlier_mask = inlier_mask + + # 5. Refit Homography using inliers + H_inlier = find_homography_least_squares_weighted_torch( + src_pts[best_inlier_mask], dst_pts[best_inlier_mask], confident_weight[best_inlier_mask] + ) + + return H_inlier + + +def find_homography_least_squares_weighted_torch_batch( + src_pts_batch, dst_pts_batch, confident_weight_batch +): + """ + Batch version of weighted least squares Homography + src_pts_batch: (B, K, 2) + dst_pts_batch: (B, K, 2) + confident_weight_batch: (B, K) + Returns: (B, 3, 3) + """ + B, K, _ = src_pts_batch.shape + w = confident_weight_batch.sqrt().unsqueeze(2) # (B,K,1) + x = src_pts_batch[:, :, 0:1] + y = src_pts_batch[:, :, 1:2] + u = dst_pts_batch[:, :, 0:1] + v = dst_pts_batch[:, :, 1:2] + zeros = torch.zeros_like(x) + A1 = torch.cat([-x * w, -y * w, -w, zeros, zeros, zeros, x * u * w, y * u * w, u * w], dim=2) + A2 = torch.cat([zeros, zeros, zeros, -x * w, -y * w, -w, x * v * w, y * v * w, v * w], dim=2) + A = torch.cat([A1, A2], dim=1) # (B, 2K, 9) + # SVD: torch.linalg.svd supports batch + _, _, Vh = torch.linalg.svd(A) + H = Vh[:, -1].reshape(B, 3, 3) + H = H / H[:, 2:3, 2:3] + return H + + +def ransac_find_homography_weighted_fast( + src_pts, + dst_pts, + confident_weight, + n_sample, + n_iter=100, + reproj_threshold=3.0, + num_sample_for_ransac=8, + random_seed=None, + rand_sample_iters_idx=None, +): + """ + Batch version of RANSAC weighted Homography estimation. + Returns: H_inlier + """ + if random_seed is not None: + torch.manual_seed(random_seed) + N = src_pts.shape[0] + device = src_pts.device + assert N >= 4 + # 1. Select top weighted points by sample_ratio + sorted_idx = torch.argsort(confident_weight, descending=True) + candidate_idx = sorted_idx[:n_sample] # (n_sample,) + if rand_sample_iters_idx is None: + rand_sample_iters_idx = torch.stack( + [torch.randperm(n_sample, device=device)[:num_sample_for_ransac] for _ in range(n_iter)], + dim=0, + ) # (n_iter, num_sample_for_ransac) + # 2. Generate all sampling groups at once + # shape: (n_iter, num_sample_for_ransac) + rand_idx = candidate_idx[rand_sample_iters_idx] # (n_iter, num_sample_for_ransac) + # 3. Construct batch input + src_pts_batch = src_pts[rand_idx] # (n_iter, num_sample_for_ransac, 2) + dst_pts_batch = dst_pts[rand_idx] # (n_iter, num_sample_for_ransac, 2) + confident_weight_batch = confident_weight[rand_idx] # (n_iter, num_sample_for_ransac) + # 4. Batch fit Homography + H_batch = find_homography_least_squares_weighted_torch_batch( + src_pts_batch, dst_pts_batch, confident_weight_batch + ) # (n_iter, 3, 3) + # 5. Batch evaluate inliers for all H + src_homo = torch.cat( + [src_pts, torch.ones(N, 1, dtype=src_pts.dtype, device=src_pts.device)], dim=1 + ) # (N,3) + src_homo_expand = src_homo.unsqueeze(0).expand(n_iter, N, 3) # (n_iter, N, 3) + dst_pts_expand = dst_pts.unsqueeze(0).expand(n_iter, N, 2) # (n_iter, N, 2) + confident_weight_expand = confident_weight.unsqueeze(0).expand(n_iter, N) # (n_iter, N) + # H_batch: (n_iter, 3, 3) + proj = torch.bmm(src_homo_expand, H_batch.transpose(1, 2)) # (n_iter, N, 3) + proj_xy = proj[:, :, :2] / proj[:, :, 2:3] # (n_iter, N, 2) + error = ((proj_xy - dst_pts_expand) ** 2).sum(dim=2).sqrt() # (n_iter, N) + inlier_mask = error < reproj_threshold # (n_iter, N) + total_score = (inlier_mask * confident_weight_expand).sum(dim=1) # (n_iter,) + # 6. Select the sampling group with the highest score + best_idx = torch.argmax(total_score) + best_inlier_mask = inlier_mask[best_idx] # (N,) + inlier_src_pts = src_pts[best_inlier_mask] + inlier_dst_pts = dst_pts[best_inlier_mask] + inlier_confident_weight = confident_weight[best_inlier_mask] + + max_inlier_num = 10000 + sorted_idx = torch.argsort(inlier_confident_weight, descending=True) + + # method 1: sort according to confident_weight, and only keep max_inlier_num pts + # sorted_idx = sorted_idx[:max_inlier_num] + + # method 2: random choose max_inlier_num pts + sorted_idx = sorted_idx[torch.randperm(len(sorted_idx))[:max_inlier_num]] + + inlier_src_pts = inlier_src_pts[sorted_idx] + inlier_dst_pts = inlier_dst_pts[sorted_idx] + inlier_confident_weight = inlier_confident_weight[sorted_idx] + # 7. Refit Homography using inliers + H_inlier = find_homography_least_squares_weighted_torch( + inlier_src_pts, inlier_dst_pts, inlier_confident_weight + ) + return H_inlier + + +def ransac_find_homography_weighted_fast_batch( + src_pts, # (B, N, 3) + dst_pts, # (B, N, 2) + confident_weight, # (B, N) + n_sample, + n_iter=100, + reproj_threshold=3.0, + num_sample_for_ransac=8, + max_inlier_num=10000, + random_seed=None, + rand_sample_iters_idx=None, +): + """ + Batch version of RANSAC weighted Homography estimation (supports batch). + Input: + src_pts: (B, N, 2) + dst_pts: (B, N, 2) + confident_weight: (B, N) + Returns: + H_inlier: (B, 3, 3) + """ + if random_seed is not None: + torch.manual_seed(random_seed) + B, N, _ = src_pts.shape + assert N >= 4 + + device = src_pts.device + + # 1. Select top weighted points by sample_ratio + sorted_idx = torch.argsort(confident_weight, descending=True, dim=1) # (B, N) + candidate_idx = sorted_idx[:, :n_sample] # (B, n_sample) + + # 2. Generate all sampling groups at once + # rand_idx: (B, n_iter, num_sample_for_ransac) + if rand_sample_iters_idx is None: + rand_sample_iters_idx = torch.stack( + [torch.randperm(n_sample, device=device)[:num_sample_for_ransac] for _ in range(n_iter)], + dim=0, + ) # (n_iter, num_sample_for_ransac) + + rand_idx = candidate_idx[:, rand_sample_iters_idx] # (B, n_iter, num_sample_for_ransac) + + # 3. Construct batch input + # Indexing method below: (B, n_iter, num_sample_for_ransac, ...) + b_idx = torch.arange(B, device=device).view(B, 1, 1).expand(B, n_iter, num_sample_for_ransac) + src_pts_batch = src_pts[b_idx, rand_idx] # (B, n_iter, num_sample_for_ransac, 2) + dst_pts_batch = dst_pts[b_idx, rand_idx] # (B, n_iter, num_sample_for_ransac, 2) + confident_weight_batch = confident_weight[b_idx, rand_idx] # (B, n_iter, num_sample_for_ransac) + + # 4. Batch fit Homography + # Need to implement batch version that supports (B, n_iter, num_sample_for_ransac, ...) input + # Output H_batch: (B, n_iter, 3, 3) + cB, cN = src_pts_batch.shape[:2] + H_batch = find_homography_least_squares_weighted_torch_batch( + src_pts_batch.flatten(0, 1), dst_pts_batch.flatten(0, 1), confident_weight_batch.flatten(0, 1) + ) # (B, n_iter, 3, 3) + H_batch = H_batch.unflatten(0, (cB, cN)) + + # 5. Batch evaluate inliers for all H + src_homo = torch.cat( + [src_pts, torch.ones(B, N, 1, dtype=src_pts.dtype, device=src_pts.device)], dim=2 + ) # (B, N, 3) + src_homo_expand = src_homo.unsqueeze(1).expand(B, n_iter, N, 3) # (B, n_iter, N, 3) + dst_pts_expand = dst_pts.unsqueeze(1).expand(B, n_iter, N, 2) # (B, n_iter, N, 2) + confident_weight_expand = confident_weight.unsqueeze(1).expand(B, n_iter, N) # (B, n_iter, N) + + # H_batch: (B, n_iter, 3, 3) + # Need to reshape H_batch to (B*n_iter, 3, 3), src_homo_expand to (B*n_iter, N, 3) + H_batch_flat = H_batch.reshape(-1, 3, 3) + src_homo_expand_flat = src_homo_expand.reshape(-1, N, 3) + proj = torch.bmm(src_homo_expand_flat, H_batch_flat.transpose(1, 2)) # (B*n_iter, N, 3) + proj_xy = proj[:, :, :2] / proj[:, :, 2:3] # (B*n_iter, N, 2) + proj_xy = proj_xy.reshape(B, n_iter, N, 2) + error = ((proj_xy - dst_pts_expand) ** 2).sum(dim=3).sqrt() # (B, n_iter, N) + inlier_mask = error < reproj_threshold # (B, n_iter, N) + total_score = (inlier_mask * confident_weight_expand).sum(dim=2) # (B, n_iter) + + # 6. Select the sampling group with the highest score + best_idx = torch.argmax(total_score, dim=1) # (B,) + best_inlier_mask = inlier_mask[torch.arange(B, device=device), best_idx] # (B, N) + + # 7. Refit Homography using inliers + H_inlier_list = [] + for b in range(B): + mask = best_inlier_mask[b] + inlier_src_pts = src_pts[b][mask] # (?, 3) + inlier_dst_pts = dst_pts[b][mask] # (?, 2) + inlier_confident_weight = confident_weight[b][mask] # (?) + + sorted_idx = torch.argsort(inlier_confident_weight, descending=True) + # # method 1: sort according to confident_weight, and only keep max_inlier_num pts + # sorted_idx = sorted_idx[:max_inlier_num] + # method 2: random choose max_inlier_num pts + if len(sorted_idx) > max_inlier_num: + # random choose from first 95% confident pts + keep_len = max(int(len(sorted_idx) * 0.95), max_inlier_num) + sorted_idx = sorted_idx[:keep_len] + perm = torch.randperm(len(sorted_idx), device=device)[:max_inlier_num] + sorted_idx = sorted_idx[perm] + inlier_src_pts = inlier_src_pts[sorted_idx] + inlier_dst_pts = inlier_dst_pts[sorted_idx] + inlier_confident_weight = inlier_confident_weight[sorted_idx] + + H_inlier = find_homography_least_squares_weighted_torch( + inlier_src_pts, inlier_dst_pts, inlier_confident_weight + ) # (3, 3) + H_inlier_list.append(H_inlier) + H_inlier = torch.stack(H_inlier_list, dim=0) # (B, 3, 3) + return H_inlier + +def get_params_for_ransac(N, device): + n_iter=100 + sample_ratio=0.3 + num_sample_for_ransac=8 + n_sample = max(num_sample_for_ransac, int(N * sample_ratio)) + rand_sample_iters_idx = torch.stack( + [torch.randperm(n_sample, device=device)[:num_sample_for_ransac] for _ in range(n_iter)], + dim=0, + ) # (n_iter, num_sample_for_ransac) + return n_iter, num_sample_for_ransac, n_sample, rand_sample_iters_idx + + +def camray_to_caminfo(camray, confidence=None, reproj_threshold=0.2, training=False): + """ + Args: + camray: (B, S, num_patches_y, num_patches_x, 6) + confidence: (B, S, num_patches_y, num_patches_x) + Returns: + R: (B, S, 3, 3) + T: (B, S, 3) + focal_lengths: (B, S, 2) + principal_points: (B, S, 2) + """ + if confidence is None: + confidence = torch.ones_like(camray[:, :, :, :, 0]) + B, S, num_patches_y, num_patches_x, _ = camray.shape + # identity K, assume imw=imh=2.0 + I_K = torch.eye(3, dtype=camray.dtype, device=camray.device) + I_K[0, 2] = 1.0 + I_K[1, 2] = 1.0 + # repeat I_K to match camray + I_K = I_K.unsqueeze(0).unsqueeze(0).expand(B, S, -1, -1) + + cam_plane_depth = torch.ones( + B, S, num_patches_y, num_patches_x, 1, dtype=camray.dtype, device=camray.device + ) + I_cam_plane_unproj = unproject_depth( + cam_plane_depth, + I_K, + c2w=None, + ixt_normalized=True, + num_patches_x=num_patches_x, + num_patches_y=num_patches_y, + ) # (B, S, num_patches_y, num_patches_x, 3) + + camray = camray.flatten(0, 1).flatten(1, 2) # (B*S, num_patches_y*num_patches_x, 6) + I_cam_plane_unproj = I_cam_plane_unproj.flatten(0, 1).flatten( + 1, 2 + ) # (B*S, num_patches_y*num_patches_x, 3) + confidence = confidence.flatten(0, 1).flatten(1, 2) # (B*S, num_patches_y*num_patches_x) + + # Compute optimal rotation to align rays + N = camray.shape[-2] + device = camray.device + n_iter, num_sample_for_ransac, n_sample, rand_sample_iters_idx = get_params_for_ransac(N, device) + + # Use batch processing (confidence is guaranteed to be not None at this point) + if training: + camray = camray.clone().detach() + I_cam_plane_unproj = I_cam_plane_unproj.clone().detach() + confidence = confidence.clone().detach() + R, focal_lengths, principal_points = compute_optimal_rotation_intrinsics_batch( + I_cam_plane_unproj, + camray[:, :, :3], + reproj_threshold=reproj_threshold, + weights=confidence, + n_sample = n_sample, + n_iter=n_iter, + num_sample_for_ransac=num_sample_for_ransac, + rand_sample_iters_idx=rand_sample_iters_idx, + ) + + T = torch.sum(camray[:, :, 3:] * confidence.unsqueeze(-1), dim=1) / torch.sum( + confidence, dim=-1, keepdim=True + ) + + R = R.reshape(B, S, 3, 3) + T = T.reshape(B, S, 3) + focal_lengths = focal_lengths.reshape(B, S, 2) + principal_points = principal_points.reshape(B, S, 2) + + return R, T, 1.0 / focal_lengths, principal_points + 1.0 + +def get_extrinsic_from_camray(camray, conf, patch_size_y, patch_size_x, training=False): + pred_R, pred_T, pred_focal_lengths, pred_principal_points = camray_to_caminfo( + camray, confidence=conf.squeeze(-1), training=training + ) + + pred_extrinsic = torch.cat( + [ + torch.cat([pred_R, pred_T.unsqueeze(-1)], dim=-1), + repeat( + torch.tensor([0, 0, 0, 1], dtype=pred_R.dtype, device=pred_R.device), + "c -> b s 1 c", + b=pred_R.shape[0], + s=pred_R.shape[1], + ), + ], + dim=-2, + ) # B, S, 4, 4 + return pred_extrinsic, pred_focal_lengths, pred_principal_points \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/read_write_model.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/read_write_model.py new file mode 100644 index 0000000000000000000000000000000000000000..4b4cf197f609665e46f14e6b3e8b6657efc5660c --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/read_write_model.py @@ -0,0 +1,585 @@ +# Copyright (c), ETH Zurich and UNC Chapel Hill. +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# All rights reserved. +# +# This file has been modified by ByteDance Ltd. and/or its affiliates. on 11/05/2025 +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# * Neither the name of ETH Zurich and UNC Chapel Hill nor the names of +# its contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + + +import argparse +import collections +import os +import struct +import numpy as np + +CameraModel = collections.namedtuple("CameraModel", ["model_id", "model_name", "num_params"]) +Camera = collections.namedtuple("Camera", ["id", "model", "width", "height", "params"]) +BaseImage = collections.namedtuple( + "Image", ["id", "qvec", "tvec", "camera_id", "name", "xys", "point3D_ids"] +) +Point3D = collections.namedtuple( + "Point3D", ["id", "xyz", "rgb", "error", "image_ids", "point2D_idxs"] +) + + +class Image(BaseImage): + def qvec2rotmat(self): + return qvec2rotmat(self.qvec) + + +CAMERA_MODELS = { + CameraModel(model_id=0, model_name="SIMPLE_PINHOLE", num_params=3), + CameraModel(model_id=1, model_name="PINHOLE", num_params=4), + CameraModel(model_id=2, model_name="SIMPLE_RADIAL", num_params=4), + CameraModel(model_id=3, model_name="RADIAL", num_params=5), + CameraModel(model_id=4, model_name="OPENCV", num_params=8), + CameraModel(model_id=5, model_name="OPENCV_FISHEYE", num_params=8), + CameraModel(model_id=6, model_name="FULL_OPENCV", num_params=12), + CameraModel(model_id=7, model_name="FOV", num_params=5), + CameraModel(model_id=8, model_name="SIMPLE_RADIAL_FISHEYE", num_params=4), + CameraModel(model_id=9, model_name="RADIAL_FISHEYE", num_params=5), + CameraModel(model_id=10, model_name="THIN_PRISM_FISHEYE", num_params=12), +} +CAMERA_MODEL_IDS = {camera_model.model_id: camera_model for camera_model in CAMERA_MODELS} +CAMERA_MODEL_NAMES = {camera_model.model_name: camera_model for camera_model in CAMERA_MODELS} + + +def read_next_bytes(fid, num_bytes, format_char_sequence, endian_character="<"): + """Read and unpack the next bytes from a binary file. + :param fid: + :param num_bytes: Sum of combination of {2, 4, 8}, e.g. 2, 6, 16, 30, etc. + :param format_char_sequence: List of {c, e, f, d, h, H, i, I, l, L, q, Q}. + :param endian_character: Any of {@, =, <, >, !} + :return: Tuple of read and unpacked values. + """ + data = fid.read(num_bytes) + return struct.unpack(endian_character + format_char_sequence, data) + + +def write_next_bytes(fid, data, format_char_sequence, endian_character="<"): + """pack and write to a binary file. + :param fid: + :param data: data to send, if multiple elements are sent at the same time, + they should be encapsuled either in a list or a tuple + :param format_char_sequence: List of {c, e, f, d, h, H, i, I, l, L, q, Q}. + should be the same length as the data list or tuple + :param endian_character: Any of {@, =, <, >, !} + """ + if isinstance(data, (list, tuple)): + bytes = struct.pack(endian_character + format_char_sequence, *data) + else: + bytes = struct.pack(endian_character + format_char_sequence, data) + fid.write(bytes) + + +def read_cameras_text(path): + """ + see: src/colmap/scene/reconstruction.cc + void Reconstruction::WriteCamerasText(const std::string& path) + void Reconstruction::ReadCamerasText(const std::string& path) + """ + cameras = {} + with open(path) as fid: + while True: + line = fid.readline() + if not line: + break + line = line.strip() + if len(line) > 0 and line[0] != "#": + elems = line.split() + camera_id = int(elems[0]) + model = elems[1] + width = int(elems[2]) + height = int(elems[3]) + params = np.array(tuple(map(float, elems[4:]))) + cameras[camera_id] = Camera( + id=camera_id, + model=model, + width=width, + height=height, + params=params, + ) + return cameras + + +def read_cameras_binary(path_to_model_file): + """ + see: src/colmap/scene/reconstruction.cc + void Reconstruction::WriteCamerasBinary(const std::string& path) + void Reconstruction::ReadCamerasBinary(const std::string& path) + """ + cameras = {} + with open(path_to_model_file, "rb") as fid: + num_cameras = read_next_bytes(fid, 8, "Q")[0] + for _ in range(num_cameras): + camera_properties = read_next_bytes(fid, num_bytes=24, format_char_sequence="iiQQ") + camera_id = camera_properties[0] + model_id = camera_properties[1] + model_name = CAMERA_MODEL_IDS[camera_properties[1]].model_name + width = camera_properties[2] + height = camera_properties[3] + num_params = CAMERA_MODEL_IDS[model_id].num_params + params = read_next_bytes( + fid, + num_bytes=8 * num_params, + format_char_sequence="d" * num_params, + ) + cameras[camera_id] = Camera( + id=camera_id, + model=model_name, + width=width, + height=height, + params=np.array(params), + ) + assert len(cameras) == num_cameras + return cameras + + +def write_cameras_text(cameras, path): + """ + see: src/colmap/scene/reconstruction.cc + void Reconstruction::WriteCamerasText(const std::string& path) + void Reconstruction::ReadCamerasText(const std::string& path) + """ + HEADER = ( + "# Camera list with one line of data per camera:\n" + + "# CAMERA_ID, MODEL, WIDTH, HEIGHT, PARAMS[]\n" + + f"# Number of cameras: {len(cameras)}\n" + ) + with open(path, "w") as fid: + fid.write(HEADER) + for _, cam in cameras.items(): + to_write = [cam.id, cam.model, cam.width, cam.height, *cam.params] + line = " ".join([str(elem) for elem in to_write]) + fid.write(line + "\n") + + +def write_cameras_binary(cameras, path_to_model_file): + """ + see: src/colmap/scene/reconstruction.cc + void Reconstruction::WriteCamerasBinary(const std::string& path) + void Reconstruction::ReadCamerasBinary(const std::string& path) + """ + with open(path_to_model_file, "wb") as fid: + write_next_bytes(fid, len(cameras), "Q") + for _, cam in cameras.items(): + model_id = CAMERA_MODEL_NAMES[cam.model].model_id + camera_properties = [cam.id, model_id, cam.width, cam.height] + write_next_bytes(fid, camera_properties, "iiQQ") + for p in cam.params: + write_next_bytes(fid, float(p), "d") + return cameras + + +def read_images_text(path): + """ + see: src/colmap/scene/reconstruction.cc + void Reconstruction::ReadImagesText(const std::string& path) + void Reconstruction::WriteImagesText(const std::string& path) + """ + images = {} + with open(path) as fid: + while True: + line = fid.readline() + if not line: + break + line = line.strip() + if len(line) > 0 and line[0] != "#": + elems = line.split() + image_id = int(elems[0]) + qvec = np.array(tuple(map(float, elems[1:5]))) + tvec = np.array(tuple(map(float, elems[5:8]))) + camera_id = int(elems[8]) + image_name = elems[9] + elems = fid.readline().split() + xys = np.column_stack( + [ + tuple(map(float, elems[0::3])), + tuple(map(float, elems[1::3])), + ] + ) + point3D_ids = np.array(tuple(map(int, elems[2::3]))) + images[image_id] = Image( + id=image_id, + qvec=qvec, + tvec=tvec, + camera_id=camera_id, + name=image_name, + xys=xys, + point3D_ids=point3D_ids, + ) + return images + + +def read_images_binary(path_to_model_file): + """ + see: src/colmap/scene/reconstruction.cc + void Reconstruction::ReadImagesBinary(const std::string& path) + void Reconstruction::WriteImagesBinary(const std::string& path) + """ + images = {} + with open(path_to_model_file, "rb") as fid: + num_reg_images = read_next_bytes(fid, 8, "Q")[0] + for _ in range(num_reg_images): + binary_image_properties = read_next_bytes( + fid, num_bytes=64, format_char_sequence="idddddddi" + ) + image_id = binary_image_properties[0] + qvec = np.array(binary_image_properties[1:5]) + tvec = np.array(binary_image_properties[5:8]) + camera_id = binary_image_properties[8] + binary_image_name = b"" + current_char = read_next_bytes(fid, 1, "c")[0] + while current_char != b"\x00": # look for the ASCII 0 entry + binary_image_name += current_char + current_char = read_next_bytes(fid, 1, "c")[0] + image_name = binary_image_name.decode("utf-8") + num_points2D = read_next_bytes(fid, num_bytes=8, format_char_sequence="Q")[0] + x_y_id_s = read_next_bytes( + fid, + num_bytes=24 * num_points2D, + format_char_sequence="ddq" * num_points2D, + ) + xys = np.column_stack( + [ + tuple(map(float, x_y_id_s[0::3])), + tuple(map(float, x_y_id_s[1::3])), + ] + ) + point3D_ids = np.array(tuple(map(int, x_y_id_s[2::3]))) + images[image_id] = Image( + id=image_id, + qvec=qvec, + tvec=tvec, + camera_id=camera_id, + name=image_name, + xys=xys, + point3D_ids=point3D_ids, + ) + return images + + +def write_images_text(images, path): + """ + see: src/colmap/scene/reconstruction.cc + void Reconstruction::ReadImagesText(const std::string& path) + void Reconstruction::WriteImagesText(const std::string& path) + """ + if len(images) == 0: + mean_observations = 0 + else: + mean_observations = sum((len(img.point3D_ids) for _, img in images.items())) / len(images) + HEADER = ( + "# Image list with two lines of data per image:\n" + + "# IMAGE_ID, QW, QX, QY, QZ, TX, TY, TZ, CAMERA_ID, NAME\n" + + "# POINTS2D[] as (X, Y, POINT3D_ID)\n" + + "# Number of images: {}, mean observations per image: {}\n".format( + len(images), mean_observations + ) + ) + + with open(path, "w") as fid: + fid.write(HEADER) + for _, img in images.items(): + image_header = [ + img.id, + *img.qvec, + *img.tvec, + img.camera_id, + img.name, + ] + first_line = " ".join(map(str, image_header)) + fid.write(first_line + "\n") + + points_strings = [] + for xy, point3D_id in zip(img.xys, img.point3D_ids): + points_strings.append(" ".join(map(str, [*xy, point3D_id]))) + fid.write(" ".join(points_strings) + "\n") + + +def write_images_binary(images, path_to_model_file): + """ + see: src/colmap/scene/reconstruction.cc + void Reconstruction::ReadImagesBinary(const std::string& path) + void Reconstruction::WriteImagesBinary(const std::string& path) + """ + with open(path_to_model_file, "wb") as fid: + write_next_bytes(fid, len(images), "Q") + for _, img in images.items(): + write_next_bytes(fid, img.id, "i") + write_next_bytes(fid, img.qvec.tolist(), "dddd") + write_next_bytes(fid, img.tvec.tolist(), "ddd") + write_next_bytes(fid, img.camera_id, "i") + for char in img.name: + write_next_bytes(fid, char.encode("utf-8"), "c") + write_next_bytes(fid, b"\x00", "c") + write_next_bytes(fid, len(img.point3D_ids), "Q") + for xy, p3d_id in zip(img.xys, img.point3D_ids): + write_next_bytes(fid, [*xy, p3d_id], "ddq") + + +def read_points3D_text(path): + """ + see: src/colmap/scene/reconstruction.cc + void Reconstruction::ReadPoints3DText(const std::string& path) + void Reconstruction::WritePoints3DText(const std::string& path) + """ + points3D = {} + with open(path) as fid: + while True: + line = fid.readline() + if not line: + break + line = line.strip() + if len(line) > 0 and line[0] != "#": + elems = line.split() + point3D_id = int(elems[0]) + xyz = np.array(tuple(map(float, elems[1:4]))) + rgb = np.array(tuple(map(int, elems[4:7]))) + error = float(elems[7]) + image_ids = np.array(tuple(map(int, elems[8::2]))) + point2D_idxs = np.array(tuple(map(int, elems[9::2]))) + points3D[point3D_id] = Point3D( + id=point3D_id, + xyz=xyz, + rgb=rgb, + error=error, + image_ids=image_ids, + point2D_idxs=point2D_idxs, + ) + return points3D + + +def read_points3D_binary(path_to_model_file): + """ + see: src/colmap/scene/reconstruction.cc + void Reconstruction::ReadPoints3DBinary(const std::string& path) + void Reconstruction::WritePoints3DBinary(const std::string& path) + """ + points3D = {} + with open(path_to_model_file, "rb") as fid: + num_points = read_next_bytes(fid, 8, "Q")[0] + for _ in range(num_points): + binary_point_line_properties = read_next_bytes( + fid, num_bytes=43, format_char_sequence="QdddBBBd" + ) + point3D_id = binary_point_line_properties[0] + xyz = np.array(binary_point_line_properties[1:4]) + rgb = np.array(binary_point_line_properties[4:7]) + error = np.array(binary_point_line_properties[7]) + track_length = read_next_bytes(fid, num_bytes=8, format_char_sequence="Q")[0] + track_elems = read_next_bytes( + fid, + num_bytes=8 * track_length, + format_char_sequence="ii" * track_length, + ) + image_ids = np.array(tuple(map(int, track_elems[0::2]))) + point2D_idxs = np.array(tuple(map(int, track_elems[1::2]))) + points3D[point3D_id] = Point3D( + id=point3D_id, + xyz=xyz, + rgb=rgb, + error=error, + image_ids=image_ids, + point2D_idxs=point2D_idxs, + ) + return points3D + + +def write_points3D_text(points3D, path): + """ + see: src/colmap/scene/reconstruction.cc + void Reconstruction::ReadPoints3DText(const std::string& path) + void Reconstruction::WritePoints3DText(const std::string& path) + """ + if len(points3D) == 0: + mean_track_length = 0 + else: + mean_track_length = sum((len(pt.image_ids) for _, pt in points3D.items())) / len(points3D) + HEADER = ( + "# 3D point list with one line of data per point:\n" + + "# POINT3D_ID, X, Y, Z, R, G, B, ERROR, TRACK[] as (IMAGE_ID, POINT2D_IDX)\n" + + "# Number of points: {}, mean track length: {}\n".format( + len(points3D), mean_track_length + ) + ) + + with open(path, "w") as fid: + fid.write(HEADER) + for _, pt in points3D.items(): + point_header = [pt.id, *pt.xyz, *pt.rgb, pt.error] + fid.write(" ".join(map(str, point_header)) + " ") + track_strings = [] + for image_id, point2D in zip(pt.image_ids, pt.point2D_idxs): + track_strings.append(" ".join(map(str, [image_id, point2D]))) + fid.write(" ".join(track_strings) + "\n") + + +def write_points3D_binary(points3D, path_to_model_file): + """ + see: src/colmap/scene/reconstruction.cc + void Reconstruction::ReadPoints3DBinary(const std::string& path) + void Reconstruction::WritePoints3DBinary(const std::string& path) + """ + with open(path_to_model_file, "wb") as fid: + write_next_bytes(fid, len(points3D), "Q") + for _, pt in points3D.items(): + write_next_bytes(fid, pt.id, "Q") + write_next_bytes(fid, pt.xyz.tolist(), "ddd") + write_next_bytes(fid, pt.rgb.tolist(), "BBB") + write_next_bytes(fid, pt.error, "d") + track_length = pt.image_ids.shape[0] + write_next_bytes(fid, track_length, "Q") + for image_id, point2D_id in zip(pt.image_ids, pt.point2D_idxs): + write_next_bytes(fid, [image_id, point2D_id], "ii") + + +def detect_model_format(path, ext): + if ( + os.path.isfile(os.path.join(path, "cameras" + ext)) + and os.path.isfile(os.path.join(path, "images" + ext)) + and os.path.isfile(os.path.join(path, "points3D" + ext)) + ): + print("Detected model format: '" + ext + "'") + return True + + return False + + +def read_model(path, ext=""): + # try to detect the extension automatically + if ext == "": + if detect_model_format(path, ".bin"): + ext = ".bin" + elif detect_model_format(path, ".txt"): + ext = ".txt" + else: + print("Provide model format: '.bin' or '.txt'") + return + + if ext == ".txt": + cameras = read_cameras_text(os.path.join(path, "cameras" + ext)) + images = read_images_text(os.path.join(path, "images" + ext)) + points3D = read_points3D_text(os.path.join(path, "points3D") + ext) + else: + cameras = read_cameras_binary(os.path.join(path, "cameras" + ext)) + images = read_images_binary(os.path.join(path, "images" + ext)) + points3D = read_points3D_binary(os.path.join(path, "points3D") + ext) + return cameras, images, points3D + + +def write_model(cameras, images, points3D, path, ext=".bin"): + if ext == ".txt": + write_cameras_text(cameras, os.path.join(path, "cameras" + ext)) + write_images_text(images, os.path.join(path, "images" + ext)) + write_points3D_text(points3D, os.path.join(path, "points3D") + ext) + else: + write_cameras_binary(cameras, os.path.join(path, "cameras" + ext)) + write_images_binary(images, os.path.join(path, "images" + ext)) + write_points3D_binary(points3D, os.path.join(path, "points3D") + ext) + return cameras, images, points3D + + +def qvec2rotmat(qvec): + return np.array( + [ + [ + 1 - 2 * qvec[2] ** 2 - 2 * qvec[3] ** 2, + 2 * qvec[1] * qvec[2] - 2 * qvec[0] * qvec[3], + 2 * qvec[3] * qvec[1] + 2 * qvec[0] * qvec[2], + ], + [ + 2 * qvec[1] * qvec[2] + 2 * qvec[0] * qvec[3], + 1 - 2 * qvec[1] ** 2 - 2 * qvec[3] ** 2, + 2 * qvec[2] * qvec[3] - 2 * qvec[0] * qvec[1], + ], + [ + 2 * qvec[3] * qvec[1] - 2 * qvec[0] * qvec[2], + 2 * qvec[2] * qvec[3] + 2 * qvec[0] * qvec[1], + 1 - 2 * qvec[1] ** 2 - 2 * qvec[2] ** 2, + ], + ] + ) + + +def rotmat2qvec(R): + Rxx, Ryx, Rzx, Rxy, Ryy, Rzy, Rxz, Ryz, Rzz = R.flat + K = ( + np.array( + [ + [Rxx - Ryy - Rzz, 0, 0, 0], + [Ryx + Rxy, Ryy - Rxx - Rzz, 0, 0], + [Rzx + Rxz, Rzy + Ryz, Rzz - Rxx - Ryy, 0], + [Ryz - Rzy, Rzx - Rxz, Rxy - Ryx, Rxx + Ryy + Rzz], + ] + ) + / 3.0 + ) + eigvals, eigvecs = np.linalg.eigh(K) + qvec = eigvecs[[3, 0, 1, 2], np.argmax(eigvals)] + if qvec[0] < 0: + qvec *= -1 + return qvec + + +def main(): + parser = argparse.ArgumentParser(description="Read and write COLMAP binary and text models") + parser.add_argument("--input_model", help="path to input model folder") + parser.add_argument( + "--input_format", + choices=[".bin", ".txt"], + help="input model format", + default="", + ) + parser.add_argument("--output_model", help="path to output model folder") + parser.add_argument( + "--output_format", + choices=[".bin", ".txt"], + help="output model format", + default=".txt", + ) + args = parser.parse_args() + + cameras, images, points3D = read_model(path=args.input_model, ext=args.input_format) + + print("num_cameras:", len(cameras)) + print("num_images:", len(images)) + print("num_points3D:", len(points3D)) + + if args.output_model is not None: + write_model( + cameras, + images, + points3D, + path=args.output_model, + ext=args.output_format, + ) + + +if __name__ == "__main__": + main() diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/registry.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/registry.py new file mode 100644 index 0000000000000000000000000000000000000000..7db16d525e0417110d87aa5e621b792d8bd95596 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/registry.py @@ -0,0 +1,36 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import Any +from addict import Dict + + +class Registry(Dict[str, Any]): + def __init__(self): + super().__init__() + self._map = Dict({}) + + def register(self, name=None): + def decorator(cls): + key = name or cls.__name__ + self._map[key] = cls + return cls + + return decorator + + def get(self, name): + return self._map[name] + + def all(self): + return self._map diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/sh_helpers.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/sh_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..1a1a4ca8204eb8d858351afb253e41e77dfa2f74 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/sh_helpers.py @@ -0,0 +1,88 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from math import isqrt +import torch +from einops import einsum + +try: + from e3nn.o3 import matrix_to_angles, wigner_D +except ImportError: + from depth_anything_3.utils.logger import logger + + logger.warn("Dependency 'e3nn' not found. Required for rotating the camera space SH coeff") + + +def project_to_so3_strict(M: torch.Tensor) -> torch.Tensor: + if M.shape[-2:] != (3, 3): + raise ValueError("Input must be a batch of 3x3 matrices (i.e., shape [..., 3, 3]).") + + # 1. Compute SVD + U, S, Vh = torch.linalg.svd(M) + V = Vh.mH + + # 2. Handle reflection case (det = -1) + det_U = torch.det(U) + det_V = torch.det(V) + is_reflection = (det_U * det_V) < 0 + correction_sign = torch.where( + is_reflection[..., None], + torch.tensor([1, 1, -1.0], device=M.device, dtype=M.dtype), + torch.tensor([1, 1, 1.0], device=M.device, dtype=M.dtype), + ) + correction_matrix = torch.diag_embed(correction_sign) + U_corrected = U @ correction_matrix + R_so3_initial = U_corrected @ V.transpose(-2, -1) + + # 3. Explicitly ensure determinant is 1 (or extremely close) + current_det = torch.det(R_so3_initial) + det_correction_factor = torch.pow(current_det, -1 / 3)[..., None, None] + R_so3_final = R_so3_initial * det_correction_factor + + return R_so3_final + + +def rotate_sh( + sh_coefficients: torch.Tensor, # "*#batch n" + rotations: torch.Tensor, # "*#batch 3 3" +) -> torch.Tensor: # "*batch n" + # https://github.com/graphdeco-inria/gaussian-splatting/issues/176#issuecomment-2452412653 + device = sh_coefficients.device + dtype = sh_coefficients.dtype + + *_, n = sh_coefficients.shape + + with torch.autocast(device_type=rotations.device.type, enabled=False): + rotations_float32 = rotations.to(torch.float32) + + # switch axes: yzx -> xyz + P = torch.tensor([[0, 0, 1], [1, 0, 0], [0, 1, 0]]).unsqueeze(0).to(rotations_float32) + permuted_rotations = torch.linalg.inv(P) @ rotations_float32 @ P + + # ensure rotation has det == 1 in float32 type + permuted_rotations_so3 = project_to_so3_strict(permuted_rotations) + + alpha, beta, gamma = matrix_to_angles(permuted_rotations_so3) + result = [] + for degree in range(isqrt(n)): + with torch.device(device): + sh_rotations = wigner_D(degree, alpha, -beta, gamma).type(dtype) + sh_rotated = einsum( + sh_rotations, + sh_coefficients[..., degree**2 : (degree + 1) ** 2], + "... i j, ... j -> ... i", + ) + result.append(sh_rotated) + + return torch.cat(result, dim=-1) diff --git a/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/visualize.py b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/visualize.py new file mode 100644 index 0000000000000000000000000000000000000000..8fd32bddf00e5461f674525e73653409270c0227 --- /dev/null +++ b/OVOW/engine/oneposeviagen/DA3/src/depth_anything_3/utils/visualize.py @@ -0,0 +1,120 @@ +# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import matplotlib +import numpy as np +import torch +from einops import rearrange + +from depth_anything_3.utils.logger import logger + + +def visualize_depth( + depth: np.ndarray, + depth_min=None, + depth_max=None, + percentile=2, + ret_minmax=False, + ret_type=np.uint8, + cmap="Spectral", +): + """ + Visualize a depth map using a colormap. + + Args: + depth: Input depth map array + depth_min: Minimum depth value for normalization. If None, uses percentile + depth_max: Maximum depth value for normalization. If None, uses percentile + percentile: Percentile for min/max computation if not provided + ret_minmax: Whether to return min/max depth values + ret_type: Return array type (uint8 or float) + cmap: Matplotlib colormap name to use + + Returns: + Colored depth visualization as numpy array + If ret_minmax=True, also returns depth_min and depth_max + """ + depth = depth.copy() + depth.copy() + valid_mask = depth > 0 + depth[valid_mask] = 1 / depth[valid_mask] + if depth_min is None: + if valid_mask.sum() <= 10: + depth_min = 0 + else: + depth_min = np.percentile(depth[valid_mask], percentile) + if depth_max is None: + if valid_mask.sum() <= 10: + depth_max = 0 + else: + depth_max = np.percentile(depth[valid_mask], 100 - percentile) + if depth_min == depth_max: + depth_min = depth_min - 1e-6 + depth_max = depth_max + 1e-6 + cm = matplotlib.colormaps[cmap] + depth = ((depth - depth_min) / (depth_max - depth_min)).clip(0, 1) + depth = 1 - depth + img_colored_np = cm(depth[None], bytes=False)[:, :, :, 0:3] # value from 0 to 1 + if ret_type == np.uint8: + img_colored_np = (img_colored_np[0] * 255.0).astype(np.uint8) + elif ret_type == np.float32 or ret_type == np.float64: + img_colored_np = img_colored_np[0] + else: + raise ValueError(f"Invalid return type: {ret_type}") + if ret_minmax: + return img_colored_np, depth_min, depth_max + else: + return img_colored_np + + +# GS video rendering visulization function, since it operates in Tensor space... + + +def vis_depth_map_tensor( + result: torch.Tensor, # "*batch height width" + color_map: str = "Spectral", +) -> torch.Tensor: # "*batch 3 height with" + """ + Color-map the depth map. + """ + far = result.reshape(-1)[:16_000_000].float().quantile(0.99).log().to(result) + try: + near = result[result > 0][:16_000_000].float().quantile(0.01).log().to(result) + except (RuntimeError, ValueError) as e: + logger.error(f"No valid depth values found. Reason: {e}") + near = torch.zeros_like(far) + result = result.log() + result = (result - near) / (far - near) + return apply_color_map_to_image(result, color_map) + + +def apply_color_map( + x: torch.Tensor, # " *batch" + color_map: str = "inferno", +) -> torch.Tensor: # "*batch 3" + cmap = matplotlib.cm.get_cmap(color_map) + + # Convert to NumPy so that Matplotlib color maps can be used. + mapped = cmap(x.float().detach().clip(min=0, max=1).cpu().numpy())[..., :3] + + # Convert back to the original format. + return torch.tensor(mapped, device=x.device, dtype=torch.float32) + + +def apply_color_map_to_image( + image: torch.Tensor, # "*batch height width" + color_map: str = "inferno", +) -> torch.Tensor: # "*batch 3 height with" + image = apply_color_map(image, color_map) + return rearrange(image, "... h w c -> ... c h w") diff --git a/OVOW/engine/oneposeviagen/Orientation/README.md b/OVOW/engine/oneposeviagen/Orientation/README.md new file mode 100644 index 0000000000000000000000000000000000000000..50b03ca501b0253bdeb723144433a2f098f1bbc4 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/README.md @@ -0,0 +1,191 @@ +# Orientation Matters (NeurIPS 2025) +Official repository for the paper "Orientation Matters: Making 3D Generative Models Orientation-Aligned" + +
    + +![Version](https://img.shields.io/badge/version-1.0.0-blue)   +   +   +   +   +   + +
    + +Humans intuitively perceive object shape and orientation from a single image, guided by strong priors about canonical poses. However, existing 3D generative models often produce misaligned results due to inconsistent training data, limiting their usability in downstream tasks. To address this gap, we introduce the task of orientation-aligned 3D object generation: producing 3D objects from single images with consistent orientations across categories. To facilitate this, we construct Objaverse-OA, a dataset of 14,832 orientation-aligned 3D models spanning 1,008 categories. Leveraging Objaverse-OA, we fine-tune two representative 3D generative models based on multi-view diffusion and 3D variational autoencoder frameworks to produce aligned objects that generalize well to unseen objects across various categories. Experimental results demonstrate the superiority of our method over post-hoc alignment approaches. Furthermore, we showcase downstream applications enabled by our aligned object generation, including zero-shot model-free object orientation estimation via analysis-by-synthesis and efficient arrow-based object rotation manipulation in 3D simulation systems. + +## 🔥 News +- 2025.11.25 We release the [Objaverse-OA](https://huggingface.co/datasets/Louischong/Objaverse-OA) dataset. +- 2025.7.20 We release the pre-trained models and codes of Trellis-OA, Wonder3D-OA, and orientation estimation method. +- 2025.6.25 We release the [Huggingface Demo](https://huggingface.co/spaces/Louischong/Trellis-OA)🤗 and pre-trained [model](https://huggingface.co/Louischong/Trellis-OA)🤗 of Trellis-OA. Have a try! + +### 📝 TODO List +- [x] Add Huggingface demo, inference code and pre-trained checkpoint of Trellis-OA. +- [x] Add checkpoint and inference code of Wonder3D-OA. +- [x] Add checkpoint and inference code of the orientation estimation method. +- [x] Release the Objaverse-OA dataset. +- [ ] Add code of the augmented reality application. +- [ ] Add the Blender add-on of our arrow-based manipulation. + +## Install + +Tested on NVIDIA A6000 and 3090 GPU. + +``` +# create conda environment +conda create -n orient_mat python=3.10 +conda activate orient_mat + +# install cuda +conda install cuda -c nvidia/label/cuda-11.8.0 + +# install pytorch +pip install torch==2.4.0 torchvision==0.19.0 torchaudio==2.4.0 --index-url https://download.pytorch.org/whl/cu118 + +# install xformers +pip install xformers==0.0.27.post2 --index-url https://download.pytorch.org/whl/cu118 + +# install nvdiffrast +pip install git+https://github.com/NVlabs/nvdiffrast.git +``` + +### Install dependencies for 3D generation + + +``` +# install dependencies for trellis_oa +. trellis_oa/setup.sh --basic --flash-attn --diffoctreerast --spconv + +# install kaolin +pip install Cython==0.29.37 +git clone https://github.com/NVIDIAGameWorks/kaolin.git +pip install -e kaolin/. + +# install dependencies +pip install -r requirements_3d.txt + +# a modified gaussian splatting (+ depth, alpha rendering) +git clone --recursive https://github.com/ashawkey/diff-gaussian-rasterization +pip install ./diff-gaussian-rasterization +``` + + +### Install dependencies for orientation estimation + +``` +# install Eigen3 3.4.0 under conda environment +conda install conda-forge::eigen=3.4.0 + +# install dependencies +pip install -r requirements_pose.txt + +# install unidepth +pip install -e orientation_estimation/data_preprocessing/. + +# install pytorch3d +git clone https://github.com/facebookresearch/pytorch3d +pip install -e pytorch3d/. + +# build extensions +conda install boost +CMAKE_PREFIX_PATH=$CONDA_PREFIX/lib/python3.10/site-packages/pybind11/share/cmake/pybind11 bash orientation_estimation/pose_refinement/build_all_conda.sh +``` + +## Pretrained Weights + +Our pretrained weights can be downloaded from Huggingface: + +| Module Name | Pretrained Weights | +| --------- | --------- | +| Trellis-OA | [download](https://huggingface.co/Louischong/Trellis-OA) | +| Wonder3D-OA | [download](https://huggingface.co/Louischong/Wonder3D-OA) | +| Orientation Estimation | [download](https://huggingface.co/Louischong/Orientation_Estimation) | + +You can also download the pretrained weights using [huggingface cli](https://huggingface.co/docs/huggingface_hub/guides/cli). + +Example for Trellis-OA and Orientation Estimation: + +``` +mkdir -p ./checkpoints/trellis_oa +huggingface-cli download --resume-download Louischong/Trellis-OA --local-dir ./checkpoints/trellis_oa +mkdir -p ./checkpoints/orientation_estimation +huggingface-cli download --resume-download Louischong/Orientation_Estimation --local-dir ./checkpoints/orientation_estimation +``` + +## Inference + +### Trellis-OA + +Run Trellis-OA using the shell script: + +``` +sh run_trellis_oa.sh $IMG_PATH $SAVE_DIR $CHECKPOINT_DIR +``` + +where `$IMG_PATH` is the path to the image, `$SAVE_DIR` is the directory to save the results, and `$CHECKPOINT_DIR` is the directory containing the pretrained weights. The 3D model will be saved in `$SAVE_DIR/trellis_oa_results`. + +For example, download the pretrained weights to `./checkpoints/trellis_oa` and run the following command: + +``` +sh run_trellis_oa.sh ./assets/boat.png ./results/boat ./checkpoints/trellis_oa +``` + +### Wonder3D-OA + +Run Wonder3D-OA using the shell script: + +``` +sh run_wonder3d_oa.sh $IMG_DIR $IMG_NAME $SAVE_DIR $CHECKPOINT_DIR +``` + +where `$IMG_DIR` is the directory containing the image, `$IMG_NAME` is the name of the image, `$SAVE_DIR` is the directory to save the results, and `$CHECKPOINT_DIR` is the directory containing the pretrained weights. The 3D model will be saved in `$SAVE_DIR/wonder3d_oa_results`. + +For example, download the pretrained weights to `./checkpoints/wonder3d_oa` and run the following command: + +``` +sh run_wonder3d_oa.sh ./assets boat.png ./results/boat ./checkpoints/wonder3d_oa +``` + +### Orientation Estimation + +Run Orientation Estimation using the shell script: + +``` +sh run_orientation_estimation.sh $IMG_PATH $SAVE_DIR $3D_MODEL_PATH $CHECKPOINT_DIR +``` + +where `$IMG_PATH` is the path to the image, `$SAVE_DIR` is the directory to save the results, `$3D_MODEL_PATH` is the path to the generated 3D model (.glb file is recommended), and `$CHECKPOINT_DIR` is the directory containing the pretrained weights. The orientation estimation results will be saved in `$SAVE_DIR/orientation_estimation_results`. + +For example, download the pretrained weights to `./checkpoints/orientation_estimation` and run the following command: + +``` +sh run_orientation_estimation.sh assets/boat.png ./results/boat ./results/boat/trellis_oa_results/sample.glb ./checkpoints/orientation_estimation +``` + + +## Dataset + +You can download the Objaverse-OA dataset from Huggingface: +``` +huggingface-cli download --repo-type dataset --resume-download Louischong/Objaverse-OA --local-dir ./datasets/objaverse_oa +``` + +## Acknowledgement + +Our code is built upon the following open-source projects: +[Wonder3D](https://github.com/xxlong0/Wonder3D), [LGM](https://github.com/3DTopia/LGM), [Trellis](https://github.com/microsoft/TRELLIS), [FoundationPose](https://github.com/NVlabs/FoundationPose), [UniDepth](https://github.com/lpiccinelli-eth/UniDepth), [DINOV2](https://github.com/facebookresearch/dinov2). Thanks for their great work! + +## 🔗 Citation +If you find this work helpful, please consider citing: +```BibTeXw +@misc{lu2025orientationmatters, + title={Orientation Matters: Making 3D Generative Models Orientation-Aligned}, + author={Yichong Lu and Yuzhuo Tian and Zijin Jiang and Yikun Zhao and Yuanbo Yang and Hao Ouyang and Haoji Hu and Huimin Yu and Yujun Shen and Yiyi Liao}, + year={2025}, + eprint={2506.08640}, + archivePrefix={arXiv}, + primaryClass={cs.CV}, + url={https://arxiv.org/abs/2506.08640}, +} +``` + diff --git a/OVOW/engine/oneposeviagen/Orientation/orient_then_scale.py b/OVOW/engine/oneposeviagen/Orientation/orient_then_scale.py new file mode 100644 index 0000000000000000000000000000000000000000..86587e28b36c5c45b14e4540b59131ed143fb49f --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orient_then_scale.py @@ -0,0 +1,356 @@ +import os +import sys +import glob +import json +import math +import shutil +from pathlib import Path + +import cv2 +import numpy as np +import torch +import trimesh + +# make project root importable +ROOT = Path(__file__).resolve().parents[2] +if str(ROOT) not in sys.path: + sys.path.insert(0, str(ROOT)) + +# ensure pose_refinement package-local imports (Utils, etc.) are visible +POSE_REFINE_DIR = Path(__file__).resolve().parent / "orientation_estimation" / "pose_refinement" +if str(POSE_REFINE_DIR) not in sys.path: + sys.path.insert(0, str(POSE_REFINE_DIR)) + +# --- import Orientation Estimation components --- +from oneposeviagen.Orientation.orientation_estimation.pose_refinement.estimater import ( + FoundationPose, + ScorePredictor, + PoseRefinePredictor, +) +from oneposeviagen.Orientation.orientation_estimation.pose_refinement.datareader import ( + YcbineoatReader, +) +import kaolin as _ # ensure kaolin is initialized if available +import nvdiffrast.torch as dr + +# --- torch hub will load local dinov2 --- +from PIL import Image +import torchvision.transforms as T +import torch.nn as nn + + +def _ensure_dir(p: Path): + p.mkdir(parents=True, exist_ok=True) + + +def _load_K(k_path: Path) -> np.ndarray: + if k_path.suffix == ".json": + with open(k_path, "r", encoding="utf-8") as f: + data = json.load(f) + k = np.array(data["0"]).reshape(3, 3) + else: + k = np.loadtxt(k_path).reshape(3, 3) + return k.astype(np.float32) + + +def _copy_rgb_depth_mask(rgb_path: Path, depth_path: Path, mask_path: Path, dst_root: Path): + rgb_dst = dst_root / "rgb" / "000000.png" + depth_dst = dst_root / "depth" / "000000.png" + mask_dst = dst_root / "masks" / "000000.png" + _ensure_dir(rgb_dst.parent) + _ensure_dir(depth_dst.parent) + _ensure_dir(mask_dst.parent) + + rgb = cv2.imread(str(rgb_path)) + if rgb is None: + raise FileNotFoundError(rgb_path) + cv2.imwrite(str(rgb_dst), rgb) + + depth = cv2.imread(str(depth_path), cv2.IMREAD_UNCHANGED) + if depth is None: + raise FileNotFoundError(depth_path) + cv2.imwrite(str(depth_dst), depth) + + mask = cv2.imread(str(mask_path), cv2.IMREAD_UNCHANGED) + if mask is None: + raise FileNotFoundError(mask_path) + if mask.ndim == 3: + mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY) + mask_bin = (mask > 0).astype(np.uint8) * 255 + cv2.imwrite(str(mask_dst), mask_bin) + return rgb_dst, depth_dst, mask_dst + + +def _run_orientation_estimation(mesh_path: Path, input_root: Path, ckpt_root: Path, debug: int = 2): + # Mirror of run_demo.py + dinov2_pose.py but in-process + test_scene_dir = input_root + output_dir = input_root / "foundationpose_outputs" + _ensure_dir(output_dir) + mesh = trimesh.load(mesh_path, force="mesh") + + # mesh normalization (same as default run_demo) + bbox_min, bbox_max = mesh.bounds + center = (bbox_min + bbox_max) / 2 + scale = np.max(bbox_max - bbox_min) + mesh.apply_translation(-center) + mesh.apply_scale(1.0 / scale) + + scorer = ScorePredictor(ckpt_root_dir=str(ckpt_root / "pose_refinement" / "ckpts")) + refiner = PoseRefinePredictor(ckpt_root_dir=str(ckpt_root / "pose_refinement" / "ckpts")) + glctx = dr.RasterizeCudaContext() + est = FoundationPose( + model_pts=mesh.vertices, + model_normals=mesh.vertex_normals, + mesh=mesh, + scorer=scorer, + refiner=refiner, + debug_dir=str(output_dir), + debug=debug, + glctx=glctx, + bg_color="black", + object_level=True, + rgb_only=True, + crop_ratio=1.8, + ) + + reader = YcbineoatReader(video_dir=str(test_scene_dir), shorter_side=None, zfar=np.inf) + poses = [] + _ensure_dir(output_dir / "ob_in_cam") + for i in range(len(reader.color_files)): + color = reader.get_color(i) + depth = reader.get_depth(i) + mask = reader.get_mask(i).astype(bool) + if i == 0: + pose = est.register(K=reader.K, rgb=color, depth=depth, ob_mask=mask, iteration=5) + else: + pose = est.track_one(rgb=color, depth=depth, K=reader.K, iteration=2) + np.savetxt(output_dir / "ob_in_cam" / f"{reader.id_strs[i]}.txt", pose.reshape(4, 4)) + poses.append(pose.reshape(4, 4)) + # save K for pose selection + _ensure_dir(output_dir / "refiner") + np.savetxt(output_dir / "refiner" / "K.txt", reader.K) + return output_dir, poses + + +def _pose_selection_dinov2(output_dir: Path, test_image: Path, ckpt_root: Path): + refiner_dir = output_dir / "refiner" + rgbA_files = sorted(refiner_dir.glob("rgbA_vis_*.png")) + if not rgbA_files: + raise RuntimeError("No rgbA_vis_*.png found for pose selection.") + num_frames = len(rgbA_files) + + # torch.hub expects the directory that directly contains hubconf.py + dinov2_repo_root = ckpt_root / "pose_selection" / "facebookresearch_dinov2_main" + if not (dinov2_repo_root / "hubconf.py").exists(): + alt = dinov2_repo_root / "facebookresearch_dinov2_main" + if (alt / "hubconf.py").exists(): + dinov2_repo_root = alt + dinov2_model = torch.hub.load(str(dinov2_repo_root), "dinov2_vitl14_reg", source="local") + dinov2_model.eval().cuda() + + def _score(idx): + rgbA_path = refiner_dir / f"rgbA_vis_{idx}.png" + rgbB_path = refiner_dir / f"rgbB_vis_{idx}.png" + rgbA = Image.open(rgbA_path).convert("RGB") + rgbB = Image.open(rgbB_path).convert("RGB") + image_transforms = T.Compose( + [ + T.Resize(256, interpolation=T.InterpolationMode.BICUBIC), + T.CenterCrop(224), + T.ToTensor(), + T.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)), + ] + ) + a = image_transforms(rgbA)[:3].unsqueeze(0).cuda() + b = image_transforms(rgbB)[:3].unsqueeze(0).cuda() + with torch.no_grad(): + fa = dinov2_model.forward_features(a)["x_norm_patchtokens"] + fb = dinov2_model.forward_features(b)["x_norm_patchtokens"] + mse_loss = nn.MSELoss() + return (1 - mse_loss(fa, fb)).item() + + scores = [ _score(i) for i in range(num_frames) ] + best_id = int(np.argmax(scores)) + + out_dir = output_dir.parent / "orientation_estimation_results" + if out_dir.exists(): + shutil.rmtree(out_dir) + _ensure_dir(out_dir) + + shutil.copy(refiner_dir / f"ob_in_cam_{best_id}.txt", out_dir / "ob_in_cam.txt") + shutil.copy(refiner_dir / f"rgbA_vis_{best_id}.png", out_dir / "rgbA_vis.png") + shutil.copy(refiner_dir / f"rgbB_vis_{best_id}.png", out_dir / "rgbB_vis.png") + + ob_in_cam = np.loadtxt(out_dir / "ob_in_cam.txt") + K = np.loadtxt(refiner_dir / "K.txt") + color_rgb = np.array(Image.open(test_image))[:, :, :3] + vis = _draw_xyz_axis(color_rgb, ob_in_cam, K, scale=0.5) + cv2.imwrite(str(out_dir / "vis.png"), cv2.cvtColor(vis, cv2.COLOR_RGB2BGR)) + return out_dir, scores, best_id + + +def _draw_xyz_axis(img_rgb, ob_in_cam, K, scale=0.5, thickness=3): + def proj(pt): + pt = pt.reshape(4, 1) + p2 = K @ ((ob_in_cam @ pt)[:3, :]) + p2 = p2.flatten() + return (p2[:2] / p2[2]).round().astype(int) + + origin = tuple(proj(np.array([0, 0, 0, 1], dtype=float))) + axes = [ + (np.array([scale, 0, 0, 1]), (255, 0, 0)), # X red (RGB) + (np.array([0, scale, 0, 1]), (0, 255, 0)), # Y green + (np.array([0, 0, scale, 1]), (0, 0, 255)), # Z blue + ] + canvas = img_rgb.copy() + for pt, col in axes: + dst = tuple(proj(pt)) + cv2.arrowedLine(canvas, origin, dst, col, thickness, tipLength=0.1) + return canvas + + +def _compute_scale(mesh: trimesh.Trimesh, depth_path: Path, mask_path: Path, K: np.ndarray, + R_cam_obj: np.ndarray, max_points=20000, mesh_samples=50000, q_lo=0.05, q_hi=0.95): + depth = cv2.imread(str(depth_path), cv2.IMREAD_UNCHANGED) + if depth is None: + raise FileNotFoundError(depth_path) + depth = depth.astype(np.float32) / 1000.0 + mask = cv2.imread(str(mask_path), cv2.IMREAD_UNCHANGED) + if mask is None: + raise FileNotFoundError(mask_path) + if mask.ndim == 3: + mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY) + mask = mask > 0 + + h, w = depth.shape[:2] + yy, xx = np.where(mask) + if len(xx) == 0: + raise RuntimeError("Mask is empty.") + z = depth[yy, xx] + valid = z > 1e-4 + xx = xx[valid] + yy = yy[valid] + z = z[valid] + if len(z) == 0: + raise RuntimeError("No valid depth in mask.") + + if len(z) > max_points: + sel = np.random.choice(len(z), max_points, replace=False) + xx, yy, z = xx[sel], yy[sel], z[sel] + + fx, fy, cx, cy = K[0, 0], K[1, 1], K[0, 2], K[1, 2] + x = (xx - cx) * z / fx + y = (yy - cy) * z / fy + P_cam = np.stack([x, y, z], axis=1) + P_obj = (R_cam_obj.T @ P_cam.T).T # rotate into mesh frame + + # mesh sampling + verts, _ = trimesh.sample.sample_surface(mesh, mesh_samples) + + # center both + P0 = P_obj - P_obj.mean(axis=0, keepdims=True) + V0 = verts - verts.mean(axis=0, keepdims=True) + + scales = [] + for axis in range(3): + ext_v = np.quantile(V0[:, axis], q_hi) - np.quantile(V0[:, axis], q_lo) + ext_p = np.quantile(P0[:, axis], q_hi) - np.quantile(P0[:, axis], q_lo) + if ext_v > 1e-6 and ext_p > 1e-6: + scales.append(ext_p / ext_v) + if not scales: + raise RuntimeError("Failed to compute scale; degenerate extents.") + scale = float(np.median(scales)) + return scale + + +def orient_then_scale( + object_dir: Path, + scene_dir: Path, + ckpt_root: Path, + frame: int = 0, + out_dir: Path = None, + use_existing_ob: Path = None, +): + object_dir = object_dir.resolve() + scene_dir = scene_dir.resolve() + if out_dir is None: + out_dir = object_dir / "oe_scale" + out_dir = out_dir.resolve() + _ensure_dir(out_dir) + + mesh_path = object_dir / "model" / "model.obj" + rgb_path = scene_dir / "rgb" / f"{frame:06d}.jpg" + depth_path = scene_dir / "depth" / f"{frame:06d}.png" + mask_path = object_dir / "masks" / f"{frame:06d}.png" + + # prefer anchor_file/intrinsic.txt, fallback to intrinsics.json + k_path = object_dir / "anchor_file" / "intrinsic.txt" + if not k_path.exists(): + k_path = scene_dir / "intrinsics.json" + K = _load_K(k_path) + + # prepare OE input + fp_inputs = out_dir / "foundationpose_inputs" + _copy_rgb_depth_mask(rgb_path, depth_path, mask_path, fp_inputs) + np.savetxt(fp_inputs / "cam_K.txt", K, fmt="%.6f") + + # Orientation Estimation + if use_existing_ob is None: + fp_outputs, _ = _run_orientation_estimation(mesh_path, fp_inputs, ckpt_root, debug=3) + oe_results, _, best_id = _pose_selection_dinov2(fp_outputs, rgb_path, ckpt_root) + ob_path = oe_results / "ob_in_cam.txt" + else: + ob_path = use_existing_ob + oe_results = out_dir / "orientation_estimation_results" + _ensure_dir(oe_results) + shutil.copy(ob_path, oe_results / "ob_in_cam.txt") + + ob_in_cam = np.loadtxt(ob_path) + R = ob_in_cam[:3, :3] + + # scale estimation + mesh = trimesh.load(mesh_path, force="mesh") + scale = _compute_scale(mesh, depth_path, mask_path, K, R) + mesh.apply_scale(scale) + mesh.export(out_dir / "scaled_mesh.obj") + with open(out_dir / "scale.txt", "w", encoding="utf-8") as f: + f.write(f"{scale:.8f}\n") + + # optional: save combined pose with scale + S = np.eye(4, dtype=np.float32) + S[:3, :3] *= scale + M = S @ ob_in_cam + np.savetxt(out_dir / "scaled_ob_in_cam.txt", M) + + return { + "scaled_mesh": str(out_dir / "scaled_mesh.obj"), + "scale": scale, + "ob_in_cam": str(ob_path), + "scaled_ob_in_cam": str(out_dir / "scaled_ob_in_cam.txt"), + } + + +def _parse_args(): + import argparse + + parser = argparse.ArgumentParser(description="Single-process Orientation Estimation + scale recovery") + parser.add_argument("--object_dir", type=str, required=True, help="Path to object dir (contains model/, masks/, anchor_file/)") + parser.add_argument("--scene_dir", type=str, required=True, help="Path to scene dir (contains rgb/, depth/, intrinsics.json)") + parser.add_argument("--ckpt_root", type=str, required=True, help="Orientation Estimation checkpoints root") + parser.add_argument("--frame", type=int, default=0, help="Anchor frame index, default 0") + parser.add_argument("--out_dir", type=str, default=None, help="Output directory (default: object_dir/oe_scale)") + parser.add_argument("--ob_in_cam", type=str, default=None, help="Use existing ob_in_cam.txt instead of running OE") + return parser.parse_args() + + +if __name__ == "__main__": + args = _parse_args() + res = orient_then_scale( + object_dir=Path(args.object_dir), + scene_dir=Path(args.scene_dir), + ckpt_root=Path(args.ckpt_root), + frame=args.frame, + out_dir=Path(args.out_dir) if args.out_dir else None, + use_existing_ob=Path(args.ob_in_cam) if args.ob_in_cam else None, + ) + print(json.dumps(res, indent=2)) diff --git a/OVOW/engine/oneposeviagen/Orientation/orient_then_scale.sh b/OVOW/engine/oneposeviagen/Orientation/orient_then_scale.sh new file mode 100644 index 0000000000000000000000000000000000000000..20ca60aa398ad0f4a3104129d56fae6f7dc27086 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orient_then_scale.sh @@ -0,0 +1,6 @@ +python OnePoseviaGen/oneposeviagen/Orientation/orient_then_scale.py \ + --object_dir OnePoseviaGen/temp_local/batch_run_20251210_025735/scene_02/objects/bag \ + --scene_dir OnePoseviaGen/temp_local/batch_run_20251210_025735/scene_02 \ + --ckpt_root OnePoseviaGen/oneposeviagen/Orientation/ckpt \ + --frame 0 \ + --out_dir OnePoseviaGen/temp_local/batch_run_20251210_025735/scene_02/objects/bag/oe_scale \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/.gitignore b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..07e7f5631cc90af2a92bd039b00263dbccaa862e --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/.gitignore @@ -0,0 +1,15 @@ +# don't upload macOS folder info +*.DS_Store + +#python +*.pyc +__pycache__/ + +#scripts +_*.sh +___*.py + +# package +**/build/ +**/dist/ +**/*.egg-info/ diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/LICENSE b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..12d4ca74d98cfb36269464dced75e9441b7bf645 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/LICENSE @@ -0,0 +1,407 @@ +Attribution-NonCommercial 4.0 International + +======================================================================= + +Creative Commons Corporation ("Creative Commons") is not a law firm and +does not provide legal services or legal advice. Distribution of +Creative Commons public licenses does not create a lawyer-client or +other relationship. Creative Commons makes its licenses and related +information available on an "as-is" basis. Creative Commons gives no +warranties regarding its licenses, any material licensed under their +terms and conditions, or any related information. Creative Commons +disclaims all liability for damages resulting from their use to the +fullest extent possible. + +Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and +conditions that creators and other rights holders may use to share +original works of authorship and other material subject to copyright +and certain other rights specified in the public license below. The +following considerations are for informational purposes only, are not +exhaustive, and do not form part of our licenses. + + Considerations for licensors: Our public licenses are + intended for use by those authorized to give the public + permission to use material in ways otherwise restricted by + copyright and certain other rights. Our licenses are + irrevocable. Licensors should read and understand the terms + and conditions of the license they choose before applying it. + Licensors should also secure all rights necessary before + applying our licenses so that the public can reuse the + material as expected. Licensors should clearly mark any + material not subject to the license. This includes other CC- + licensed material, or material used under an exception or + limitation to copyright. More considerations for licensors: + wiki.creativecommons.org/Considerations_for_licensors + + Considerations for the public: By using one of our public + licenses, a licensor grants the public permission to use the + licensed material under specified terms and conditions. If + the licensor's permission is not necessary for any reason--for + example, because of any applicable exception or limitation to + copyright--then that use is not regulated by the license. Our + licenses grant only permissions under copyright and certain + other rights that a licensor has authority to grant. Use of + the licensed material may still be restricted for other + reasons, including because others have copyright or other + rights in the material. A licensor may make special requests, + such as asking that all changes be marked or described. + Although not required by our licenses, you are encouraged to + respect those requests where reasonable. More considerations + for the public: + wiki.creativecommons.org/Considerations_for_licensees + +======================================================================= + +Creative Commons Attribution-NonCommercial 4.0 International Public +License + +By exercising the Licensed Rights (defined below), You accept and agree +to be bound by the terms and conditions of this Creative Commons +Attribution-NonCommercial 4.0 International Public License ("Public +License"). To the extent this Public License may be interpreted as a +contract, You are granted the Licensed Rights in consideration of Your +acceptance of these terms and conditions, and the Licensor grants You +such rights in consideration of benefits the Licensor receives from +making the Licensed Material available under these terms and +conditions. + + +Section 1 -- Definitions. + + a. Adapted Material means material subject to Copyright and Similar + Rights that is derived from or based upon the Licensed Material + and in which the Licensed Material is translated, altered, + arranged, transformed, or otherwise modified in a manner requiring + permission under the Copyright and Similar Rights held by the + Licensor. For purposes of this Public License, where the Licensed + Material is a musical work, performance, or sound recording, + Adapted Material is always produced where the Licensed Material is + synched in timed relation with a moving image. + + b. Adapter's License means the license You apply to Your Copyright + and Similar Rights in Your contributions to Adapted Material in + accordance with the terms and conditions of this Public License. + + c. Copyright and Similar Rights means copyright and/or similar rights + closely related to copyright including, without limitation, + performance, broadcast, sound recording, and Sui Generis Database + Rights, without regard to how the rights are labeled or + categorized. For purposes of this Public License, the rights + specified in Section 2(b)(1)-(2) are not Copyright and Similar + Rights. + d. Effective Technological Measures means those measures that, in the + absence of proper authority, may not be circumvented under laws + fulfilling obligations under Article 11 of the WIPO Copyright + Treaty adopted on December 20, 1996, and/or similar international + agreements. + + e. Exceptions and Limitations means fair use, fair dealing, and/or + any other exception or limitation to Copyright and Similar Rights + that applies to Your use of the Licensed Material. + + f. Licensed Material means the artistic or literary work, database, + or other material to which the Licensor applied this Public + License. + + g. Licensed Rights means the rights granted to You subject to the + terms and conditions of this Public License, which are limited to + all Copyright and Similar Rights that apply to Your use of the + Licensed Material and that the Licensor has authority to license. + + h. Licensor means the individual(s) or entity(ies) granting rights + under this Public License. + + i. NonCommercial means not primarily intended for or directed towards + commercial advantage or monetary compensation. For purposes of + this Public License, the exchange of the Licensed Material for + other material subject to Copyright and Similar Rights by digital + file-sharing or similar means is NonCommercial provided there is + no payment of monetary compensation in connection with the + exchange. + + j. Share means to provide material to the public by any means or + process that requires permission under the Licensed Rights, such + as reproduction, public display, public performance, distribution, + dissemination, communication, or importation, and to make material + available to the public including in ways that members of the + public may access the material from a place and at a time + individually chosen by them. + + k. Sui Generis Database Rights means rights other than copyright + resulting from Directive 96/9/EC of the European Parliament and of + the Council of 11 March 1996 on the legal protection of databases, + as amended and/or succeeded, as well as other essentially + equivalent rights anywhere in the world. + + l. You means the individual or entity exercising the Licensed Rights + under this Public License. Your has a corresponding meaning. + + +Section 2 -- Scope. + + a. License grant. + + 1. Subject to the terms and conditions of this Public License, + the Licensor hereby grants You a worldwide, royalty-free, + non-sublicensable, non-exclusive, irrevocable license to + exercise the Licensed Rights in the Licensed Material to: + + a. reproduce and Share the Licensed Material, in whole or + in part, for NonCommercial purposes only; and + + b. produce, reproduce, and Share Adapted Material for + NonCommercial purposes only. + + 2. Exceptions and Limitations. For the avoidance of doubt, where + Exceptions and Limitations apply to Your use, this Public + License does not apply, and You do not need to comply with + its terms and conditions. + + 3. Term. The term of this Public License is specified in Section + 6(a). + + 4. Media and formats; technical modifications allowed. The + Licensor authorizes You to exercise the Licensed Rights in + all media and formats whether now known or hereafter created, + and to make technical modifications necessary to do so. The + Licensor waives and/or agrees not to assert any right or + authority to forbid You from making technical modifications + necessary to exercise the Licensed Rights, including + technical modifications necessary to circumvent Effective + Technological Measures. For purposes of this Public License, + simply making modifications authorized by this Section 2(a) + (4) never produces Adapted Material. + + 5. Downstream recipients. + + a. Offer from the Licensor -- Licensed Material. Every + recipient of the Licensed Material automatically + receives an offer from the Licensor to exercise the + Licensed Rights under the terms and conditions of this + Public License. + + b. No downstream restrictions. You may not offer or impose + any additional or different terms or conditions on, or + apply any Effective Technological Measures to, the + Licensed Material if doing so restricts exercise of the + Licensed Rights by any recipient of the Licensed + Material. + + 6. No endorsement. Nothing in this Public License constitutes or + may be construed as permission to assert or imply that You + are, or that Your use of the Licensed Material is, connected + with, or sponsored, endorsed, or granted official status by, + the Licensor or others designated to receive attribution as + provided in Section 3(a)(1)(A)(i). + + b. Other rights. + + 1. Moral rights, such as the right of integrity, are not + licensed under this Public License, nor are publicity, + privacy, and/or other similar personality rights; however, to + the extent possible, the Licensor waives and/or agrees not to + assert any such rights held by the Licensor to the limited + extent necessary to allow You to exercise the Licensed + Rights, but not otherwise. + + 2. Patent and trademark rights are not licensed under this + Public License. + + 3. To the extent possible, the Licensor waives any right to + collect royalties from You for the exercise of the Licensed + Rights, whether directly or through a collecting society + under any voluntary or waivable statutory or compulsory + licensing scheme. In all other cases the Licensor expressly + reserves any right to collect such royalties, including when + the Licensed Material is used other than for NonCommercial + purposes. + + +Section 3 -- License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the +following conditions. + + a. Attribution. + + 1. If You Share the Licensed Material (including in modified + form), You must: + + a. retain the following if it is supplied by the Licensor + with the Licensed Material: + + i. identification of the creator(s) of the Licensed + Material and any others designated to receive + attribution, in any reasonable manner requested by + the Licensor (including by pseudonym if + designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of + warranties; + + v. a URI or hyperlink to the Licensed Material to the + extent reasonably practicable; + + b. indicate if You modified the Licensed Material and + retain an indication of any previous modifications; and + + c. indicate the Licensed Material is licensed under this + Public License, and include the text of, or the URI or + hyperlink to, this Public License. + + 2. You may satisfy the conditions in Section 3(a)(1) in any + reasonable manner based on the medium, means, and context in + which You Share the Licensed Material. For example, it may be + reasonable to satisfy the conditions by providing a URI or + hyperlink to a resource that includes the required + information. + + 3. If requested by the Licensor, You must remove any of the + information required by Section 3(a)(1)(A) to the extent + reasonably practicable. + + 4. If You Share Adapted Material You produce, the Adapter's + License You apply must not prevent recipients of the Adapted + Material from complying with this Public License. + + +Section 4 -- Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that +apply to Your use of the Licensed Material: + + a. for the avoidance of doubt, Section 2(a)(1) grants You the right + to extract, reuse, reproduce, and Share all or a substantial + portion of the contents of the database for NonCommercial purposes + only; + + b. if You include all or a substantial portion of the database + contents in a database in which You have Sui Generis Database + Rights, then the database in which You have Sui Generis Database + Rights (but not its individual contents) is Adapted Material; and + + c. You must comply with the conditions in Section 3(a) if You Share + all or a substantial portion of the contents of the database. + +For the avoidance of doubt, this Section 4 supplements and does not +replace Your obligations under this Public License where the Licensed +Rights include other Copyright and Similar Rights. + + +Section 5 -- Disclaimer of Warranties and Limitation of Liability. + + a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE + EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS + AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF + ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, + IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, + WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR + PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, + ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT + KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT + ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. + + b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE + TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, + NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, + INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, + COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR + USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN + ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR + DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR + IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. + + c. The disclaimer of warranties and limitation of liability provided + above shall be interpreted in a manner that, to the extent + possible, most closely approximates an absolute disclaimer and + waiver of all liability. + + +Section 6 -- Term and Termination. + + a. This Public License applies for the term of the Copyright and + Similar Rights licensed here. However, if You fail to comply with + this Public License, then Your rights under this Public License + terminate automatically. + + b. Where Your right to use the Licensed Material has terminated under + Section 6(a), it reinstates: + + 1. automatically as of the date the violation is cured, provided + it is cured within 30 days of Your discovery of the + violation; or + + 2. upon express reinstatement by the Licensor. + + For the avoidance of doubt, this Section 6(b) does not affect any + right the Licensor may have to seek remedies for Your violations + of this Public License. + + c. For the avoidance of doubt, the Licensor may also offer the + Licensed Material under separate terms or conditions or stop + distributing the Licensed Material at any time; however, doing so + will not terminate this Public License. + + d. Sections 1, 5, 6, 7, and 8 survive termination of this Public + License. + + +Section 7 -- Other Terms and Conditions. + + a. The Licensor shall not be bound by any additional or different + terms or conditions communicated by You unless expressly agreed. + + b. Any arrangements, understandings, or agreements regarding the + Licensed Material not stated herein are separate from and + independent of the terms and conditions of this Public License. + + +Section 8 -- Interpretation. + + a. For the avoidance of doubt, this Public License does not, and + shall not be interpreted to, reduce, limit, restrict, or impose + conditions on any use of the Licensed Material that could lawfully + be made without permission under this Public License. + + b. To the extent possible, if any provision of this Public License is + deemed unenforceable, it shall be automatically reformed to the + minimum extent necessary to make it enforceable. If the provision + cannot be reformed, it shall be severed from this Public License + without affecting the enforceability of the remaining terms and + conditions. + + c. No term or condition of this Public License will be waived and no + failure to comply consented to unless expressly agreed to by the + Licensor. + + d. Nothing in this Public License constitutes or may be interpreted + as a limitation upon, or waiver of, any privileges and immunities + that apply to the Licensor or You, including from the legal + processes of any jurisdiction or authority. + +======================================================================= + +Creative Commons is not a party to its public +licenses. Notwithstanding, Creative Commons may elect to apply one of +its public licenses to material it publishes and in those instances +will be considered the “Licensor.” The text of the Creative Commons +public licenses is dedicated to the public domain under the CC0 Public +Domain Dedication. Except for the limited purpose of indicating that +material is shared under a Creative Commons public license or as +otherwise permitted by the Creative Commons policies published at +creativecommons.org/policies, Creative Commons does not authorize the +use of the trademark "Creative Commons" or any other trademark or logo +of Creative Commons without its prior written consent including, +without limitation, in connection with any unauthorized modifications +to any of its public licenses or any other arrangements, +understandings, or agreements concerning use of licensed material. For +the avoidance of doubt, this paragraph does not form part of the +public licenses. + +Creative Commons may be contacted at creativecommons.org. \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/README.md b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/README.md new file mode 100644 index 0000000000000000000000000000000000000000..31140984301a3b5704d702a0724063aeac31eb3c --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/README.md @@ -0,0 +1,300 @@ +[![arXiv](https://img.shields.io/badge/UniDepthV2%20arXiv-2502.20110-blue?logo=arxiv&color=%23B31B1B)](https://arxiv.org/abs/2502.20110) +[![arXiv](https://img.shields.io/badge/UniDepthV1%20arXiv-2403.18913-blue?logo=arxiv-v1&color=%23B31B1B)](https://arxiv.org/abs/2403.18913) +[![ProjectPage](https://img.shields.io/badge/Project_Page-UniDepth-blue)](https://lpiccinelli-eth.github.io/pub/unidepth/) + +# UniDepthV2: Universal Monocular Metric Depth Estimation Made Simpler + +[![KITTI Benchmark](https://img.shields.io/badge/KITTI%20Benchmark-1st%20(at%20submission%20time)-orange)](https://www.cvlibs.net/datasets/kitti/eval_depth.php?benchmark=depth_prediction) +[![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/unidepthv2-universal-monocular-metric-depth/monocular-depth-estimation-on-nyu-depth-v2)](https://paperswithcode.com/sota/monocular-depth-estimation-on-nyu-depth-v2?p=unidepthv2-universal-monocular-metric-depth) +[![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/unidepthv2-universal-monocular-metric-depth/monocular-depth-estimation-on-kitti-eigen)](https://paperswithcode.com/sota/monocular-depth-estimation-on-kitti-eigen?p=unidepthv2-universal-monocular-metric-depth) + + +![](assets/docs/unidepthv2-banner.png) + +> [**UniDepthV2: Universal Monocular Metric Depth Estimation Made Simpler**](https://arxiv.org/abs/2502.20110), +> Luigi Piccinelli, Christos Sakaridis, Yung-Hsu Yang, Mattia Segu, Siyuan Li, Wim Abbeloos, Luc Van Gool, +> under submission, +> *Paper at [arXiv 2502.20110](https://arxiv.org/abs/2502.20110.pdf)* + + +# UniDepth: Universal Monocular Metric Depth Estimation + +[![KITTI Benchmark](https://img.shields.io/badge/KITTI%20Benchmark-1st%20(at%20submission%20time)-orange)](https://www.cvlibs.net/datasets/kitti/eval_depth.php?benchmark=depth_prediction) +[![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/unidepth-universal-monocular-metric-depth/monocular-depth-estimation-on-nyu-depth-v2)](https://paperswithcode.com/sota/monocular-depth-estimation-on-nyu-depth-v2?p=unidepth-universal-monocular-metric-depth) +[![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/unidepth-universal-monocular-metric-depth/monocular-depth-estimation-on-kitti-eigen)](https://paperswithcode.com/sota/monocular-depth-estimation-on-kitti-eigen?p=unidepth-universal-monocular-metric-depth) + +![](assets/docs/unidepth-banner.png) + +> [**UniDepth: Universal Monocular Metric Depth Estimation**](https://arxiv.org/abs/2403.18913), +> Luigi Piccinelli, Yung-Hsu Yang, Christos Sakaridis, Mattia Segu, Siyuan Li, Luc Van Gool, Fisher Yu, +> CVPR 2024, +> *Paper at [arXiv 2403.18913](https://arxiv.org/pdf/2403.18913.pdf)* + + + +## News and ToDo + +- [ ] HuggingFace/Gradio demo. +- [x] `28.02.2025`: Release UniDepthV2. +- [x] `15.10.2024`: Release training code. +- [x] `02.04.2024`: Release UniDepth as python package. +- [x] `01.04.2024`: Inference code and V1 models are released. +- [x] `26.02.2024`: UniDepth is accepted at CVPR 2024! (Highlight :star:) + + +## Zero-Shot Visualization + +### YouTube (The Office - Parkour) +

    + animated +

    + +### NuScenes (stitched cameras) +

    + animated +

    + + +## Installation + +Requirements are not in principle hard requirements, but there might be some differences (not tested): +- Linux +- Python 3.10+ +- CUDA 11.8+ + +Install the environment needed to run UniDepth with: +```shell +export VENV_DIR= +export NAME=Unidepth + +python -m venv $VENV_DIR/$NAME +source $VENV_DIR/$NAME/bin/activate + +# Install UniDepth and dependencies, cuda >11.8 work fine, too. +pip install -e . --extra-index-url https://download.pytorch.org/whl/cu118 + +# Install Pillow-SIMD (Optional) +pip uninstall pillow +CC="cc -mavx2" pip install -U --force-reinstall pillow-simd + +# Install KNN (for evaluation only) +cd unidepth/ops/knn;bash compile.sh;cd ../../../ +``` + +If you use conda, you should change the following: +```shell +python -m venv $VENV_DIR/$NAME -> conda create -n $NAME python=3.11 +source $VENV_DIR/$NAME/bin/activate -> conda activate $NAME +``` + +*Note*: Make sure that your compilation CUDA version and runtime CUDA version match. +You can check the supported CUDA version for precompiled packages on the [PyTorch website](https://pytorch.org/). + +*Note*: xFormers may raise the the Runtime "error": `Triton Error [CUDA]: device kernel image is invalid`. +This is related to xFormers mismatching system-wide CUDA and CUDA shipped with torch. +It may considerably slow down inference. + +Run UniDepth on the given assets to test your installation (you can check this script as guideline for further usage): +```shell +python ./scripts/demo.py +``` +If everything runs correctly, `demo.py` should print: `ARel: 7.45%`. + +If you encounter `Segmentation Fault` after running the demo, you may need to uninstall torch via pip (`pip uninstall torch`) and install the torch version present in [requirements](requirements.txt) with `conda`. + +## Get Started + +After installing the dependencies, you can load the pre-trained models easily from [Hugging Face](https://huggingface.co/models?other=UniDepth) as follows: + +```python +from unidepth.models import UniDepthV1 + +model = UniDepthV1.from_pretrained("lpiccinelli/unidepth-v1-vitl14") # or "lpiccinelli/unidepth-v1-cnvnxtl" for the ConvNext backbone +``` + +Then you can generate the metric depth estimation and intrinsics prediction directly from RGB image only as follows: + +```python +import numpy as np +from PIL import Image + +# Move to CUDA, if any +device = torch.device("cuda" if torch.cuda.is_available() else "cpu") +model = model.to(device) + +# Load the RGB image and the normalization will be taken care of by the model +rgb = torch.from_numpy(np.array(Image.open(image_path))).permute(2, 0, 1) # C, H, W + +predictions = model.infer(rgb) + +# Metric Depth Estimation +depth = predictions["depth"] + +# Point Cloud in Camera Coordinate +xyz = predictions["points"] + +# Intrinsics Prediction +intrinsics = predictions["intrinsics"] +``` + +You can use ground truth intrinsics as input to the model as well: +```python +intrinsics_path = "assets/demo/intrinsics.npy" + +# Load the intrinsics if available +intrinsics = torch.from_numpy(np.load(intrinsics_path)) # 3 x 3 + +# For V2, we defined camera classes. If you pass a 3x3 tensor (as above) +# it will convert to Pinhole, but you can pass classes from camera.py. +# The `Camera` class is meant as an abstract, use only child classes as e.g.: +from unidepth.utils.camera import Pinhole, Fisheye624 + +camera = Pinhole(K=intrinsics) # pinhole +# fill in fisheye, params: fx,fy,cx,cy,d1,d2,d3,d4,d5,d6,t1,t2,s1,s2,s3,s4 +camera = Fisheye624(params=torch.tensor([...])) +predictions = model.infer(rgb, camera) +``` + +To use the forward method for your custom training, you should: +1) Take care of the dataloading: + a) ImageNet-normalization + b) Long-edge based resizing (and padding) with input shape provided in `image_shape` under configs + c) `BxCxHxW` format + d) If any intriniscs given, adapt them accordingly to your resizing +2) Format the input data structure as: +```python +data = {"image": rgb, "K": intrinsics} +predictions = model(data, {}) +``` + +## Model Zoo + +The available models are the following: + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + +
    ModelBackboneName
    UnidepthV1ConvNext-Lunidepth-v1-cnvnxtl
    ViT-Lunidepth-v1-vitl14
    UnidepthV2ViT-Sunidepth-v2-vits14
    ViT-Bunidepth-v2-vits14
    ViT-Lunidepth-v2-vitl14
    + +Please visit [Hugging Face](https://huggingface.co/lpiccinelli) or click on the links above to access the repo models with weights. +You can load UniDepth as the following, with `name` variable matching the table above: + +```python +from unidepth.models import UniDepthV1, UniDepthV2 + +model_v1 = UniDepthV1.from_pretrained(f"lpiccinelli/{name}") +model_v2 = UniDepthV2.from_pretrained(f"lpiccinelli/{name}") +``` + +In addition, we provide loading from TorchHub as: + +```python +version = "v2" +backbone = "vitl14" + +model = torch.hub.load("lpiccinelli-eth/UniDepth", "UniDepth", version=version, backbone=backbone, pretrained=True, trust_repo=True, force_reload=True) +``` + +You can look into function `UniDepth` in [hubconf.py](hubconf.py) to see how to instantiate the model from local file: provide a local `path` in line 34. + + +## UniDepthV2 + +Visit [UniDepthV2 ReadMe](assets/docs/V2_README.md) for a more detailed changelog. +To summarize the main differences are: +- Improved performance and edge sharpness. (`EdgeGuidedLocalSSI`) +- Input shape and ratio flexibility. (`self.resolution_level`) +- Confidence output. +- Faster inference. +- ONNX support. +- New cameras support (see `camera.py`). + +UnidepthV2old is actually V1 version updated to compensate for wave artifacts due to wrong LiDAR accumulation. + +## Training + +Please [visit the training README](scripts/README.md) for more information. + + +## Results + +### Metric Depth Estimation +The performance reported is for UniDepthV1 model and the metrics is d1 (higher is better) on zero-shot evaluation. The common split between SUN-RGBD and NYUv2 is removed from SUN-RGBD validation set for evaluation. + +| Model | NYUv2 | SUN-RGBD | ETH3D | Diode (In) | IBims-1 | KITTI | Nuscenes | DDAD | +| :-: | :-: | :-: | :-: | :-: | :-: | :-: | :-: | :-: | +| iDisc | 93.8 | 83.7 | 35.6 | 23.8 | 48.9 | 97.5 | 39.4 | 28.4 | +| ZoeDepth | 95.2 | 86.7 | 35.0 | 36.9 | 58.0 | 96.5 | 28.3 | 27.2 | +| Metric3D | 92.6 | 15.4 | 45.6 | 39.2 | 79.7 | 97.5 | 72.3 | - | +| Metric3Dv2 | 98.9 | 81.2 | 90.0 | - | 68.4 | 98.5 | 84.1 | - | +| DepthPro | - | 83.1 | 39.7 | - | 82.3 | - | 56.6 | 29.9 | +| UniDepthV1 | 98.4 | 94.3 | 18.5 | 77.1 | 15.7 | 98.6 | 84.6 | 85.8 | +| UniDepthV2 | 98.8 | 96.4 | 85.2 | - | 94.5 | 98.9 | 87.0 | 88.2 | + + + +## Contributions + +If you find any bug in the code, please report to Luigi Piccinelli (lpiccinelli@ethz.ch) + + +## Citation + +If you find our work useful in your research please consider citing our publications: +```bibtex +@inproceedings{piccinelli2024unidepth, + title = {{U}ni{D}epth: Universal Monocular Metric Depth Estimation}, + author = {Piccinelli, Luigi and Yang, Yung-Hsu and Sakaridis, Christos and Segu, Mattia and Li, Siyuan and Van Gool, Luc and Yu, Fisher}, + booktitle = {Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR)}, + year = {2024} +} +``` + +```bibtex +@misc{piccinelli2025unidepthv2, + title={{U}ni{D}epth{V2}: Universal Monocular Metric Depth Estimation Made Simpler}, + author={Luigi Piccinelli and Christos Sakaridis and Yung-Hsu Yang and Mattia Segu and Siyuan Li and Wim Abbeloos and Luc Van Gool}, + year={2025}, + eprint={2502.20110}, + archivePrefix={arXiv}, + primaryClass={cs.CV}, + url={https://arxiv.org/abs/2502.20110}, +} +``` + +## License + +This software is released under Creatives Common BY-NC 4.0 license. You can view a license summary [here](LICENSE). + + +## Acknowledgement + +We would like to express our gratitude to [@niels](https://huggingface.co/nielsr) for helping intergrating UniDepth in HuggingFace. + +This work is funded by Toyota Motor Europe via the research project [TRACE-Zurich](https://trace.ethz.ch) (Toyota Research on Automated Cars Europe). diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/assets/docs/V2_README.md b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/assets/docs/V2_README.md new file mode 100644 index 0000000000000000000000000000000000000000..585043db19647ff3a3b7016c3cd9ce78287b4e4f --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/assets/docs/V2_README.md @@ -0,0 +1,49 @@ +# Changes + + +### Input shape and ratio flexibility. + +1. Input images will not be reshaped to a specific image size. Training image ratios are in tha range: `[0.5, 2.5]`, thus if your image ratio is outside of these boundaries, padding will be applied. + +2. UnidepthV2 exposes the attribute `self.resolution_level` (with range `[0,10)`) that is used in the preprocess function and can be used to tradeoff resolution and speed, with **ideally small effect** on the output scale. In particular, the level describes the linear interpolation degree of the processed image area within the training bounds. The training image area (named "pixels") for ViT are in the range `[0.2, 0.6]` MegaPixels (see `pixels_bounds` in config). If no attribute is set, the full pixel bounds are used. + +3. Infer method will use interpolation mode defined by the attribute `self.interpolation_mode`, default is `bilinear`. + + +### Confidence output + +The model outputs confidence as the estimated scale-invaraint log error, i.e. the confidence is a ranking and relative within one input. +In particular, it does not have an absolute meaning (e.g. no heteroschdastic noise modelling). + + +### Faster inference + +The model is >30% faster than V1, tested on RTX4090 with float16 data-type. + + +### Random edge extraction + +In order to perform `EdgeGuidedLocalSSI` efficiently, you need to compile the CUDA operation we wrote to speedup the random patch extraction with `cd ./unidepth/ops/extract_patches && bash compile.sh`. Remember to export your `TORCH_CUDA_ARCH_LIST` if it is different wrt the defualt present in `compile.sh`. + + +### Camera + +UniDepthV2 can accept a larger variety of cameras, plase check `unidepth/utils/camera.py` for a comprehensive list. +`infer` method accepts either a tensor as a K matrix, i.e. assumes pinhole!, or a **child** of `Camera`, which can be, e.g. Fisheye624, Pinhole, OPENCV, ... +Do not pass directly a `Camera` class as it lacks methods and it is supposed to be an abtract parent class with some methods implemented. + + +### ONNX support + +We added support to UniDepthV2 in __ONNX__ format. +For instance you can run from the root of the repo: +```bash + +python ./unidepth/models/unidepthv2/export.py --version v2 --backbone vitl --shape 462 616 --output-path unidepthv2.onnx +``` + +Shape will be changed to the closest shape which is multiple of 14, i.e. ViT patch size. +Your input shape at inference time will have to match with the (resized) shape passed to the exporter! +The corresponding __ONNX__ model does not do any pre- or post-processing. +Therefore, you should input an ImageNet-statistic normalized rgb image rescaled to the given input shape and. +Add falg `--with-camera` to accept given GT camera as unprojected rays as input. \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/configs/config_v1_cnvnxtl.json b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/configs/config_v1_cnvnxtl.json new file mode 100644 index 0000000000000000000000000000000000000000..f2002be27672042d8845aa1af2e96733c7305427 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/configs/config_v1_cnvnxtl.json @@ -0,0 +1,24 @@ +{ + "generic": { + "seed": 13 + }, + "training": { + }, + "data": { + "image_shape": [462, 616] + }, + "model": { + "name": "UniDepthV1", + "num_heads": 8, + "expansion": 4, + "pixel_decoder": { + "hidden_dim": 512, + "depths": [3, 2, 1], + "dropout": 0.0 + }, + "pixel_encoder": { + "name": "convnext_large", + "pretrained": null + } + } +} \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/configs/config_v1_vitl14.json b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/configs/config_v1_vitl14.json new file mode 100644 index 0000000000000000000000000000000000000000..b57f6db2549297bc407a77b89177e14077d00d8c --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/configs/config_v1_vitl14.json @@ -0,0 +1,23 @@ +{ + "generic": { + "seed": 13 + }, + "training": {}, + "data": { + "image_shape": [462, 616] + }, + "model": { + "name": "UniDepthV1", + "num_heads": 8, + "expansion": 4, + "pixel_decoder": { + "hidden_dim": 512, + "depths": [3, 2, 1], + "dropout": 0.0 + }, + "pixel_encoder": { + "name": "dinov2_vitl14", + "pretrained": null + } + } +} \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/configs/config_v2_vitb14.json b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/configs/config_v2_vitb14.json new file mode 100644 index 0000000000000000000000000000000000000000..3decb3fe3997a03fa85e0309bbc1a9f2af800077 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/configs/config_v2_vitb14.json @@ -0,0 +1,133 @@ +{ + "generic": { + "seed": 13, + "deterministic": true + }, + "training": { + "n_iters": 300000, + "batch_size": 8, + "validation_interval": 2, + "nsteps_accumulation_gradient": 2, + "use_checkpoint": false, + "lr": 1e-4, + "lr_final": 1e-6, + "lr_warmup": 1.0, + "cycle_beta": false, + + "wd": 0.1, + "wd_final": 0.1, + "warmup_iters": 75000, + "ld": 1.0, + + "drop_path": 0.0, + "ema": true, + "f16": true, + "clipping": 1.0, + "losses": { + "depth": { + "name": "SILog", + "weight": 1.0, + "output_fn": "sqrt", + "input_fn": "log", + "dims": [-2,-1], + "integrated": 0.15 + }, + "invariance": { + "name": "SelfDistill", + "weight": 0.1, + "output_fn": "sqrt" + }, + "camera": { + "name": "Regression", + "weight": 0.25, + "gamma": 1.0, + "alpha": 1.0, + "fn": "l2", + "output_fn": "sqrt", + "input_fn": "linear" + }, + "ssi": { + "name": "EdgeGuidedLocalSSI", + "weight": 1.0, + "output_fn": "sqrt", + "input_fn": "log1i", + "use_global": true, + "min_samples": 6 + }, + "confidence": { + "name": "Confidence", + "weight": 0.1, + "gamma": 1.0, + "alpha": 1.0, + "fn": "l1", + "output_fn": "sqrt", + "input_fn": "linear" + } + }}, + "data": { + "image_shape": [480, 640], + "normalization": "imagenet", + "num_copies": 2, + "num_frames": 1, + "sampling":{ + "Waymo": 1.0, + "ETH3D": 1.0 + }, + "train_datasets": [ + "ETH3D", + "Waymo" + ], + "val_datasets": [ + "IBims" + ], + "data_root": "datasets", + "crop": "garg", + "augmentations": { + "random_scale": 2.0, + "random_jitter": 0.4, + "jitter_p": 0.8, + "random_blur": 2.0, + "blur_p": 0.2, + "random_gamma": 0.2, + "gamma_p": 0.8, + "grayscale_p": 0.2, + "flip_p": 0.5, + "test_context": 1.0, + "shape_constraints": { + "ratio_bounds": [0.5, 2.5], + "pixels_max": 600000, + "pixels_min": 200000, + "height_min": 15, + "width_min": 15, + "shape_mult": 14, + "sample": true + } + } + }, + "model": { + "name": "UniDepthV2", + "num_heads": 8, + "expansion": 4, + "layer_scale": 1.0, + "pixel_decoder": { + "name": "Decoder", + "hidden_dim": 384, + "dropout": 0.0, + "depths": [2, 2, 2], + "out_dim": 48, + "kernel_size": 3 + }, + "pixel_encoder": { + "lr": 2e-06, + "wd": 0.1, + "name": "dinov2_vitb14", + "frozen_stages": 0, + "num_register_tokens": 0, + "use_norm": true, + "freeze_norm": true, + "pretrained": null, + "stacking_fn": "last", + "output_idx": [3, 6, 9, 12] + } + } +} \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/configs/config_v2_vitl14.json b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/configs/config_v2_vitl14.json new file mode 100644 index 0000000000000000000000000000000000000000..3d7d963a69521ba4cb6e304967579a2497bf208e --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/configs/config_v2_vitl14.json @@ -0,0 +1,133 @@ +{ + "generic": { + "seed": 13, + "deterministic": true + }, + "training": { + "n_iters": 300000, + "batch_size": 8, + "validation_interval": 2, + "nsteps_accumulation_gradient": 2, + "use_checkpoint": false, + "lr": 1e-4, + "lr_final": 1e-6, + "lr_warmup": 1.0, + "cycle_beta": false, + + "wd": 0.1, + "wd_final": 0.1, + "warmup_iters": 75000, + "ld": 1.0, + + "drop_path": 0.0, + "ema": true, + "f16": true, + "clipping": 1.0, + "losses": { + "depth": { + "name": "SILog", + "weight": 1.0, + "output_fn": "sqrt", + "input_fn": "log", + "dims": [-2,-1], + "integrated": 0.15 + }, + "invariance": { + "name": "SelfDistill", + "weight": 0.1, + "output_fn": "sqrt" + }, + "camera": { + "name": "Regression", + "weight": 0.25, + "gamma": 1.0, + "alpha": 1.0, + "fn": "l2", + "output_fn": "sqrt", + "input_fn": "linear" + }, + "ssi": { + "name": "EdgeGuidedLocalSSI", + "weight": 1.0, + "output_fn": "sqrt", + "input_fn": "log1i", + "use_global": true, + "min_samples": 6 + }, + "confidence": { + "name": "Confidence", + "weight": 0.1, + "gamma": 1.0, + "alpha": 1.0, + "fn": "l1", + "output_fn": "sqrt", + "input_fn": "linear" + } + }}, + "data": { + "image_shape": [480, 640], + "normalization": "imagenet", + "num_copies": 2, + "num_frames": 1, + "sampling":{ + "Waymo": 1.0, + "ETH3D": 1.0 + }, + "train_datasets": [ + "ETH3D", + "Waymo" + ], + "val_datasets": [ + "IBims" + ], + "data_root": "datasets", + "crop": "garg", + "augmentations": { + "random_scale": 2.0, + "random_jitter": 0.4, + "jitter_p": 0.8, + "random_blur": 2.0, + "blur_p": 0.2, + "random_gamma": 0.2, + "gamma_p": 0.8, + "grayscale_p": 0.2, + "flip_p": 0.5, + "test_context": 1.0, + "shape_constraints": { + "ratio_bounds": [0.5, 2.5], + "pixels_max": 600000, + "pixels_min": 200000, + "height_min": 15, + "width_min": 15, + "shape_mult": 14, + "sample": true + } + } + }, + "model": { + "name": "UniDepthV2", + "num_heads": 8, + "expansion": 4, + "layer_scale": 1.0, + "pixel_decoder": { + "name": "Decoder", + "hidden_dim": 512, + "dropout": 0.0, + "depths": [2, 2, 2], + "out_dim": 64, + "kernel_size": 3 + }, + "pixel_encoder": { + "lr": 2e-06, + "wd": 0.1, + "name": "dinov2_vitl14", + "frozen_stages": 0, + "num_register_tokens": 0, + "use_norm": true, + "freeze_norm": true, + "pretrained": null, + "stacking_fn": "last", + "output_idx": [6, 12, 18, 24] + } + } +} \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/configs/config_v2_vits14.json b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/configs/config_v2_vits14.json new file mode 100644 index 0000000000000000000000000000000000000000..fa9b47c6ea5d49e444d21139b00c1500f5edf33e --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/configs/config_v2_vits14.json @@ -0,0 +1,133 @@ +{ + "generic": { + "seed": 13, + "deterministic": true + }, + "training": { + "n_iters": 300000, + "batch_size": 8, + "validation_interval": 2, + "nsteps_accumulation_gradient": 2, + "use_checkpoint": false, + "lr": 1e-4, + "lr_final": 1e-6, + "lr_warmup": 1.0, + "cycle_beta": false, + + "wd": 0.1, + "wd_final": 0.1, + "warmup_iters": 75000, + "ld": 1.0, + + "drop_path": 0.0, + "ema": true, + "f16": true, + "clipping": 1.0, + "losses": { + "depth": { + "name": "SILog", + "weight": 1.0, + "output_fn": "sqrt", + "input_fn": "log", + "dims": [-2,-1], + "integrated": 0.15 + }, + "invariance": { + "name": "SelfDistill", + "weight": 0.1, + "output_fn": "sqrt" + }, + "camera": { + "name": "Regression", + "weight": 0.25, + "gamma": 1.0, + "alpha": 1.0, + "fn": "l2", + "output_fn": "sqrt", + "input_fn": "linear" + }, + "ssi": { + "name": "EdgeGuidedLocalSSI", + "weight": 1.0, + "output_fn": "sqrt", + "input_fn": "log1i", + "use_global": true, + "min_samples": 6 + }, + "confidence": { + "name": "Confidence", + "weight": 0.1, + "gamma": 1.0, + "alpha": 1.0, + "fn": "l1", + "output_fn": "sqrt", + "input_fn": "linear" + } + }}, + "data": { + "image_shape": [480, 640], + "normalization": "imagenet", + "num_copies": 2, + "num_frames": 1, + "sampling":{ + "Waymo": 1.0, + "ETH3D": 1.0 + }, + "train_datasets": [ + "ETH3D", + "Waymo" + ], + "val_datasets": [ + "IBims" + ], + "data_root": "datasets", + "crop": "garg", + "augmentations": { + "random_scale": 2.0, + "random_jitter": 0.4, + "jitter_p": 0.8, + "random_blur": 2.0, + "blur_p": 0.2, + "random_gamma": 0.2, + "gamma_p": 0.8, + "grayscale_p": 0.2, + "flip_p": 0.5, + "test_context": 1.0, + "shape_constraints": { + "ratio_bounds": [0.5, 2.5], + "pixels_max": 600000, + "pixels_min": 200000, + "height_min": 15, + "width_min": 15, + "shape_mult": 14, + "sample": true + } + } + }, + "model": { + "name": "UniDepthV2", + "num_heads": 8, + "expansion": 4, + "layer_scale": 1.0, + "pixel_decoder": { + "name": "Decoder", + "hidden_dim": 256, + "dropout": 0.0, + "depths": [2, 2, 2], + "out_dim": 32, + "kernel_size": 3 + }, + "pixel_encoder": { + "lr": 2e-06, + "wd": 0.1, + "name": "dinov2_vits14", + "frozen_stages": 0, + "num_register_tokens": 0, + "use_norm": true, + "freeze_norm": true, + "pretrained": null, + "stacking_fn": "last", + "output_idx": [3, 6, 9, 12] + } + } +} \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/configs/config_v2old_vitl14.json b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/configs/config_v2old_vitl14.json new file mode 100644 index 0000000000000000000000000000000000000000..88ce8d0e7c91a489c2485b1bc18c6c2bb0861fc2 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/configs/config_v2old_vitl14.json @@ -0,0 +1,32 @@ +{ + "generic": { + "seed": 13, + "deterministic": true + }, + "training": {}, + "data": { + "image_shape": [420, 560], + "shape_constraints": { + "ratio_bounds": [0.66, 2.0], + "pixels_bounds": [1400, 2400], + "patch_size": 14 + } + }, + "model": { + "name": "UniDepthV2old", + "num_heads": 8, + "expansion": 4, + "pixel_decoder": { + "hidden_dim": 512, + "depths": [6, 0, 0], + "dropout": 0.0 + }, + "pixel_encoder": { + "name": "dinov2_vitl14", + "pretrained": null, + "use_norm": true, + "stacking_fn": "last", + "output_idx": [21,22,23,24] + } + } +} \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/configs/config_v2old_vits14.json b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/configs/config_v2old_vits14.json new file mode 100644 index 0000000000000000000000000000000000000000..3efc6655802dc704a254a3af6f0546baf74cff31 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/configs/config_v2old_vits14.json @@ -0,0 +1,32 @@ +{ + "generic": { + "seed": 13, + "deterministic": true + }, + "training": {}, + "data": { + "image_shape": [420, 560], + "shape_constraints": { + "ratio_bounds": [0.66, 2.0], + "pixels_bounds": [1400, 2400], + "patch_size": 14 + } + }, + "model": { + "name": "UniDepthV2old", + "num_heads": 8, + "expansion": 4, + "pixel_decoder": { + "hidden_dim": 512, + "depths": [6, 0, 0], + "dropout": 0.0 + }, + "pixel_encoder": { + "name": "dinov2_vits14", + "pretrained": null, + "use_norm": true, + "stacking_fn": "last", + "output_idx": [9,10,11,12] + } + } +} \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/configs/train_v1_vitl14.json b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/configs/train_v1_vitl14.json new file mode 100644 index 0000000000000000000000000000000000000000..9ebe3a7967ddcf799574bfefd60d5662b7517c6b --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/configs/train_v1_vitl14.json @@ -0,0 +1,113 @@ +{ + "generic": { + "seed": 13, + "deterministic": true + }, + "training": { + "n_iters": 300000, + "batch_size": 8, + "validation_interval": 1000, + "nsteps_accumulation_gradient": 2, + "use_checkpoint": false, + "lr": 1e-4, + "lr_final": 1e-6, + "lr_warmup": 1.0, + "cycle_beta": false, + + "wd": 0.1, + "wd_final": 0.1, + "warmup_iters": 75000, + "ld": 1.0, + + "drop_path": 0.0, + "ema": true, + "f16": true, + "clipping": 1.0, + "losses": { + "depth": { + "name": "SILog", + "weight": 1.0, + "output_fn": "sqrt", + "input_fn": "log", + "dims": [-2,-1], + "integrated": 0.15 + }, + "invariance": { + "name": "SelfDistill", + "weight": 0.1, + "output_fn": "sqrt" + }, + "camera": { + "name": "Regression", + "weight": 0.25, + "gamma": 1.0, + "alpha": 1.0, + "fn": "l2", + "output_fn": "sqrt", + "input_fn": "linear" + } + }}, + "data": { + "image_shape": [480, 640], + "normalization": "imagenet", + "num_copies": 2, + "num_frames": 1, + "sampling":{ + "Taskonomy": 1.0, + "DrivingStereo": 1.0, + "Cityscape": 1.0, + "Mapillary": 1.0, + "ScanNet": 1.0, + "Waymo": 1.0, + "Argoverse2": 1.0 + }, + "train_datasets": [ + "ScanNet", + "Waymo", + "Argoverse2" + ], + "val_datasets": [ + "IBims" + ], + "data_root": "datasets", + "crop": "garg", + "augmentations": { + "random_scale": 2.0, + "random_jitter": 0.4, + "jitter_p": 0.8, + "random_blur": 2.0, + "blur_p": 0.2, + "random_gamma": 0.2, + "gamma_p": 0.8, + "grayscale_p": 0.2, + "flip_p": 0.5, + "test_context": 1.0, + "shape_constraints": { + "ratio_bounds": [0.66, 2.0], + "pixels_max": 200000, + "pixels_min": 400000, + "height_min": 15, + "width_min": 15, + "shape_mult": 14, + "sample": true + } + } + }, + "model": { + "name": "UniDepthV1", + "num_heads": 8, + "expansion": 4, + "pixel_decoder": { + "hidden_dim": 512, + "depths": [3, 2, 1], + "dropout": 0.0 + }, + "pixel_encoder": { + "name": "dinov2_vitl14", + "norm": true, + "pretrained": "", + "lr": 1e-5, + "frozen_stages": 0 + } + } +} \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/hubconf.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/hubconf.py new file mode 100644 index 0000000000000000000000000000000000000000..606dce6e529405aaa09e71be2bef62a8c2ee10fb --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/hubconf.py @@ -0,0 +1,41 @@ +dependencies = ["torch", "huggingface_hub"] + +import os +import json + +import torch +import huggingface_hub + +from unidepth.models import UniDepthV1, UniDepthV2, UniDepthV2old + + +MAP_VERSIONS = { + "v1": UniDepthV1, + "v2": UniDepthV2, + "v2old": UniDepthV2old +} + +BACKBONES = { + "v1": ["vitl14", "cnvnxtl"], + "v2": ["vitl14", "vitb14", "vits14"], + "v2old": ["vitl14", "vits14"] +} + + +def UniDepth(version="v2", backbone="vitl14", pretrained=True): + assert version in MAP_VERSIONS.keys(), f"version must be one of {list(MAP_VERSIONS.keys())}" + assert backbone in BACKBONES[version], f"backbone for current version ({version}) must be one of {list(BACKBONES[version])}" + repo_dir = os.path.dirname(os.path.realpath(__file__)) + with open(os.path.join(repo_dir, "configs", f"config_{version}_{backbone}.json")) as f: + config = json.load(f) + + model = MAP_VERSIONS[version](config) + if pretrained: + path = huggingface_hub.hf_hub_download(repo_id=f"lpiccinelli/unidepth-{version}-{backbone}", filename=f"pytorch_model.bin", repo_type="model") + info = model.load_state_dict(torch.load(path), strict=False) + print(f"UniDepth_{version}_{backbone} is loaded with:") + print(f"\t missing keys: {info.missing_keys}") + print(f"\t additional keys: {info.unexpected_keys}") + + return model + diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/pyproject.toml b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..8ad738c9faac0b64df9b5785488588dbf19cc49b --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/pyproject.toml @@ -0,0 +1,25 @@ +[build-system] +requires = ["setuptools"] +build-backend = "setuptools.build_meta" + +[tool.pyright] +include = ["unidepth"] + +[project] +name = "unidepth" +version = "0.1" +authors = [{name = "Luigi Piccinelli", email = "lpiccinelli@ethz.ch"}] +description = "UniDepth: Universal Monocular Metric Depth Estimation" +readme = "README.md" +license = { text="Creatives Common BY-NC 4.0 license"} +requires-python = ">=3.10.0" +dynamic = ["dependencies"] + +[tool.setuptools.dynamic] +dependencies = {file = ["requirements.txt"]} + +[tool.setuptools.package-data] +"*" = ["py.typed"] + +[tool.setuptools.packages.find] +include = ["unidepth*"] diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/requirements.txt b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..3fe9a9a1da48f99e4357d028aaf14738c94607f2 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/requirements.txt @@ -0,0 +1,19 @@ +einops>=0.7.0 +gradio +h5py>=3.10.0 +huggingface-hub>=0.22.0 +imageio +matplotlib +# numpy>=2.0.0 +opencv-python +pandas +pillow>=10.2.0 +protobuf>=4.25.3 +scipy +tables +tabulate +termcolor +timm +tqdm +trimesh +wandb \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/scripts/README.md b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/scripts/README.md new file mode 100644 index 0000000000000000000000000000000000000000..939b416f14ceec9bc98f1e6dfd88369cc3ad521a --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/scripts/README.md @@ -0,0 +1,57 @@ +## Training + +We provide the `train.py` script that allows to load the dataset, initialize and start the training. From the root of the repo: + +```bash +export REPO=`pwd` +export PYTHONPATH=${REPO}:${PYTHONPATH} + +# Adapt all this to your setup +export TMPDIR="/tmp" +export TORCH_HOME=${TMPDIR} +export HUGGINGFACE_HUB_CACHE=${TMPDIR} +export WANDB_HOME=${TMPDIR} +export DATAROOT= + + +export MASTER_PORT=$((( RANDOM % 600 ) + 29400 )) +if [ $NNODES -gt 1 ]; then + export MASTER_PORT=29400 +fi + +# this is the config will be used +export CFG="train_v1_vitl14.json" +``` + +If you are on a machine without SLURM you can run the following: +```bash +# make the following input-dependent for multi-node +export NNODES=1 +export RANK=0 +export MASTER_ADDR=127.0.0.1 +export CUDA_VISIBLE_DEVICES="0" # set yours + +export GPUS=$(echo ${CUDA_VISIBLE_DEVICES} | tr ',' '\n' | wc -l) +echo "Start script with python from: `which python`" +torchrun --rdzv-backend=c10d --nnodes=${NNODES} --nproc_per_node=${GPUS} --rdzv-endpoint ${MASTER_ADDR}:${MASTER_PORT} ${REPO}/scripts/train.py --config-file ${REPO}/configs/${CFG} --distributed +``` + +If you system present SLURM, all the information will be set by the scheduler and you have to run just: +```bash +srun -c ${SLURM_CPUS_PER_TASK} --kill-on-bad-exit=1 python -u ${REPO}/scripts/train.py --config-file ${REPO}/configs/${CFG} --master-port ${MASTER_PORT} --distributed +``` + +The training is available only for V1.
    +We have changes in the upcomping month for V2 and its "trainable model code" will be made public then. + + +### Datasets + +We used both image-based and sequence-based dataset. The `ImageDataset` class is actually for legacy only as we moved image-based dataset to be "dummy" single-frame sequences.
    +We [provide two example dataset to get familiar to the pipeline and structure, namely iBims-1 and Sintel](https://drive.google.com/drive/folders/1FKsa5-b3EX0ukZq7bxord5fC5OfUiy16?usp=sharing), image- and sequence-based, respectively.
    +You can adapt the data loading and processing to your example; however, you will need to keep the same interface for the model to be consisten and train "out-of-the-box" the model.
    + + +### Additional dependencies + +We require chamfer distance for the evaluation, hence we rely on Pytorch3D knn, if you find any issue with Pytorch3D installation, you can compile the knn operation under `ops/knn`: `bash compile.sh` from the directory `$REPO/unidepth/ops/knn`. \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/scripts/demo.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/scripts/demo.py new file mode 100644 index 0000000000000000000000000000000000000000..5c97ca2c279e08b992503c52680b4724914e63d5 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/scripts/demo.py @@ -0,0 +1,59 @@ +import numpy as np +import torch +from PIL import Image + +from unidepth.models import UniDepthV1, UniDepthV2, UniDepthV2old +from unidepth.utils import colorize, image_grid +from unidepth.utils.camera import Pinhole + + +def demo(model): + rgb = np.array(Image.open("assets/demo/rgb.png")) + rgb_torch = torch.from_numpy(rgb).permute(2, 0, 1) + intrinsics_torch = torch.from_numpy(np.load("assets/demo/intrinsics.npy")) + camera = Pinhole(K=intrinsics_torch.unsqueeze(0)) + + # infer method of V1 uses still the K matrix as input + if isinstance(model, (UniDepthV2old, UniDepthV1)): + camera = camera.K.squeeze(0) + + # predict + predictions = model.infer(rgb_torch, camera) + + # get GT and pred + depth_pred = predictions["depth"].squeeze().cpu().numpy() + depth_gt = np.array(Image.open("assets/demo/depth.png")).astype(float) / 1000.0 + + # compute error, you have zero divison where depth_gt == 0.0 + depth_arel = np.abs(depth_gt - depth_pred) / depth_gt + depth_arel[depth_gt == 0.0] = 0.0 + + # colorize + depth_pred_col = colorize(depth_pred, vmin=0.01, vmax=10.0, cmap="magma_r") + depth_gt_col = colorize(depth_gt, vmin=0.01, vmax=10.0, cmap="magma_r") + depth_error_col = colorize(depth_arel, vmin=0.0, vmax=0.2, cmap="coolwarm") + + # save image with pred and error + artifact = image_grid([rgb, depth_gt_col, depth_pred_col, depth_error_col], 2, 2) + Image.fromarray(artifact).save("assets/demo/output.png") + + print("Available predictions:", list(predictions.keys())) + print(f"ARel: {depth_arel[depth_gt > 0].mean() * 100:.2f}%") + + +if __name__ == "__main__": + print("Torch version:", torch.__version__) + type_ = "l" # available types: s, b, l + name = f"unidepth-v2-vit{type_}14" + model = UniDepthV2.from_pretrained(f"lpiccinelli/{name}") + + # set resolution level (only V2) + # model.resolution_level = 9 + + # set interpolation mode (only V2) + model.interpolation_mode = "bilinear" + + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + model = model.to(device).eval() + + demo(model) diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/scripts/depth_vis_batch.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/scripts/depth_vis_batch.py new file mode 100644 index 0000000000000000000000000000000000000000..1a1c69e45ee4aae2c3e9f862f1392a60be97f352 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/scripts/depth_vis_batch.py @@ -0,0 +1,25 @@ +import os +import cv2 +import numpy as np +import sys +sys.path.append("./scripts") +from utils import depth_to_vis +import argparse + +parser = argparse.ArgumentParser() +parser.add_argument('--depth_dir', type=str, default='/path/to/unidepth/outputs/gso_30/depth') +parser.add_argument('--output_dir', type=str, default='/path/to/unidepth/outputs/gso_30/depth_vis') +args = parser.parse_args() + +os.makedirs(args.output_dir, exist_ok=True) + +depth_files = os.listdir(args.depth_dir) + +for depth_file in depth_files: + depth = cv2.imread(os.path.join(args.depth_dir, depth_file), cv2.IMREAD_ANYDEPTH) + H,W = depth.shape[:2] + zmin = depth.min() + zmax = depth.max() + + depth_vis = depth_to_vis(depth, zmin=zmin, zmax=zmax, inverse=False, mode='gray') + cv2.imwrite(os.path.join(args.output_dir, depth_file), depth_vis) diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/scripts/inference.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/scripts/inference.py new file mode 100644 index 0000000000000000000000000000000000000000..cd581c9c8eb484acfbf9771ee8cb8f6117571192 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/scripts/inference.py @@ -0,0 +1,55 @@ +from unidepth.models import UniDepthV1 +import numpy as np +from PIL import Image +import torch +import os +import argparse + +def parse_args(): + parser = argparse.ArgumentParser() + parser.add_argument("--image_path", type=str, required=True) + parser.add_argument("--output_dir", type=str, required=True) + parser.add_argument("--ckpt_root_dir", type=str, required=True) + return parser.parse_args() + +if __name__ == "__main__": + args = parse_args() + image_path = args.image_path + output_dir = args.output_dir + model = UniDepthV1.from_pretrained(os.path.join(args.ckpt_root_dir, "data_preprocessing")) # or "lpiccinelli/unidepth-v1-cnvnxtl" for the ConvNext backbone + + output_dir = os.path.join(output_dir, "foundationpose_inputs") + + # Move to CUDA, if any + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + model = model.to(device) + + # Load the RGB image and the normalization will be taken care of by the model + rgb = torch.from_numpy(np.array(Image.open(image_path)))[..., :3].permute(2, 0, 1) # C, H, W + + predictions = model.infer(rgb) + + # Metric Depth Estimation + depth = predictions["depth"] + + # Point Cloud in Camera Coordinate + xyz = predictions["points"] + + # Intrinsics Prediction + intrinsics = predictions["intrinsics"] + + # Save the depth map + depth_map = (depth.squeeze().cpu().numpy() * 1000.0).astype(np.uint16) + image_name = image_path.split("/")[-1] + depth_output_path = os.path.join(output_dir, 'depth') + os.makedirs(depth_output_path, exist_ok=True) + Image.fromarray(depth_map).save(os.path.join(depth_output_path, image_name)) + + # Save the intrinsics + cam_K_output_path = output_dir + with open(os.path.join(cam_K_output_path, "cam_K.txt"), "w") as f: + f.write("%f %f %f\n" % (intrinsics[0, 0, 0], intrinsics[0, 0, 1], intrinsics[0, 0, 2])) + f.write("%f %f %f\n" % (intrinsics[0, 1, 0], intrinsics[0, 1, 1], intrinsics[0, 1, 2])) + f.write("%f %f %f\n" % (intrinsics[0, 2, 0], intrinsics[0, 2, 1], intrinsics[0, 2, 2])) + + diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/scripts/train.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/scripts/train.py new file mode 100644 index 0000000000000000000000000000000000000000..b3440af0115a9e4b8ab770aa660712e3aeb45442 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/scripts/train.py @@ -0,0 +1,561 @@ +import argparse +import json +import os +import random +import uuid +from contextlib import nullcontext +from datetime import datetime as dt +from functools import partial +from time import time +from typing import Any, Dict + +import git +import numpy as np +import psutil +import torch +import torch.nn as nn +import torch.utils.data.distributed +import wandb +from torch import distributed as dist +from torch import optim +from torch.nn.parallel.distributed import DistributedDataParallel +from torch.utils.data import DataLoader, RandomSampler, SequentialSampler +from tqdm import tqdm + +import unidepth.datasets as datasets +from unidepth.datasets import (ConcatDataset, DistributedSamplerNoDuplicate, + collate_fn, get_weights) +from unidepth.models import UniDepthV1, UniDepthV2 +from unidepth.ops.scheduler import CosineScheduler +from unidepth.utils.distributed import (barrier, create_local_process_group, + is_main_process, + local_broadcast_process_authkey, + setup_multi_processes, setup_slurm, + sync_string_across_gpus, + sync_tensor_across_gpus) +from unidepth.utils.ema_torch import (DummyExponentialMovingAverage, + ExponentialMovingAverage) +from unidepth.utils.misc import calculate_mean_values, format_seconds +from unidepth.utils.validation import validate + +EMA_INTERVAL = 10 + + +def aggregate_sync_losses(dict_: dict[str, torch.Tensor], device): + keys = list(dict_.keys()) + values = torch.tensor(list(dict_.values()), device=device) + keys = sync_string_across_gpus(keys, device) + values = sync_tensor_across_gpus(values, dim=0).cpu().tolist() + dict_ = calculate_mean_values(keys, values) + return dict_ + + +def main_worker(config: Dict[str, Any], args: argparse.Namespace): + + current_process = psutil.Process(os.getpid()) + device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") + seed = config["generic"]["seed"] + + if not args.distributed: + args.rank = 0 + args.local_rank = 0 + args.world_size = 1 + else: + # initializes the distributed backend which will take care of synchronizing nodes/GPUs + setup_multi_processes(config) + is_slurm = "SLURM_PROCID" in os.environ + if is_slurm: + setup_slurm("nccl", port=args.master_port) + args.rank = int(os.environ["RANK"]) + args.world_size = int(os.environ["WORLD_SIZE"]) + args.local_rank = device = int(os.environ["LOCAL_RANK"]) + if not is_slurm: + dist.init_process_group("nccl", rank=args.rank, world_size=args.world_size) + torch.cuda.set_device(device) + create_local_process_group() + local_broadcast_process_authkey() + print( + f"Start running DDP on: {args.rank} (local: {args.local_rank}) with seed {seed + args.rank}." + ) + config["training"]["batch_size"] = int( + config["training"]["batch_size"] / args.world_size + ) + dist.barrier() + + # Fix seed + # Different for every machine to avoid sampling + # the same element across machines + seed = seed + args.rank + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed(seed) + torch.cuda.manual_seed_all(seed) + os.environ["PYTHONHASHSEED"] = str(seed) + + batch_size = config["training"]["batch_size"] + if is_main_process(): + print("Config: ", args.config_file) + print( + f"Torch version:{torch.__version__}, cuda:{torch.version.cuda}, cudnn:{torch.backends.cudnn.version()}, threads:{torch.get_num_threads()}" + ) + print("BatchSize per GPU: ", batch_size) + print( + f"Divided into {config['training']['nsteps_accumulation_gradient']} accumulation step" + ) + + ############################## + ########### MODEL ############ + ############################## + # Build model + model = eval(config["model"]["name"])(config).to(device) + model.eval() + print(f"MODEL: {model.__class__.__name__} at {model.device}") + torch.cuda.empty_cache() + if args.distributed: + model = nn.SyncBatchNorm.convert_sync_batchnorm(model) + # Before setting find_unused_parameters=True, be sure no gradient checkpointing is on + # => DDP with double pass (unused params) is incompatible with gradient checkpointing + # My guess: CheckpointFunction does not have a pointer pointing to the original model + # params (?), so DDP Reducer will treat those model parameters as unused, and mark them + # as ready. Later, when the forward-backward is run within CheckpointFunction, those + # parameters will be marked as ready again, which can also trigger this error. + + # Possible workaround (not sure at all): + # with model.no_sync(): + # model(inputs).backward() + # works = [dist.all_reduce(p.grad, async_op=True) for p in model.parameters()] # Manual sync + # ideally one can organize grads to larger buckets to make allreduce more efficient + # for work in works: + # work.wait() + model = DistributedDataParallel( + model, + find_unused_parameters=False, + device_ids=[device], + output_device=device, + ) + + ############################## + ######### OPTIMIZER ########## + ############################## + f16 = config["training"].get("f16", False) + clipping = config["training"].get("clipping", None) + + # Optimize + ddp_model = model.module if args.distributed else model + params = ddp_model.get_params(config) + optimizer = optim.AdamW(params) + + # Load Model: + step = 0 + if config["training"].get("pretrained", None) is not None: + ddp_model.load_pretrained(config["training"]["pretrained"]) + pretrained = torch.load( + config["training"]["pretrained"], map_location="cpu", weights_only=False + ) + try: + optimizer.load_state_dict(pretrained["optimizer"]) + except Exception as e: + if is_main_process(): + print("Could not load optimizer state dict:", e) + step = pretrained.get("step", step) + + # EMA + ema_class = ( + ExponentialMovingAverage + if config["training"]["ema"] + else DummyExponentialMovingAverage + ) + ema_handle = ema_class( + model.parameters(), + 1 - (1 - 0.9995) * EMA_INTERVAL, + update_after_step=75000 // EMA_INTERVAL, + tau=20000 // EMA_INTERVAL, + ) + setattr(ema_handle, "num_updates", step // EMA_INTERVAL) + + ############################## + ######### GENERICS ########### + ############################## + resize_method = config["data"].get("resize_method", "hard") + crop = config["data"].get("crop", "garg") + augmentations_db = config["data"].get("augmentations", {}) + image_shape = config["data"]["image_shape"] + nsteps_accumulation_gradient = config["training"]["nsteps_accumulation_gradient"] + batch_size = config["training"]["batch_size"] // config["data"]["num_copies"] + + is_shell = int(os.environ.get("SHELL_JOB", 0)) + run_id = sync_string_across_gpus( + [f"{dt.now().strftime('%d-%h_%H-%M')}-{uuid.uuid4()}"], device + )[0] + + if not is_shell and is_main_process(): + repo_folder = os.path.dirname(os.path.realpath(__file__)) + try: + repo = git.Repo(repo_folder) + current_head = repo.head if repo.head.is_detached else repo.active_branch + notes = f"MESSAGE: {current_head.commit.message} HASH:{current_head.commit.hexsha} BRANCH:{current_head.name}" + except Exception as e: + print( + f"problem with {repo_folder}, does it exist? (original excpetion: {e})" + ) + notes = "" + + # restore the original batchsize, not acquired by other calls from now on + if args.distributed: + config["training"]["batch_size"] = ( + config["training"]["batch_size"] + * args.world_size + * config["data"]["num_copies"] + ) + wandb.init( + project="UniDepth", + name=run_id, + config=config, + tags=None, + notes=notes, + dir=os.environ.get("WANDB_HOME", os.environ.get("TMPDIR", "/tmp")), + ) + wandb.watch(model) + + ############################## + ########## DATASET ########### + ############################## + # Datasets loading + train_datasets, val_datasets, dims = {}, {}, 0 + if is_main_process(): + print("Loading training datasets...") + for dataset in config["data"]["train_datasets"]: + assert hasattr(datasets, dataset), f"{dataset} not a custom dataset" + train_dataset: datasets.BaseDataset = getattr(datasets, dataset) + train_datasets[dataset] = train_dataset( + image_shape=image_shape, + split_file=train_dataset.train_split, + test_mode=False, + crop=crop, + augmentations_db=augmentations_db, + normalize=config["data"].get("normalization", "imagenet"), + resize_method=resize_method, + mini=1.0, + num_copies=config["data"]["num_copies"], + num_frames=1, + fps_range=[1, 30], + ) + dim = ( + train_datasets[dataset].dataset._addr.numel() * 8 + + train_datasets[dataset].dataset._lst.numel() + ) / (2**20) + if hasattr(train_datasets[dataset], "sequences"): + dim += ( + train_datasets[dataset].sequences._addr.numel() * 8 + + train_datasets[dataset].sequences._lst.numel() + ) / (2**20) + if is_main_process(): + print(f"{dataset}: {dim:.1f}MB") + dims += dim + + if is_main_process(): + print(f"All training datasets loaded, with total size: {dims:.1f}MB") + + barrier() + + assert batch_size % nsteps_accumulation_gradient == 0 + batch_chunk = batch_size // nsteps_accumulation_gradient + + train_dataset = ConcatDataset( + [t for t in train_datasets.values()], + shape_constraints=config["data"]["augmentations"]["shape_constraints"], + ) + + if is_main_process(): + print("Loading validation datasets...") + for dataset in config["data"]["val_datasets"]: + val_dataset: datasets.BaseDataset = getattr(datasets, dataset) + val_datasets[dataset] = val_dataset( + image_shape=image_shape, + split_file=val_dataset.test_split, + test_mode=True, + crop=crop, + augmentations_db=augmentations_db, + normalize=config["data"].get("normalization", "imagenet"), + resize_method=resize_method, + num_frames=1, + mini=1.0, + ) + + # Dataset samplers, create distributed sampler pinned to rank + if args.distributed: + weights, num_samples = get_weights(train_datasets, config["data"]["sampling"]) + train_sampler = torch.utils.data.WeightedRandomSampler( + weights, num_samples, replacement=True + ) + valid_samplers = { + k: DistributedSamplerNoDuplicate( + v, + num_replicas=args.world_size, + rank=args.rank, + shuffle=False, + drop_last=False, + ) + for k, v in val_datasets.items() + } + else: + train_sampler = RandomSampler(train_dataset) + valid_samplers = {k: SequentialSampler(v) for k, v in val_datasets.items()} + + train_sampler = torch.utils.data.BatchSampler( + train_sampler, batch_size=batch_size, drop_last=True + ) + + # DATASET LOADERS + val_batch_size = 1 + num_workers = 0 # int(os.environ.get("SLURM_CPUS_PER_TASK", 4)) + train_loader = DataLoader( + train_dataset, + num_workers=num_workers, + sampler=train_sampler, + pin_memory=True, + collate_fn=partial(collate_fn, is_batched=True), + persistent_workers=num_workers > 0, + ) + val_loaders = { + name_dataset: DataLoader( + dataset, + batch_size=val_batch_size, + shuffle=False, + num_workers=num_workers, + sampler=valid_samplers[name_dataset], + pin_memory=True, + drop_last=False, + collate_fn=partial(collate_fn, is_batched=False), + ) + for name_dataset, dataset in val_datasets.items() + } + + # SCHEDULERS + scheduler_wd = CosineScheduler( + optimizer, + key="weight_decay", + init_value=config["training"]["wd"], + base_value=config["training"]["wd"], + final_value=config["training"]["wd_final"], + warmup_iters=0, + total_iters=config["training"]["n_iters"], + step_init=step - 1, + ) + scheduler_lr = CosineScheduler( + optimizer, + key="lr", + init_value=config["training"]["lr"] * config["training"].get("lr_warmup", 1.0), + final_value=config["training"]["lr_final"], + warmup_iters=config["training"]["warmup_iters"], + total_iters=config["training"]["n_iters"], + step_init=step - 1, + ) + scheduler_betas = CosineScheduler( + optimizer, + key="betas", + init_value=0.95 if config["training"].get("cycle_betas", True) else 0.9, + base_value=0.85 if config["training"].get("cycle_betas", True) else 0.9, + final_value=0.95 if config["training"].get("cycle_betas", True) else 0.9, + warmup_iters=config["training"]["warmup_iters"], + total_iters=config["training"]["n_iters"], + step_init=step - 1, + ) + + # Set loss scaler for half precision training + sanity zeroing grads + # dtype = torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16 + dtype = torch.float16 # bfloat has some issue in terms of resolution... + context = torch.autocast(device_type="cuda", dtype=dtype, enabled=f16) + optimizer.zero_grad(set_to_none=True) + + ############################## + ########## TRAINING ########## + ############################## + # Remember that if i-th layer is frozen, this will break gradient checkpointing + # in layer i+1-th. This is because CheckpointFunction treats the i+1-th input as + # without gradient, thus the i+1-th layer does not have grads (?). To solve it, + # just add requires_grad_() to the inputs coming from the frozen layer + ddp_model.train() + start = time() + n_steps = config["training"]["n_iters"] + init_steps = int(step) + track_pbar = is_shell + + if is_main_process(): + print("Is a shell job?", is_shell) + print("Use dtype:", dtype if f16 else torch.float32) + print( + f'Train for {config["training"]["n_iters"]} steps, validate every {config["training"]["validation_interval"]} steps' + ) + print(f"START with {num_workers} workers") + if track_pbar: + pbar = tqdm(total=n_steps - init_steps) + + scaler = torch.amp.GradScaler("cuda", enabled=f16) + track_losses = {} + system_memory = dict(psutil.virtual_memory()._asdict())["available"] / 2**30 + cpid_memory = current_process.memory_info()[0] / 2.0**30 + gpu_mem = (torch.cuda.mem_get_info()[1] - torch.cuda.mem_get_info()[0]) / 2**30 + + while True: + for j, batches in enumerate(train_loader): + + system_memory = ( + 0.99 * system_memory + + 0.01 * dict(psutil.virtual_memory()._asdict())["available"] / 2**30 + ) + cpid_memory = ( + 0.99 * cpid_memory + 0.01 * current_process.memory_info()[0] / 2.0**30 + ) + gpu_mem = ( + 0.99 * gpu_mem + + 0.01 + * (torch.cuda.mem_get_info()[1] - torch.cuda.mem_get_info()[0]) + / 2**30 + ) + if j % 1000 == 0 and is_main_process(): + print(f"System information at step {j}") + print(f"System-wide RAM available: {system_memory:.2f}GB") + print(f"CPU utilization: {psutil.cpu_percent(interval=None)}%") + print(f"GPU memory utilized: {gpu_mem:.2f}GB") + + batches["data"] = { + k: v.to(model.device, non_blocking=True) + for k, v in batches["data"].items() + } + for idx in range(nsteps_accumulation_gradient): + batch = {} + batch_slice = slice(idx * batch_chunk, (idx + 1) * batch_chunk) + batch["data"] = {k: v[batch_slice] for k, v in batches["data"].items()} + batch["img_metas"] = batches["img_metas"][batch_slice] + + # remove temporal dimension of the dataloder, here is always 1!! + batch["data"] = { + k: torch.flatten(v, 0, 1) for k, v in batch["data"].items() + } + batch["img_metas"] = [ + {k: v for k, v in meta.items() if isinstance(v, list)} + for meta in batch["img_metas"] + ] + + with ( + model.no_sync() + if idx < nsteps_accumulation_gradient - 1 + else nullcontext() + ): + with context: + preds, losses = model(batch["data"], batch["img_metas"]) + loss = sum(losses["opt"].values()) / nsteps_accumulation_gradient + scaler.scale(loss).backward() + + losses_dict = { + k: v.detach() for loss in losses.values() for k, v in loss.items() + } + track_losses.update( + { + k: 0.99 * track_losses.get(k, v) + + 0.01 * torch.nan_to_num(v, nan=1e5, posinf=1e5, neginf=1e5) + for k, v in losses_dict.items() + } + ) + + if clipping is not None: + scaler.unscale_(optimizer) + torch.nn.utils.clip_grad_norm_(model.parameters(), clipping) + + scaler.step(optimizer) + scaler.update() + + scheduler_wd.step() + scheduler_lr.step() + scheduler_betas.step() + optimizer.zero_grad(set_to_none=True) + if step % EMA_INTERVAL == 0: + ema_handle.update() + + if is_main_process() and track_pbar: + pbar.update(1) + + step += 1 + + # LOGGING + if step % 50 == 0: + track_losses = aggregate_sync_losses(track_losses, device=model.device) + if is_main_process(): + try: + wandb.log( + { + **{f"Train/{k}": v for k, v in track_losses.items()}, + **{f"Train/lr": scheduler_lr.get()[-1]}, + **{f"Train/wd": scheduler_wd.get()[-2]}, + **{f"Train/scale_f16": scaler.get_scale()}, + }, + step=step, + ) + except Exception as e: + print("Not logging loss because of:", e) + pass + + if step % 100 == 0 and is_main_process(): + log_loss_dict = {f"Train/{k}": v for k, v in track_losses.items()} + elapsed = int(time() - start) + eta = int(elapsed * (n_steps - step) / max(1, step - init_steps)) + print( + f"Loss at {step}/{n_steps} [{format_seconds(elapsed)}<{format_seconds(eta)}]:" + ) + print(", ".join([f"{k}: {v:.5f}" for k, v in log_loss_dict.items()])) + + # Validation + is_last_step = step >= config["training"]["n_iters"] + is_validation = step % config["training"]["validation_interval"] == 0 + if is_last_step or is_validation: + torch.cuda.empty_cache() + barrier() + if is_main_process(): + print(f"Validation at {step}th step...") + + ddp_model.eval() + start_validation = time() + with torch.no_grad(), ema_handle.average_parameters(): + validate( + model, test_loaders=val_loaders, step=step, context=context + ) + + if is_main_process(): + print(f"Elapsed: {format_seconds(int(time() - start_validation))}") + ddp_model.train() + torch.cuda.empty_cache() + + if step >= config["training"]["n_iters"]: + if is_main_process() and track_pbar: + pbar.close() + wandb.finish(0) + dist.destroy_process_group() + return 0 + + +if __name__ == "__main__": + # dummy folder to avoid Triton conflicts on multi-node training with slurm + if "SLURM_PROCID" in os.environ: + os.environ["TRITON_CACHE_DIR"] = "/tmp" + + parser = argparse.ArgumentParser( + description="Training script", conflict_handler="resolve" + ) + parser.add_argument("--config-file", type=str, required=True) + parser.add_argument("--master-port", type=str) + parser.add_argument("--distributed", action="store_true") + parser.add_argument("--local_rank", type=int, default=0) + + args = parser.parse_args() + with open(args.config_file, "r") as f: + config = json.load(f) + + deterministic = config["generic"].get("deterministic", True) + torch.backends.cudnn.deterministic = deterministic + torch.backends.cudnn.benchmark = not deterministic + # set to false otw f16 + efficient memory is not really efficient... i.e. mem is greater than with + torch.backends.cuda.enable_mem_efficient_sdp(False) + torch.set_num_threads(1) + main_worker(config, args) diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/scripts/utils.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/scripts/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..14d5412ac4408b919c8e25e018a8f4e7f429bf3a --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/scripts/utils.py @@ -0,0 +1,28 @@ +import cv2 +import numpy as np + + +def depth_to_vis(depth, zmin=None, zmax=None, mode='rgb', inverse=True): + if zmin is None: + zmin = depth.min() + if zmax is None: + zmax = depth.max() + + if inverse: + invalid = depth<0.001 + vis = zmin/(depth+1e-8) + vis[invalid] = 0 + else: + depth = depth.clip(zmin, zmax) + invalid = (depth==zmin) | (depth==zmax) + vis = (depth-zmin)/(zmax-zmin) + vis[invalid] = 1 + + if mode=='gray': + vis = (vis*255).clip(0, 255).astype(np.uint8) + elif mode=='rgb': + vis = cv2.applyColorMap((vis*255).astype(np.uint8), cv2.COLORMAP_JET)[...,::-1] + else: + raise RuntimeError + + return vis \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/_2d3ds.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/_2d3ds.py new file mode 100644 index 0000000000000000000000000000000000000000..1599cccf0ff75e9dc594f3e61fae7a5b3049249a --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/_2d3ds.py @@ -0,0 +1,67 @@ +from typing import Any + +import torch + +from unidepth.datasets.pipelines import Compose, PanoCrop, PanoRoll +from unidepth.datasets.sequence_dataset import SequenceDataset + + +class _2D3DS(SequenceDataset): + min_depth = 0.01 + max_depth = 10.0 + depth_scale = 512.0 + test_split = "train.txt" + train_split = "train.txt" + sequences_file = "sequences.json" + hdf5_paths = [f"2D3DS.hdf5"] + + def __init__( + self, + image_shape: tuple[int, int], + split_file: str, + test_mode: bool, + normalize: bool, + augmentations_db: dict[str, Any], + resize_method: str, + mini: float = 1.0, + num_frames: int = 1, + benchmark: bool = False, + decode_fields: list[str] = ["image", "depth"], + inplace_fields: list[str] = ["cam2w", "camera_params"], + **kwargs, + ) -> None: + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + num_frames=num_frames, + decode_fields=decode_fields, + inplace_fields=inplace_fields, + **kwargs, + ) + self.resizer = Compose( + [PanoCrop(), PanoRoll(test_mode=test_mode), self.resizer] + ) + + def preprocess(self, results): + self.resizer.ctx = None + if self.test_mode: + for i, seq in enumerate(results["sequence_fields"]): + results[seq]["points"] = results[seq]["camera"].reconstruct( + results[seq]["depth"] + ) + results[seq]["depth"] = results[seq]["points"][:, -1:] + results[seq]["gt_fields"].add("points") + return super().preprocess(results) + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [True] * self.num_frames * self.num_copies + results["synthetic"] = [False] * self.num_frames * self.num_copies + results["quality"] = [1] * self.num_frames * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/_4dor.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/_4dor.py new file mode 100644 index 0000000000000000000000000000000000000000..f38e19c77957e71d440e74208328178a2c71e5df --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/_4dor.py @@ -0,0 +1,52 @@ +from typing import Any + +from unidepth.datasets.sequence_dataset import SequenceDataset + + +class _4DOR(SequenceDataset): + min_depth = 0.01 + max_depth = 10.0 + depth_scale = 1000.0 + default_fps = 10 + test_split = "train.txt" + train_split = "train.txt" + sequences_file = "sequences.json" + hdf5_paths = ["4DOR.hdf5"] + + def __init__( + self, + image_shape: tuple[int, int], + split_file: str, + test_mode: bool, + normalize: bool, + augmentations_db: dict[str, Any], + resize_method: str, + mini: float = 1.0, + num_frames: int = 1, + benchmark: bool = False, + decode_fields: list[str] = ["image", "depth"], + inplace_fields: list[str] = ["camera_params", "cam2w"], + **kwargs, + ) -> None: + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + num_frames=num_frames, + decode_fields=decode_fields, + inplace_fields=inplace_fields, + **kwargs, + ) + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [True] * self.num_frames * self.num_copies + results["synthetic"] = [False] * self.num_frames * self.num_copies + results["si"] = [False] * self.num_frames * self.num_copies + results["quality"] = [2] * self.num_frames * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/__init__.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f3e6bc979219d4566029d6757a2df52119a1a162 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/__init__.py @@ -0,0 +1,77 @@ +from ._2d3ds import _2D3DS +from ._4dor import _4DOR +from .a2d2 import A2D2 +from .adt import ADT +from .aimotive import aiMotive +from .argoverse import Argoverse +from .argoverse2 import Argoverse2 +from .arkit import ARKit +from .ase import ASE +from .base_dataset import BaseDataset +from .bdd import BDD +from .bedlam import BEDLAM +from .behave import Behave +from .blendedmvg import BlendedMVG +from .cityscape import Cityscape +from .ddad import DDAD +from .deep360 import Deep360 +from .dense import DENSE +from .diode import DiodeIndoor, DiodeIndoor_F +from .dl3dv import DL3DV +from .driving_stereo import DrivingStereo +from .dtu_rmvd import DTURMVD +from .dummy import Dummy +from .dynamic_replica import DynReplica +from .eden import EDEN +from .eth3d import ETH3D, ETH3D_F +from .eth3d_rmvd import ETH3DRMVD +from .facedepth import FaceDepth +from .flsea import FLSea +from .futurehouse import FutureHouse +from .gibson import Gibson +from .hammer import HAMMER +from .hm3d import HM3D +from .hoi4d import HOI4D +from .hypersim import HyperSim +from .ibims import IBims, IBims_F +from .image_dataset import ImageDataset +from .ken_burns import KenBurns +from .kitti import KITTI, KITTIBenchmark +from .kitti360 import KITTI360 +from .kitti_multi import KITTIMulti +from .kitti_rmvd import KITTIRMVD +from .lyft import Lyft +from .mapillary import Mapillary +from .matrix_city import MatrixCity +from .matterport3d import Matterport3D +from .megadepth import MegaDepth +from .megadepth_s import MegaDepthS +from .midair import MidAir +from .mip import MIP +from .ms2 import MS2 +from .mvimgnet import MVImgNet +from .mvsynth import MVSynth +from .nerds360 import NeRDS360 +from .niantic_mapfree import NianticMapFree +from .nuscenes import Nuscenes +from .nyuv2 import NYUv2Depth +from .point_odyssey import PointOdyssey +from .proteus import Proteus +from .samplers import DistributedSamplerNoDuplicate +from .scannet import ScanNet +from .scannetpp import ScanNetpp, ScanNetpp_F +from .sequence_dataset import SequenceDataset +from .sintel import Sintel +from .sunrgbd import SUNRGBD +from .synscapes import Synscapes +from .tartanair import TartanAir +from .taskonomy import Taskonomy +from .tat_rmvd import TATRMVD +from .theo import Theo +from .unrealstereo4k import UnrealStereo4K +from .urbansyn import UrbanSyn +from .utils import ConcatDataset, collate_fn, get_weights +from .vkitti import VKITTI +from .void import VOID +from .waymo import Waymo +from .wildrgbd import WildRGBD diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/a2d2.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/a2d2.py new file mode 100644 index 0000000000000000000000000000000000000000..7714fc2be1167bea2119e7a600c97c7466dd7f94 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/a2d2.py @@ -0,0 +1,78 @@ +import json +import os + +import h5py +import numpy as np +import torch + +from unidepth.datasets.image_dataset import ImageDataset +from unidepth.datasets.utils import DatasetFromList + + +class A2D2(ImageDataset): + min_depth = 0.01 + max_depth = 120.0 + depth_scale = 256.0 + train_split = "train_clean.txt" + intrisics_file = "intrinsics.json" + hdf5_paths = ["a2d2.hdf5"] + + def __init__( + self, + image_shape, + split_file, + test_mode, + crop=None, + benchmark=False, + augmentations_db={}, + normalize=True, + resize_method="hard", + mini=1.0, + **kwargs, + ): + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + **kwargs, + ) + self.test_mode = test_mode + self.load_dataset() + + def load_dataset(self): + h5file = h5py.File( + os.path.join(self.data_root, self.hdf5_paths[0]), + "r", + libver="latest", + swmr=True, + ) + txt_file = np.array(h5file[self.split_file]) + txt_string = txt_file.tostring().decode("ascii")[:-1] # correct the -1 + intrinsics = np.array(h5file[self.intrisics_file]).tostring().decode("ascii") + intrinsics = json.loads(intrinsics) + h5file.close() + dataset = [] + for line in txt_string.split("\n"): + image_filename, depth_filename = line.strip().split(" ") + intrinsics_val = torch.tensor( + intrinsics[os.path.join(*image_filename.split("/")[:2])] + ).squeeze()[:, :3] + sample = [image_filename, depth_filename, intrinsics_val] + dataset.append(sample) + + # if not self.test_mode: + # dataset = self.chunk(dataset, chunk_dim=1, pct=self.mini) + + self.dataset = DatasetFromList(dataset) + self.log_load_dataset() + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [False] * self.num_copies + results["quality"] = [1] * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/adt.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/adt.py new file mode 100644 index 0000000000000000000000000000000000000000..6b5f68c2b1fbf2a16ea62ee7cc24a0220cbe6f6b --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/adt.py @@ -0,0 +1,67 @@ +from typing import Any + +import torch + +from unidepth.datasets.sequence_dataset import SequenceDataset + + +class ADT(SequenceDataset): + min_depth = 0.01 + max_depth = 20.0 + depth_scale = 1000.0 + test_split = "val.txt" + train_split = "train.txt" + sequences_file = "sequences.json" + hdf5_paths = [f"ADT.hdf5"] + + def __init__( + self, + image_shape: tuple[int, int], + split_file: str, + test_mode: bool, + normalize: bool, + augmentations_db: dict[str, Any], + resize_method: str, + mini: float, + num_frames: int = 1, + benchmark: bool = False, + decode_fields: list[str] = ["image", "depth"], + inplace_fields: list[str] = ["camera_params", "cam2w"], + **kwargs, + ) -> None: + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + num_frames=num_frames, + decode_fields=decode_fields, # if not test_mode else [*decode_fields, "points"], + inplace_fields=inplace_fields, + **kwargs, + ) + + def preprocess(self, results): + self.resizer.ctx = None + for i, seq in enumerate(results["sequence_fields"]): + # Create a mask where the distance from the center is less than H/2 + H, W = results[seq]["image"].shape[-2:] + x = torch.linspace(-W / 2 - 0.5, W / 2 + 0.5, W) + y = torch.linspace(-H / 2 - 0.5, H / 2 + 0.5, H) + xv, yv = torch.meshgrid(x, y, indexing="xy") + distance_from_center = torch.sqrt(xv**2 + yv**2).reshape(1, 1, H, W) + results[seq]["validity_mask"] = distance_from_center < (H / 2) + 20 + results[seq]["depth_mask"] = results[seq]["validity_mask"].clone() + results[seq]["mask_fields"].add("depth_mask") + results[seq]["mask_fields"].add("validity_mask") + return super().preprocess(results) + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [True] * self.num_frames * self.num_copies + results["synthetic"] = [True] * self.num_frames * self.num_copies + results["quality"] = [0] * self.num_frames * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/aimotive.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/aimotive.py new file mode 100644 index 0000000000000000000000000000000000000000..c0f7ba157d40269b8f7cbf189ad668e21e64f2fd --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/aimotive.py @@ -0,0 +1,51 @@ +from typing import Any + +from unidepth.datasets.sequence_dataset import SequenceDataset + + +class aiMotive(SequenceDataset): + min_depth = 0.01 + max_depth = 100.0 + depth_scale = 256.0 + default_fps = 10 + test_split = "train.txt" + train_split = "train.txt" + sequences_file = "sequences.json" + hdf5_paths = ["aiMotive.hdf5"] + + def __init__( + self, + image_shape: tuple[int, int], + split_file: str, + test_mode: bool, + normalize: bool, + augmentations_db: dict[str, Any], + resize_method: str, + mini: float = 1.0, + num_frames: int = 1, + benchmark: bool = False, + decode_fields: list[str] = ["image", "depth"], + inplace_fields: list[str] = ["camera_params", "cam2w"], + **kwargs, + ) -> None: + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + num_frames=num_frames, + decode_fields=decode_fields, + inplace_fields=inplace_fields, + **kwargs, + ) + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [False] * self.num_frames * self.num_copies + results["synthetic"] = [False] * self.num_frames * self.num_copies + results["quality"] = [2] * self.num_frames * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/argoverse.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/argoverse.py new file mode 100644 index 0000000000000000000000000000000000000000..65a16086a3627af4a9104bbd0acf0951ebfbf545 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/argoverse.py @@ -0,0 +1,73 @@ +import json +import os + +import h5py +import numpy as np +import torch + +from unidepth.datasets.image_dataset import ImageDataset +from unidepth.datasets.utils import DatasetFromList + + +class Argoverse(ImageDataset): + min_depth = 0.05 + max_depth = 120.0 + depth_scale = 256.0 + test_split = "argo_val.txt" + train_split = "argo_train.txt" + intrisics_file = "argo_intrinsics.json" + hdf5_paths = ["argoverse11.hdf5"] + + def __init__( + self, + image_shape, + split_file, + test_mode, + crop=None, + benchmark=False, + augmentations_db={}, + normalize=True, + resize_method="hard", + mini=1.0, + **kwargs, + ): + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + **kwargs, + ) + self.test_mode = test_mode + + self.crop = crop + self.load_dataset() + + def load_dataset(self): + h5file = h5py.File( + os.path.join(self.data_root, self.hdf5_paths[0]), + "r", + libver="latest", + swmr=True, + ) + txt_file = np.array(h5file[self.split_file]) + txt_string = txt_file.tostring().decode("ascii")[:-1] # correct the -1 + intrinsics = np.array(h5file[self.intrisics_file]).tostring().decode("ascii") + intrinsics = json.loads(intrinsics) + h5file.close() + dataset = [] + for line in txt_string.split("\n"): + image_filename, depth_filename = line.strip().split(" ") + intrinsics_val = torch.tensor(intrinsics[image_filename]).squeeze()[:, :3] + sample = [image_filename, depth_filename, intrinsics_val] + dataset.append(sample) + + if not self.test_mode: + dataset = self.chunk(dataset, chunk_dim=1, pct=self.mini) + + self.dataset = DatasetFromList(dataset) + self.log_load_dataset() diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/argoverse2.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/argoverse2.py new file mode 100644 index 0000000000000000000000000000000000000000..2b63fe935add7896f0b0324d0a01e0e169c6ceff --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/argoverse2.py @@ -0,0 +1,49 @@ +from typing import Any + +from unidepth.datasets.sequence_dataset import SequenceDataset + + +class Argoverse2(SequenceDataset): + min_depth = 0.05 + max_depth = 120.0 + depth_scale = 256.0 + test_split = "val.txt" + train_split = "train.txt" + sequences_file = "sequences_clean.json" + hdf5_paths = [f"AV2_viz.hdf5"] + + def __init__( + self, + image_shape: tuple[int, int], + split_file: str, + test_mode: bool, + normalize: bool, + augmentations_db: dict[str, Any], + resize_method: str, + mini: float = 1.0, + num_frames: int = 1, + benchmark: bool = False, + decode_fields: list[str] = ["image", "depth"], + inplace_fields: list[str] = ["K", "cam2w"], + **kwargs, + ) -> None: + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + num_frames=num_frames, + decode_fields=decode_fields, + inplace_fields=inplace_fields, + **kwargs, + ) + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [False] * self.num_frames * self.num_copies + results["quality"] = [1] * self.num_frames * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/arkit.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/arkit.py new file mode 100644 index 0000000000000000000000000000000000000000..518df50e141d76468f9e7c60f4abb2854d794478 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/arkit.py @@ -0,0 +1,49 @@ +from typing import Any + +from unidepth.datasets.sequence_dataset import SequenceDataset + + +class ARKit(SequenceDataset): + min_depth = 0.01 + max_depth = 10.0 + depth_scale = 1000.0 + test_split = "Training.txt" + train_split = "Training.txt" + sequences_file = "sequences.json" + hdf5_paths = ["ARKitS.hdf5"] + + def __init__( + self, + image_shape: tuple[int, int], + split_file: str, + test_mode: bool, + normalize: bool, + augmentations_db: dict[str, Any], + resize_method: str, + mini: float = 1.0, + num_frames: int = 1, + benchmark: bool = False, + decode_fields: list[str] = ["image", "depth"], + inplace_fields: list[str] = ["K", "cam2w"], + **kwargs, + ) -> None: + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + num_frames=num_frames, + decode_fields=decode_fields, + inplace_fields=inplace_fields, + **kwargs, + ) + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [True] * self.num_frames * self.num_copies + results["quality"] = [2] * self.num_frames * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/ase.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/ase.py new file mode 100644 index 0000000000000000000000000000000000000000..b60fe8e97cc7a12671acb3d3c22deab18af8dd9f --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/ase.py @@ -0,0 +1,66 @@ +from typing import Any + +import torch + +from unidepth.datasets.sequence_dataset import SequenceDataset + + +class ASE(SequenceDataset): + min_depth = 0.01 + max_depth = 20.0 + depth_scale = 1000.0 + test_split = "val.txt" + train_split = "train.txt" + sequences_file = "sequences.json" + hdf5_paths = [f"ASE.hdf5"] + + def __init__( + self, + image_shape: tuple[int, int], + split_file: str, + test_mode: bool, + normalize: bool, + augmentations_db: dict[str, Any], + resize_method: str, + mini: float = 1.0, + num_frames: int = 1, + benchmark: bool = False, + decode_fields: list[str] = ["image", "depth"], + inplace_fields: list[str] = ["camera_params", "cam2w"], + **kwargs, + ) -> None: + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + num_frames=num_frames, + decode_fields=decode_fields, + inplace_fields=inplace_fields, + **kwargs, + ) + + def preprocess(self, results): + self.resizer.ctx = None + for i, seq in enumerate(results["sequence_fields"]): + # Create a mask where the distance from the center is less than H/2 + H, W = results[seq]["image"].shape[-2:] + x = torch.linspace(-W / 2 - 0.5, W / 2 + 0.5, W) + y = torch.linspace(-H / 2 - 0.5, H / 2 + 0.5, H) + xv, yv = torch.meshgrid(x, y, indexing="xy") + distance_from_center = torch.sqrt(xv**2 + yv**2).reshape(1, 1, H, W) + results[seq]["validity_mask"] = distance_from_center < (H / 2) + 20 + results[seq]["mask_fields"].add("validity_mask") + + return super().preprocess(results) + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [True] * self.num_frames * self.num_copies + results["synthetic"] = [True] * self.num_frames * self.num_copies + results["quality"] = [0] * self.num_frames * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/base_dataset.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/base_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..3753a04bcc73f832d40e3c0304956f8357c2bd20 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/base_dataset.py @@ -0,0 +1,343 @@ +import os +from abc import abstractmethod +from copy import deepcopy +from math import ceil, log +from typing import Any, Dict, Tuple + +import numpy as np +import torch +from torch.utils.data import Dataset + +import unidepth.datasets.pipelines as pipelines +from unidepth.utils import (eval_3d, eval_depth, identity, is_main_process, + recursive_index, sync_tensor_across_gpus) +from unidepth.utils.constants import (IMAGENET_DATASET_MEAN, + IMAGENET_DATASET_STD, + OPENAI_DATASET_MEAN, OPENAI_DATASET_STD) + + +class BaseDataset(Dataset): + min_depth = 0.01 + max_depth = 1000.0 + + def __init__( + self, + image_shape: Tuple[int, int], + split_file: str, + test_mode: bool, + benchmark: bool, + normalize: bool, + augmentations_db: Dict[str, Any], + resize_method: str, + mini: float, + num_copies: int = 1, + **kwargs, + ) -> None: + super().__init__() + assert normalize in [None, "imagenet", "openai"] + + self.split_file = split_file + self.test_mode = test_mode + self.data_root = os.environ["DATAROOT"] + self.image_shape = image_shape + self.resize_method = resize_method + self.mini = mini + self.num_frames = 1 + self.num_copies = num_copies + self.metrics_store = {} + self.metrics_count = {} + + if normalize == "imagenet": + self.normalization_stats = { + "mean": torch.tensor(IMAGENET_DATASET_MEAN), + "std": torch.tensor(IMAGENET_DATASET_STD), + } + elif normalize == "openai": + self.normalization_stats = { + "mean": torch.tensor(OPENAI_DATASET_MEAN), + "std": torch.tensor(OPENAI_DATASET_STD), + } + else: + self.normalization_stats = { + "mean": torch.tensor([0.0, 0.0, 0.0]), + "std": torch.tensor([1.0, 1.0, 1.0]), + } + + for k, v in augmentations_db.items(): + setattr(self, k, v) + if not self.test_mode: + self._augmentation_space() + + self.masker = pipelines.AnnotationMask( + min_value=0.0, + max_value=self.max_depth if test_mode else None, + custom_fn=identity, + ) + self.filler = pipelines.RandomFiller(noise_pad=True) + + shape_mult = self.shape_constraints["shape_mult"] + self.image_shape = [ + ceil(self.image_shape[0] / shape_mult) * shape_mult, + ceil(self.image_shape[1] / shape_mult) * shape_mult, + ] + self.resizer = pipelines.ContextCrop( + image_shape=self.image_shape, + train_ctx_range=(1.0 / self.random_scale, 1.0 * self.random_scale), + test_min_ctx=self.test_context, + keep_original=test_mode, + shape_constraints=self.shape_constraints, + ) + + self.collecter = pipelines.Collect( + keys=["image_fields", "mask_fields", "gt_fields", "camera_fields"] + ) + + def __len__(self): + return len(self.dataset) + + def pack_batch(self, results): + results["paddings"] = [ + results[x]["paddings"][0] for x in results["sequence_fields"] + ] + for fields_name in [ + "image_fields", + "gt_fields", + "mask_fields", + "camera_fields", + ]: + fields = results.get(fields_name) + packed = { + field: torch.cat( + [results[seq][field] for seq in results["sequence_fields"]] + ) + for field in fields + } + results.update(packed) + return results + + def unpack_batch(self, results): + for fields_name in [ + "image_fields", + "gt_fields", + "mask_fields", + "camera_fields", + ]: + fields = results.get(fields_name) + unpacked = { + field: { + seq: results[field][idx : idx + 1] + for idx, seq in enumerate(results["sequence_fields"]) + } + for field in fields + } + results.update(unpacked) + return results + + def _augmentation_space(self): + self.augmentations_dict = { + "Flip": pipelines.RandomFlip(prob=self.flip_p), + "Jitter": pipelines.RandomColorJitter( + (-self.random_jitter, self.random_jitter), prob=self.jitter_p + ), + "Gamma": pipelines.RandomGamma( + (-self.random_gamma, self.random_gamma), prob=self.gamma_p + ), + "Blur": pipelines.GaussianBlur( + kernel_size=13, sigma=(0.1, self.random_blur), prob=self.blur_p + ), + "Grayscale": pipelines.RandomGrayscale(prob=self.grayscale_p), + } + + def augment(self, results): + for name, aug in self.augmentations_dict.items(): + results = aug(results) + return results + + def prepare_depth_eval(self, inputs, preds): + new_preds = {} + keyframe_idx = getattr(self, "keyframe_idx", None) + slice_idx = slice( + keyframe_idx, keyframe_idx + 1 if keyframe_idx is not None else None + ) + new_gts = inputs["depth"][slice_idx] + new_masks = inputs["depth_mask"][slice_idx].bool() + for key, val in preds.items(): + if "depth" in key: + new_preds[key] = val[slice_idx] + return new_gts, new_preds, new_masks + + def prepare_points_eval(self, inputs, preds): + new_preds = {} + new_gts = inputs["points"] + new_masks = inputs["depth_mask"].bool() + if "points_mask" in inputs: + new_masks = inputs["points_mask"].bool() + for key, val in preds.items(): + if "points" in key: + new_preds[key] = val + return new_gts, new_preds, new_masks + + def add_points(self, inputs): + inputs["points"] = inputs.get("camera_original", inputs["camera"]).reconstruct( + inputs["depth"] + ) + return inputs + + @torch.autocast(device_type="cuda", enabled=False, dtype=torch.float32) + def accumulate_metrics( + self, + inputs, + preds, + keyframe_idx=None, + metrics=["depth", "points", "flow_fwd", "pairwise"], + ): + if "depth" in inputs and "points" not in inputs: + inputs = self.add_points(inputs) + + available_metrics = [] + for metric in metrics: + metric_in_gt = any((metric in k for k in inputs.keys())) + metric_in_pred = any((metric in k for k in preds.keys())) + if metric_in_gt and metric_in_pred: + available_metrics.append(metric) + + if keyframe_idx is not None: + inputs = recursive_index(inputs, slice(keyframe_idx, keyframe_idx + 1)) + preds = recursive_index(preds, slice(keyframe_idx, keyframe_idx + 1)) + + if "depth" in available_metrics: + depth_gt, depth_pred, depth_masks = self.prepare_depth_eval(inputs, preds) + self.accumulate_metrics_depth(depth_gt, depth_pred, depth_masks) + + if "points" in available_metrics: + points_gt, points_pred, points_masks = self.prepare_points_eval( + inputs, preds + ) + self.accumulate_metrics_3d(points_gt, points_pred, points_masks) + + @torch.autocast(device_type="cuda", enabled=False, dtype=torch.float32) + def accumulate_metrics_depth(self, gts, preds, masks): + for eval_type, pred in preds.items(): + log_name = eval_type.replace("depth", "").strip("-").strip("_") + if log_name not in self.metrics_store: + self.metrics_store[log_name] = {} + current_count = self.metrics_count.get( + log_name, torch.tensor([], device=gts.device) + ) + new_count = masks.view(gts.shape[0], -1).sum(dim=-1) + self.metrics_count[log_name] = torch.cat([current_count, new_count]) + for k, v in eval_depth(gts, pred, masks, max_depth=self.max_depth).items(): + current_metric = self.metrics_store[log_name].get( + k, torch.tensor([], device=gts.device) + ) + self.metrics_store[log_name][k] = torch.cat([current_metric, v]) + + @torch.autocast(device_type="cuda", enabled=False, dtype=torch.float32) + def accumulate_metrics_3d(self, gts, preds, masks): + thresholds = torch.linspace( + log(self.min_depth), + log(self.max_depth / 20), + steps=100, + device=gts.device, + ).exp() + for eval_type, pred in preds.items(): + log_name = eval_type.replace("points", "").strip("-").strip("_") + if log_name not in self.metrics_store: + self.metrics_store[log_name] = {} + current_count = self.metrics_count.get( + log_name, torch.tensor([], device=gts.device) + ) + new_count = masks.view(gts.shape[0], -1).sum(dim=-1) + self.metrics_count[log_name] = torch.cat([current_count, new_count]) + for k, v in eval_3d(gts, pred, masks, thresholds=thresholds).items(): + current_metric = self.metrics_store[log_name].get( + k, torch.tensor([], device=gts.device) + ) + self.metrics_store[log_name][k] = torch.cat([current_metric, v]) + + def get_evaluation(self, metrics=None): + metric_vals = {} + for eval_type in metrics if metrics is not None else self.metrics_store.keys(): + assert self.metrics_store[eval_type] + cnts = sync_tensor_across_gpus(self.metrics_count[eval_type]) + for name, val in self.metrics_store[eval_type].items(): + # vals_r = (sync_tensor_across_gpus(val) * cnts / cnts.sum()).sum() + vals_r = sync_tensor_across_gpus(val).mean() + metric_vals[f"{eval_type}_{name}".strip("_")] = np.round( + vals_r.cpu().item(), 5 + ) + self.metrics_store[eval_type] = {} + self.metrics_count = {} + return metric_vals + + def replicate(self, results): + for i in range(1, self.num_copies): + results[(0, i)] = {k: deepcopy(v) for k, v in results[(0, 0)].items()} + results["sequence_fields"].append((0, i)) + return results + + def log_load_dataset(self): + if is_main_process(): + info = f"Loaded {self.__class__.__name__} with {len(self)} images." + print(info) + + def pre_pipeline(self, results): + results["image_fields"] = results.get("image_fields", set()) + results["gt_fields"] = results.get("gt_fields", set()) + results["mask_fields"] = results.get("mask_fields", set()) + results["sequence_fields"] = results.get("sequence_fields", set()) + results["camera_fields"] = results.get("camera_fields", set()) + results["dataset_name"] = ( + [self.__class__.__name__] * self.num_frames * self.num_copies + ) + results["depth_scale"] = [self.depth_scale] * self.num_frames * self.num_copies + results["si"] = [False] * self.num_frames * self.num_copies + results["dense"] = [False] * self.num_frames * self.num_copies + results["synthetic"] = [False] * self.num_frames * self.num_copies + results["quality"] = [0] * self.num_frames * self.num_copies + results["valid_camera"] = [True] * self.num_frames * self.num_copies + results["valid_pose"] = [True] * self.num_frames * self.num_copies + return results + + def eval_mask(self, valid_mask): + return valid_mask + + def chunk(self, dataset, chunk_dim=1, pct=1.0): + subsampled_datasets = [ + x + for i in range(0, len(dataset), int(1 / pct * chunk_dim)) + for x in dataset[i : i + chunk_dim] + ] + return subsampled_datasets + + @abstractmethod + def preprocess(self, results): + raise NotImplementedError + + @abstractmethod + def postprocess(self, results): + raise NotImplementedError + + @abstractmethod + def get_mapper(self): + raise NotImplementedError + + @abstractmethod + def get_intrinsics(self, idx, image_name): + raise NotImplementedError + + @abstractmethod + def get_extrinsics(self, idx, image_name): + raise NotImplementedError + + @abstractmethod + def load_dataset(self): + raise NotImplementedError + + @abstractmethod + def get_single_item(self, idx, sample=None, mapper=None): + raise NotImplementedError + + @abstractmethod + def __getitem__(self, idx): + raise NotImplementedError diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/bdd.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/bdd.py new file mode 100644 index 0000000000000000000000000000000000000000..d78ea873dc616786a381ba392a79b6c0fd6e17fe --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/bdd.py @@ -0,0 +1,82 @@ +import json +import os + +import h5py +import numpy as np +import torch + +from unidepth.datasets.image_dataset import ImageDataset +from unidepth.datasets.utils import DatasetFromList + + +class BDD(ImageDataset): + min_depth = 0.01 + max_depth = 70.0 + depth_scale = 256.0 + test_split = "val.txt" + train_split = "train_clean.txt" + intrisics_file = "intrinsics.json" + hdf5_paths = ["BDD.hdf5"] + + def __init__( + self, + image_shape, + split_file, + test_mode, + benchmark=False, + augmentations_db={}, + normalize=True, + resize_method="hard", + mini=1.0, + **kwargs, + ): + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + **kwargs, + ) + self.test_mode = test_mode + self.load_dataset() + + def load_dataset(self): + h5file = h5py.File( + os.path.join(self.data_root, self.hdf5_paths[0]), + "r", + libver="latest", + swmr=True, + ) + txt_file = np.array(h5file[self.split_file]) + txt_string = txt_file.tostring().decode("ascii") # [:-1] # correct the -1 + intrinsics = np.array(h5file[self.intrisics_file]).tostring().decode("ascii") + intrinsics = json.loads(intrinsics) + + dataset = [] + for line in txt_string.split("\n"): + image_filename, depth_filename = line.strip().split(" ") + intrinsics_val = torch.tensor( + intrinsics[os.path.join(*image_filename.split("/")[:2])] + ).squeeze()[:, :3] + sample = [image_filename, depth_filename, intrinsics_val] + dataset.append(sample) + h5file.close() + if not self.test_mode: + dataset = self.chunk(dataset, chunk_dim=1, pct=self.mini) + if self.test_mode and not self.benchmark: + dataset = self.chunk(dataset, chunk_dim=1, pct=0.1) + + self.dataset = DatasetFromList(dataset) + self.log_load_dataset() + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["si"] = [True] * self.num_copies + results["valid_camera"] = [False] * self.num_copies + results["dense"] = [False] * self.num_copies + results["quality"] = [2] * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/bedlam.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/bedlam.py new file mode 100644 index 0000000000000000000000000000000000000000..50ba09de857bbb841adc3470d2221cbc6d575f00 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/bedlam.py @@ -0,0 +1,50 @@ +from typing import Any + +from unidepth.datasets.sequence_dataset import SequenceDataset + + +class BEDLAM(SequenceDataset): + min_depth = 0.01 + max_depth = 256.0 + depth_scale = 1000.0 + test_split = "train.txt" + train_split = "val.txt" + sequences_file = "sequences.json" + hdf5_paths = ["BEDLAM.hdf5"] + + def __init__( + self, + image_shape: tuple[int, int], + split_file: str, + test_mode: bool, + normalize: bool, + augmentations_db: dict[str, Any], + resize_method: str, + mini: float = 1.0, + num_frames: int = 1, + benchmark: bool = False, + decode_fields: list[str] = ["image", "depth"], + inplace_fields: list[str] = ["K", "cam2w"], + **kwargs, + ) -> None: + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + num_frames=num_frames, + decode_fields=decode_fields, + inplace_fields=inplace_fields, + **kwargs, + ) + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [True] * self.num_frames * self.num_copies + results["synthetic"] = [True] * self.num_frames * self.num_copies + results["quality"] = [0] * self.num_frames * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/behave.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/behave.py new file mode 100644 index 0000000000000000000000000000000000000000..4b5b32704a0af05e8c0966712b0a9af7352528e1 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/behave.py @@ -0,0 +1,52 @@ +from typing import Any + +from unidepth.datasets.sequence_dataset import SequenceDataset + + +class Behave(SequenceDataset): + min_depth = 0.01 + max_depth = 10.0 + depth_scale = 1000.0 + default_fps = 10 + test_split = "train.txt" + train_split = "train.txt" + sequences_file = "sequences.json" + hdf5_paths = ["Behave.hdf5"] + + def __init__( + self, + image_shape: tuple[int, int], + split_file: str, + test_mode: bool, + normalize: bool, + augmentations_db: dict[str, Any], + resize_method: str, + mini: float = 1.0, + num_frames: int = 1, + benchmark: bool = False, + decode_fields: list[str] = ["image", "depth"], + inplace_fields: list[str] = ["camera_params", "cam2w"], + **kwargs, + ) -> None: + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + num_frames=num_frames, + decode_fields=decode_fields, + inplace_fields=inplace_fields, + **kwargs, + ) + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [True] * self.num_frames * self.num_copies + results["synthetic"] = [False] * self.num_frames * self.num_copies + results["si"] = [False] * self.num_frames * self.num_copies + results["quality"] = [1] * self.num_frames * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/blendedmvg.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/blendedmvg.py new file mode 100644 index 0000000000000000000000000000000000000000..1f1fe53d2d3f4d54c02cab263dcd2f4460c44c3b --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/blendedmvg.py @@ -0,0 +1,50 @@ +from typing import Any + +from unidepth.datasets.sequence_dataset import SequenceDataset + + +class BlendedMVG(SequenceDataset): + min_depth = 0.01 + max_depth = 5000.0 + depth_scale = 1000.0 + test_split = "train.txt" + train_split = "train.txt" + sequences_file = "sequences_clean.json" + hdf5_paths = ["BlendedMVG_.hdf5"] + + def __init__( + self, + image_shape: tuple[int, int], + split_file: str, + test_mode: bool, + normalize: bool, + augmentations_db: dict[str, Any], + resize_method: str, + mini: float = 1.0, + num_frames: int = 1, + benchmark: bool = False, + decode_fields: list[str] = ["image", "depth"], + inplace_fields: list[str] = ["K", "cam2w"], + **kwargs, + ) -> None: + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + num_frames=num_frames, + decode_fields=decode_fields, + inplace_fields=inplace_fields, + **kwargs, + ) + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [True] * self.num_frames * self.num_copies + results["si"] = [False] * self.num_frames * self.num_copies + results["quality"] = [2] * self.num_frames * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/cityscape.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/cityscape.py new file mode 100644 index 0000000000000000000000000000000000000000..024063812b6ec3b6bcd57d84091a16eb1854bf5a --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/cityscape.py @@ -0,0 +1,78 @@ +import json +import os + +import h5py +import numpy as np +import torch + +from unidepth.datasets.image_dataset import ImageDataset +from unidepth.datasets.utils import DatasetFromList + + +class Cityscape(ImageDataset): + min_depth = 0.05 + max_depth = 80.0 + depth_scale = 256.0 + test_split = "val.txt" + train_split = "train.txt" + intrisics_file = "intrinsics.json" + hdf5_paths = ["cityscape.hdf5"] + + def __init__( + self, + image_shape, + split_file, + test_mode, + crop=None, + benchmark=False, + augmentations_db={}, + normalize=True, + resize_method="hard", + mini=1.0, + **kwargs, + ): + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + **kwargs, + ) + self.test_mode = test_mode + + self.crop = crop + self.load_dataset() + + def load_dataset(self): + h5file = h5py.File( + os.path.join(self.data_root, self.hdf5_paths[0]), + "r", + libver="latest", + swmr=True, + ) + txt_file = np.array(h5file[self.split_file]) + txt_string = txt_file.tostring().decode("ascii")[:-1] # correct the -1 + intrinsics = np.array(h5file[self.intrisics_file]).tostring().decode("ascii") + intrinsics = json.loads(intrinsics) + h5file.close() + dataset = [] + for line in txt_string.split("\n"): + image_filename, depth_filename = line.strip().split(" ") + intrinsics_val = torch.tensor(intrinsics[image_filename]).squeeze()[:, :3] + sample = [image_filename, depth_filename, intrinsics_val] + dataset.append(sample) + + if not self.test_mode: + dataset = self.chunk(dataset, chunk_dim=1, pct=self.mini) + + self.dataset = DatasetFromList(dataset) + self.log_load_dataset() + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["quality"] = [2] * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/ddad.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/ddad.py new file mode 100644 index 0000000000000000000000000000000000000000..390c67a5c5416ce508b19e305903cf7eaafef4d7 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/ddad.py @@ -0,0 +1,84 @@ +import json +import os + +import h5py +import numpy as np +import torch + +from unidepth.datasets.image_dataset import ImageDataset +from unidepth.datasets.utils import DatasetFromList + + +class DDAD(ImageDataset): + min_depth = 0.05 + max_depth = 120.0 + depth_scale = 256.0 + test_split = "val.txt" + train_split = "train.txt" + intrisics_file = "intrinsics.json" + hdf5_paths = [f"ddad/ddad_{i}.hdf5" for i in range(8)] + + def __init__( + self, + image_shape, + split_file, + test_mode, + benchmark=False, + augmentations_db={}, + normalize=True, + resize_method="hard", + mini=1.0, + **kwargs, + ): + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + **kwargs, + ) + self.test_mode = test_mode + self.load_dataset() + + def load_dataset(self): + h5file = h5py.File( + os.path.join(self.data_root, self.hdf5_paths[0]), + "r", + libver="latest", + swmr=True, + ) + txt_file = np.array(h5file[self.split_file]) + txt_string = txt_file.tostring().decode("ascii").strip("\n") + intrinsics = np.array(h5file[self.intrisics_file]).tostring().decode("ascii") + intrinsics = json.loads(intrinsics) + h5file.close() + dataset = [] + for line in txt_string.split("\n"): + image_filename, depth_filename, chunk_idx = line.strip().split(" ") + intrinsics_val = torch.tensor(intrinsics[image_filename]).squeeze()[:, :3] + sample = [image_filename, depth_filename, intrinsics_val, chunk_idx] + dataset.append(sample) + + if not self.test_mode: + dataset = self.chunk(dataset, chunk_dim=1, pct=self.mini) + + self.dataset = DatasetFromList(dataset) + self.log_load_dataset() + + def get_mapper(self): + return { + "image_filename": 0, + "depth_filename": 1, + "K": 2, + "chunk_idx": 3, + } + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [False] * self.num_copies + results["quality"] = [1] * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/deep360.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/deep360.py new file mode 100644 index 0000000000000000000000000000000000000000..11855cec315e08378da92a8d756ee32e94f7e16c --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/deep360.py @@ -0,0 +1,56 @@ +from typing import Any + +import torch + +from unidepth.datasets.pipelines import Compose, PanoCrop, PanoRoll +from unidepth.datasets.sequence_dataset import SequenceDataset + + +class Deep360(SequenceDataset): + min_depth = 0.1 + max_depth = 1000.0 + depth_scale = 1000.0 + test_split = "train.txt" + train_split = "train.txt" + sequences_file = "sequences.json" + hdf5_paths = [f"Deep360.hdf5"] + + def __init__( + self, + image_shape: tuple[int, int], + split_file: str, + test_mode: bool, + normalize: bool, + augmentations_db: dict[str, Any], + resize_method: str, + mini: float = 1.0, + num_frames: int = 1, + benchmark: bool = False, + decode_fields: list[str] = ["image", "depth"], + inplace_fields: list[str] = ["cam2w", "camera_params"], + **kwargs, + ) -> None: + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + num_frames=num_frames, + decode_fields=decode_fields, + inplace_fields=inplace_fields, + **kwargs, + ) + self.resizer = Compose( + [PanoCrop(), PanoRoll(test_mode=test_mode), self.resizer] + ) + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [True] * self.num_frames * self.num_copies + results["synthetic"] = [True] * self.num_frames * self.num_copies + results["quality"] = [0] * self.num_frames * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/dense.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/dense.py new file mode 100644 index 0000000000000000000000000000000000000000..fbeba065d5e226f723d637d1d575eabbf6226e26 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/dense.py @@ -0,0 +1,91 @@ +import os + +import h5py +import numpy as np +import torch + +from unidepth.datasets.image_dataset import ImageDataset +from unidepth.datasets.utils import DatasetFromList + + +class DENSE(ImageDataset): + CAM_INTRINSIC = { + "ALL": torch.tensor( + [ + [1177.8614, 0.0, 474.319027], + [0.0, 1177.8614, 224.275919], + [0.0, 0.0, 1.0], + ] + ) + } + min_depth = 0.05 + max_depth = 80.0 + depth_scale = 255.0 + test_split = "train.txt" + train_split = "train.txt" + hdf5_paths = ["DENSE.hdf5"] + + def __init__( + self, + image_shape, + split_file, + test_mode, + benchmark=False, + augmentations_db={}, + normalize=True, + resize_method="hard", + mini=1.0, + **kwargs, + ): + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + **kwargs, + ) + self.test_mode = test_mode + + self.intrisics = {} + self.load_dataset() + + def load_dataset(self): + h5file = h5py.File( + os.path.join(self.data_root, self.hdf5_paths[0]), + "r", + libver="latest", + swmr=True, + ) + txt_file = np.array(h5file[self.split_file]) + txt_string = txt_file.tostring().decode("ascii")[:-1] # correct the -1 + h5file.close() + dataset = [] + for line in txt_string.split("\n"): + image_filename, depth_filename = line.strip().split(" ") + sample = [image_filename, depth_filename] + dataset.append(sample) + + if not self.test_mode: + dataset = self.chunk(dataset, chunk_dim=1, pct=self.mini) + + self.dataset = DatasetFromList(dataset) + self.log_load_dataset() + + def get_intrinsics(self, idx, image_name): + return self.CAM_INTRINSIC["ALL"].clone() + + def get_mapper(self): + return { + "image_filename": 0, + "depth_filename": 1, + } + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [False] * self.num_copies + results["quality"] = [1] * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/diml.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/diml.py new file mode 100644 index 0000000000000000000000000000000000000000..139e034f1f45b477eb8a613b9049d36468feb422 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/diml.py @@ -0,0 +1,79 @@ +import json +import os + +import h5py +import numpy as np +import torch + +from unidepth.datasets.image_dataset import ImageDataset +from unidepth.datasets.utils import DatasetFromList + + +class DIML(ImageDataset): + min_depth = 0.01 + max_depth = 100.0 + depth_scale = 256.0 + test_split = "test.txt" + train_split = "train.txt" + intrisics_file = "intrinsics.json" + hdf5_paths = ["DIML.hdf5"] + + def __init__( + self, + image_shape, + split_file, + test_mode, + benchmark=False, + augmentations_db={}, + normalize=True, + resize_method="hard", + mini=1.0, + **kwargs, + ): + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + **kwargs, + ) + self.test_mode = test_mode + + self.intrisics = {} + self.load_dataset() + + def load_dataset(self): + h5file = h5py.File( + os.path.join(self.data_root, self.hdf5_paths[0]), + "r", + libver="latest", + swmr=True, + ) + txt_file = np.array(h5file[self.split_file]) + txt_string = txt_file.tostring().decode("ascii") # [:-1] # correct the -1 + intrinsics = np.array(h5file[self.intrisics_file]).tostring().decode("ascii") + intrinsics = json.loads(intrinsics) + dataset = [] + for line in txt_string.split("\n"): + image_filename, depth_filename = line.strip().split(" ") + intrinsics_val = torch.tensor( + intrinsics[image_filename.split("/")[0]] + ).squeeze()[:, :3] + sample = [image_filename, depth_filename, intrinsics_val] + dataset.append(sample) + h5file.close() + if not self.test_mode: + dataset = self.chunk(dataset, chunk_dim=1, pct=self.mini) + + self.dataset = DatasetFromList(dataset) + self.log_load_dataset() + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [True] * self.num_copies + results["quality"] = [2] * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/diode.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/diode.py new file mode 100644 index 0000000000000000000000000000000000000000..bf09f1f47a00c2005d8cca81629f7ce66c6509d3 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/diode.py @@ -0,0 +1,278 @@ +import os + +import h5py +import numpy as np +import torch + +from unidepth.datasets.image_dataset import ImageDataset +from unidepth.datasets.sequence_dataset import SequenceDataset +from unidepth.datasets.utils import DatasetFromList + + +class DiodeIndoor(ImageDataset): + CAM_INTRINSIC = { + "ALL": torch.tensor([[886.81, 0, 512], [0, 927.06, 384], [0, 0, 1]]) + } + min_depth = 0.01 + max_depth = 25.0 + depth_scale = 256.0 + test_split = "val.txt" + train_split = "train.txt" + hdf5_paths = ["DiodeIndoor.hdf5"] + + def __init__( + self, + image_shape, + split_file, + test_mode, + crop=None, + benchmark=False, + augmentations_db={}, + normalize=True, + mini=1.0, + **kwargs, + ): + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + mini=mini, + **kwargs, + ) + self.test_mode = test_mode + + # load annotations + self.load_dataset() + + def load_dataset(self): + h5file = h5py.File( + os.path.join(self.data_root, self.hdf5_paths[0]), + "r", + libver="latest", + swmr=True, + ) + txt_file = np.array(h5file[self.split_file]) + txt_string = txt_file.tostring().decode("ascii")[:-1] # correct the -1 + h5file.close() + dataset = [] + for line in txt_string.split("\n"): + image_filename, depth_filename = line.strip().split(" ") + sample = [ + image_filename, + depth_filename, + ] + dataset.append(sample) + + if not self.test_mode: + dataset = self.chunk(dataset, chunk_dim=1, pct=self.mini) + + self.dataset = DatasetFromList(dataset) + self.log_load_dataset() + + def get_intrinsics(self, *args, **kwargs): + return self.CAM_INTRINSIC["ALL"].clone() + + def get_mapper(self): + return { + "image_filename": 0, + "depth_filename": 1, + } + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [True] * self.num_copies + results["quality"] = [1] * self.num_copies + return results + + +class DiodeIndoor_F(SequenceDataset): + min_depth = 0.01 + max_depth = 25.0 + depth_scale = 1000.0 + test_split = "train.txt" + train_split = "train.txt" + sequences_file = "sequences.json" + hdf5_paths = ["DiodeIndoor-F.hdf5"] + + def __init__( + self, + image_shape: tuple[int, int], + split_file: str, + test_mode: bool, + normalize: bool, + augmentations_db: dict[str, float], + resize_method: str, + mini: float = 1.0, + num_frames: int = 1, + benchmark: bool = False, + decode_fields: list[str] = ["image", "depth"], + inplace_fields: list[str] = ["camera_params", "cam2w"], + **kwargs, + ) -> None: + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + num_frames=num_frames, + decode_fields=( + decode_fields if not test_mode else [*decode_fields, "points"] + ), + inplace_fields=inplace_fields, + **kwargs, + ) + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [True] * self.num_frames * self.num_copies + results["quality"] = [1] * self.num_frames * self.num_copies + return results + + +class DiodeOutdoor(ImageDataset): + CAM_INTRINSIC = { + "ALL": torch.tensor([[886.81, 0, 512], [0, 927.06, 384], [0, 0, 1]]) + } + min_depth = 0.1 + max_depth = 80.0 + log_mean = 0 + log_std = 1 + test_split = "diode_outdoor_val.txt" + train_split = "diode_outdoor_train.txt" + hdf5_paths = ["diode.hdf5"] + + def __init__( + self, + image_shape, + split_file, + test_mode, + depth_scale=256, + crop=None, + benchmark=False, + augmentations_db={}, + normalize=True, + resize_method="hard", + mini=1.0, + **kwargs, + ): + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + **kwargs, + ) + self.test_mode = test_mode + self.depth_scale = depth_scale + + self.masker = AnnotationMask( + min_value=self.min_depth, + max_value=self.max_depth if test_mode else None, + custom_fn=self.eval_mask if test_mode else lambda x, *args, **kwargs: x, + ) + # load annotations + self.load_dataset() + + def load_dataset(self): + self.h5file = h5py.File( + os.path.join(self.data_root, self.hdf5_path), + "r", + libver="latest", + swmr=True, + ) + txt_file = np.array(self.h5file[self.split_file]) + txt_string = txt_file.tostring().decode("ascii")[:-1] + dataset = {"depth_filename": [], "image_filename": []} + for line in txt_string.split("\n"): + depth_filename = line.strip().split(" ")[1] + img_name = line.strip().split(" ")[0] + image_filename = img_name + dataset["depth_filename"].append(depth_filename) + dataset["image_filename"].append(image_filename) + + self.dataset = pl.from_dict(dataset) + + if not self.test_mode and self.mini: + self.dataset = self.dataset[::2] + + +class Diode(ImageDataset): + CAM_INTRINSIC = { + "ALL": torch.tensor([[886.81, 0, 512], [0, 927.06, 384], [0, 0, 1]]) + } + log_mean = 0 + log_std = 1 + min_depth = 0.6 + max_depth = 80.0 + test_split = "diode_val.txt" + train_split = "diode_train.txt" + hdf5_paths = ["diode.hdf5"] + + def __init__( + self, + image_shape, + split_file, + test_mode, + depth_scale=256, + crop=None, + benchmark=False, + augmentations_db={}, + normalize=True, + mini=1.0, + **kwargs, + ): + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + mini=mini, + **kwargs, + ) + self.test_mode = test_mode + self.depth_scale = depth_scale + + self.masker = AnnotationMask( + min_value=self.min_depth, + max_value=self.max_depth if test_mode else None, + custom_fn=self.eval_mask if test_mode else lambda x, *args, **kwargs: x, + ) + # load annotations + self.load_dataset() + + def load_dataset(self): + self.h5file = h5py.File( + os.path.join(self.data_root, self.hdf5_path), + "r", + libver="latest", + swmr=True, + ) + txt_file = np.array(self.h5file[self.split_file]) + txt_string = txt_file.tostring().decode("ascii")[:-1] + dataset = {"depth_filename": [], "image_filename": []} + for line in txt_string.split("\n"): + depth_filename = line.strip().split(" ")[1] + image_filename = line.strip().split(" ")[0] + dataset["depth_filename"].append(depth_filename) + dataset["image_filename"].append(image_filename) + + self.dataset = pl.from_dict(dataset) + + if not self.test_mode and self.mini: + self.dataset = self.dataset[::2] + + def get_intrinsics(self, *args, **kwargs): + return self.CAM_INTRINSIC["ALL"].clone() diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/dl3dv.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/dl3dv.py new file mode 100644 index 0000000000000000000000000000000000000000..a185cd88f64ffad258d647cc144b693364f35ded --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/dl3dv.py @@ -0,0 +1,49 @@ +from typing import Any + +from unidepth.datasets.sequence_dataset import SequenceDataset + + +class DL3DV(SequenceDataset): + min_depth = 0.001 + max_depth = 250.0 + depth_scale = 512.0 + test_split = "train.txt" + train_split = "train.txt" + sequences_file = "sequences.json" + hdf5_paths = [f"DL3DVcv.hdf5"] + + def __init__( + self, + image_shape: tuple[int, int], + split_file: str, + test_mode: bool, + normalize: bool, + augmentations_db: dict[str, Any], + resize_method: str, + mini: float = 1.0, + num_frames: int = 1, + benchmark: bool = False, + decode_fields: list[str] = ["image", "depth"], + inplace_fields: list[str] = ["camera_params", "cam2w"], + **kwargs, + ) -> None: + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + num_frames=num_frames, + decode_fields=decode_fields, + inplace_fields=inplace_fields, + **kwargs, + ) + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["si"] = [True] * self.num_frames * self.num_copies + results["quality"] = [2] * self.num_frames * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/driving_stereo.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/driving_stereo.py new file mode 100644 index 0000000000000000000000000000000000000000..9946f36aebf0bc6e8db974fa87db346dbcba639e --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/driving_stereo.py @@ -0,0 +1,82 @@ +import json +import os + +import h5py +import numpy as np +import torch + +from unidepth.datasets.image_dataset import ImageDataset +from unidepth.datasets.utils import DatasetFromList + + +class DrivingStereo(ImageDataset): + min_depth = 0.05 + max_depth = 80.0 + depth_scale = 256.0 + test_split = "drivingstereo_val.txt" + train_split = "drivingstereo_train.txt" + intrisics_file = "drivingstereo_intrinsics.json" + hdf5_paths = ["DrivingStereo.hdf5"] + + def __init__( + self, + image_shape, + split_file, + test_mode, + crop=None, + benchmark=False, + augmentations_db={}, + normalize=True, + resize_method="hard", + mini=1.0, + **kwargs, + ): + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + **kwargs, + ) + self.test_mode = test_mode + + self.crop = crop + self.load_dataset() + + def load_dataset(self): + h5file = h5py.File( + os.path.join(self.data_root, self.hdf5_paths[0]), + "r", + libver="latest", + swmr=True, + ) + txt_file = np.array(h5file[self.split_file]) + txt_string = txt_file.tostring().decode("ascii") # [:-1] # correct the -1 + intrinsics = np.array(h5file[self.intrisics_file]).tostring().decode("ascii") + intrinsics = json.loads(intrinsics) + dataset = [] + for line in txt_string.split("\n"): + image_filename, depth_filename = line.strip().split(" ") + intrinsics_val = torch.tensor(intrinsics[image_filename]).squeeze()[:, :3] + sample = [image_filename, depth_filename, intrinsics_val] + dataset.append(sample) + h5file.close() + + if not self.test_mode: + dataset = self.chunk(dataset, chunk_dim=1, pct=self.mini) + + if self.test_mode and not self.benchmark: + dataset = self.chunk(dataset, chunk_dim=1, pct=1.0) + + self.dataset = DatasetFromList(dataset) + self.log_load_dataset() + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [False] * self.num_copies + results["quality"] = [1] * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/dtu_rmvd.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/dtu_rmvd.py new file mode 100644 index 0000000000000000000000000000000000000000..1f48652b992bcd1617c806d61f0e0c25172a499b --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/dtu_rmvd.py @@ -0,0 +1,62 @@ +import json +import os +from typing import Any + +import h5py +import numpy as np +import torch + +from unidepth.datasets.image_dataset import ImageDataset +from unidepth.datasets.pipelines import AnnotationMask, KittiCrop +from unidepth.datasets.sequence_dataset import SequenceDataset +from unidepth.datasets.utils import DatasetFromList +from unidepth.utils import identity + + +class DTURMVD(SequenceDataset): + min_depth = 0.05 + max_depth = 3.0 + depth_scale = 1000.0 + default_fps = 6 + test_split = "test.txt" + train_split = "test.txt" + sequences_file = "sequences.json" + hdf5_paths = ["dtu_rmvd.hdf5"] + + def __init__( + self, + image_shape, + split_file, + test_mode, + crop=None, + augmentations_db={}, + normalize=True, + resize_method="hard", + mini: float = 1.0, + num_frames: int = 1, + benchmark: bool = False, + decode_fields: list[str] = ["image", "depth"], + inplace_fields: list[str] = ["K", "cam2w"], + **kwargs, + ): + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + num_frames=num_frames, + decode_fields=decode_fields, + inplace_fields=inplace_fields, + **kwargs, + ) + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [True] * self.num_frames * self.num_copies + results["si"] = [True] * self.num_frames * self.num_copies + results["quality"] = [1] * self.num_frames * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/dummy.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/dummy.py new file mode 100644 index 0000000000000000000000000000000000000000..2e0157c7e2c60631d16603aa7b5616fa32d07cf2 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/dummy.py @@ -0,0 +1,33 @@ +import numpy as np +import torch +from torch.utils.data import Dataset + + +class Dummy(Dataset): + train_split = None + test_split = None + + def __init__(self, *args, **kwargs): + super().__init__() + self.dataset = np.arange(1_000_000) + + def get_single_item(self, idx): + # results = {} + # results["cam2w"] = torch.eye(4).unsqueeze(0) + # results["K"] = torch.eye(3).unsqueeze(0) + # results["image"] = torch.zeros(1, 3, 1024, 1024).to(torch.uint8) + # results["depth"] = torch.zeros(1, 1, 1024, 1024).to(torch.float32) + return { + "x": {(0, 0): torch.rand(1, 3, 1024, 1024, dtype=torch.float32)}, + "img_metas": {"val": torch.rand(1, 1024, dtype=torch.float32)}, + } + + def __getitem__(self, idx): + if isinstance(idx, (list, tuple)): + results = [self.get_single_item(i) for i in idx] + else: + results = self.get_single_item(idx) + return results + + def __len__(self): + return len(self.dataset) diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/dynamic_replica.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/dynamic_replica.py new file mode 100644 index 0000000000000000000000000000000000000000..8fb457ab26b68f280f8abd9289e0e9b3c5799e6e --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/dynamic_replica.py @@ -0,0 +1,51 @@ +from typing import Any + +from unidepth.datasets.sequence_dataset import SequenceDataset + + +class DynReplica(SequenceDataset): + min_depth = 0.01 + max_depth = 20.0 + default_fps = 30.0 + depth_scale = 512.0 + test_split = "val.txt" + train_split = "train.txt" + sequences_file = "sequences_clean.json" + hdf5_paths = ["DynReplica.hdf5"] + + def __init__( + self, + image_shape: tuple[int, int], + split_file: str, + test_mode: bool, + normalize: bool, + augmentations_db: dict[str, Any], + resize_method: str, + mini: float = 1.0, + num_frames: int = 1, + benchmark: bool = False, + decode_fields: list[str] = ["image", "depth"], + inplace_fields: list[str] = ["K", "cam2w"], + **kwargs, + ) -> None: + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + num_frames=num_frames, + decode_fields=decode_fields, + inplace_fields=inplace_fields, + **kwargs, + ) + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [True] * self.num_frames * self.num_copies + results["synthetic"] = [True] * self.num_frames * self.num_copies + results["quality"] = [0] * self.num_frames * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/eden.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/eden.py new file mode 100644 index 0000000000000000000000000000000000000000..df35efb5962e0ac27c31618a9e53f6312eb89b9f --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/eden.py @@ -0,0 +1,50 @@ +from typing import Any + +from unidepth.datasets.sequence_dataset import SequenceDataset + + +class EDEN(SequenceDataset): + min_depth = 0.1 + max_depth = 100.0 + depth_scale = 256.0 + test_split = "train.txt" + train_split = "train.txt" + sequences_file = "sequences.json" + hdf5_paths = [f"EDEN.hdf5"] + + def __init__( + self, + image_shape: tuple[int, int], + split_file: str, + test_mode: bool, + normalize: bool, + augmentations_db: dict[str, Any], + resize_method: str, + mini: float = 1.0, + num_frames: int = 1, + benchmark: bool = False, + decode_fields: list[str] = ["image", "depth"], + inplace_fields: list[str] = ["K", "cam2w"], + **kwargs, + ) -> None: + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + num_frames=num_frames, + decode_fields=decode_fields, + inplace_fields=inplace_fields, + **kwargs, + ) + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [True] * self.num_frames * self.num_copies + results["synthetic"] = [True] * self.num_frames * self.num_copies + results["quality"] = [0] * self.num_frames * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/eth3d.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/eth3d.py new file mode 100644 index 0000000000000000000000000000000000000000..207e5386e1617eb399cea6dc370e71cc9a6d94dc --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/eth3d.py @@ -0,0 +1,122 @@ +import json +import os + +import h5py +import numpy as np +import torch + +from unidepth.datasets.image_dataset import ImageDataset +from unidepth.datasets.sequence_dataset import SequenceDataset +from unidepth.datasets.utils import DatasetFromList + + +class ETH3D(ImageDataset): + min_depth = 0.01 + max_depth = 50.0 + depth_scale = 1000.0 + test_split = "train.txt" + train_split = "train.txt" + intrisics_file = "intrinsics.json" + hdf5_paths = ["ETH3D.hdf5"] + + def __init__( + self, + image_shape, + split_file, + test_mode, + benchmark=False, + augmentations_db={}, + normalize=True, + resize_method="hard", + mini=1.0, + **kwargs, + ): + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + **kwargs, + ) + self.test_mode = test_mode + self.load_dataset() + + def load_dataset(self): + h5file = h5py.File( + os.path.join(self.data_root, self.hdf5_paths[0]), + "r", + libver="latest", + swmr=True, + ) + txt_file = np.array(h5file[self.split_file]) + txt_string = txt_file.tostring().decode("ascii")[:-1] # correct the -1 + intrinsics = np.array(h5file[self.intrisics_file]).tostring().decode("ascii") + intrinsics = json.loads(intrinsics) + h5file.close() + dataset = [] + for line in txt_string.split("\n"): + image_filename, depth_filename = line.strip().split(" ") + intrinsics_val = torch.tensor(intrinsics[image_filename]).squeeze()[:, :3] + sample = [image_filename, depth_filename, intrinsics_val] + dataset.append(sample) + + self.dataset = DatasetFromList(dataset) + self.log_load_dataset() + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [True] * self.num_frames * self.num_copies + results["quality"] = [1] * self.num_frames * self.num_copies + return results + + +class ETH3D_F(SequenceDataset): + min_depth = 0.05 + max_depth = 60.0 + depth_scale = 1000.0 + test_split = "train.txt" + train_split = "train.txt" + sequences_file = "sequences.json" + hdf5_paths = ["ETH3D-F.hdf5"] + + def __init__( + self, + image_shape: tuple[int, int], + split_file: str, + test_mode: bool, + normalize: bool, + augmentations_db: dict[str, float], + resize_method: str, + mini: float = 1.0, + num_frames: int = 1, + benchmark: bool = False, + decode_fields: list[str] = ["image", "depth"], + inplace_fields: list[str] = ["camera_params", "cam2w"], + **kwargs, + ) -> None: + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + num_frames=num_frames, + decode_fields=( + decode_fields if not test_mode else [*decode_fields, "points"] + ), + inplace_fields=inplace_fields, + **kwargs, + ) + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [True] * self.num_frames * self.num_copies + results["quality"] = [1] * self.num_frames * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/eth3d_rmvd.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/eth3d_rmvd.py new file mode 100644 index 0000000000000000000000000000000000000000..ffe676a94f6b8c50103dc3d12eca88c4cf3c4fb5 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/eth3d_rmvd.py @@ -0,0 +1,55 @@ +import json +import os +from typing import Any + +import h5py +import numpy as np +import torch + +from unidepth.datasets.image_dataset import ImageDataset +from unidepth.datasets.pipelines import AnnotationMask, KittiCrop +from unidepth.datasets.sequence_dataset import SequenceDataset +from unidepth.datasets.utils import DatasetFromList +from unidepth.utils import identity + + +class ETH3DRMVD(SequenceDataset): + min_depth = 0.01 + max_depth = 50.0 + depth_scale = 1000.0 + default_fps = 6 + test_split = "test.txt" + train_split = "test.txt" + sequences_file = "sequences.json" + hdf5_paths = ["eth3d_rmvd.hdf5"] + + def __init__( + self, + image_shape, + split_file, + test_mode, + crop=None, + augmentations_db={}, + normalize=True, + resize_method="hard", + mini: float = 1.0, + num_frames: int = 1, + benchmark: bool = False, + decode_fields: list[str] = ["image", "depth"], + inplace_fields: list[str] = ["K", "cam2w"], + **kwargs, + ): + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + num_frames=num_frames, + decode_fields=decode_fields, + inplace_fields=inplace_fields, + **kwargs, + ) diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/facedepth.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/facedepth.py new file mode 100644 index 0000000000000000000000000000000000000000..4ff2aff5fcbe58d3e2c1ffc96797655d85380c43 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/facedepth.py @@ -0,0 +1,51 @@ +from typing import Any + +from unidepth.datasets.sequence_dataset import SequenceDataset + + +class FaceDepth(SequenceDataset): + min_depth = 0.01 + max_depth = 10.0 + depth_scale = 1000.0 + default_fps = 10 + test_split = "train.txt" + train_split = "train.txt" + sequences_file = "sequences.json" + hdf5_paths = ["FaceDepth.hdf5"] + + def __init__( + self, + image_shape: tuple[int, int], + split_file: str, + test_mode: bool, + normalize: bool, + augmentations_db: dict[str, Any], + resize_method: str, + mini: float = 1.0, + num_frames: int = 1, + benchmark: bool = False, + decode_fields: list[str] = ["image", "depth"], + inplace_fields: list[str] = ["K", "cam2w"], + **kwargs, + ) -> None: + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + num_frames=num_frames, + decode_fields=decode_fields, + inplace_fields=inplace_fields, + **kwargs, + ) + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [True] * self.num_frames * self.num_copies + results["synthetic"] = [True] * self.num_frames * self.num_copies + results["quality"] = [0] * self.num_frames * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/flsea.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/flsea.py new file mode 100644 index 0000000000000000000000000000000000000000..1c0e116c3b7da95664f74c24f997ae2f16fb23be --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/flsea.py @@ -0,0 +1,100 @@ +import os + +import h5py +import numpy as np +import torch + +from unidepth.datasets.image_dataset import ImageDataset +from unidepth.datasets.utils import DatasetFromList + + +class FLSea(ImageDataset): + CAM_INTRINSIC = { + "canyons": torch.tensor( + [ + [1175.3913431656817, 0.0, 466.2595428966926], + [0.0, 1174.2805075232263, 271.2116633091501], + [0.0, 0.0, 1.0], + ] + ), + "red_sea": torch.tensor( + [ + [1296.666758476217, 0.0, 501.50386149846], + [0.0, 1300.831316354508, 276.161712082695], + [0.0, 0.0, 1.0], + ] + ), + } + min_depth = 0.05 + max_depth = 20.0 + depth_scale = 1000.0 + train_split = "train.txt" + hdf5_paths = ["FLSea.hdf5"] + + def __init__( + self, + image_shape, + split_file, + test_mode, + crop=None, + benchmark=False, + augmentations_db={}, + normalize=True, + resize_method="hard", + mini=False, + **kwargs, + ): + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + **kwargs, + ) + self.test_mode = test_mode + + self.crop = crop + self.load_dataset() + + def load_dataset(self): + h5file = h5py.File( + os.path.join(self.data_root, self.hdf5_paths[0]), + "r", + libver="latest", + swmr=True, + ) + txt_file = np.array(h5file[self.split_file]) + txt_string = txt_file.tostring().decode("ascii")[:-1] # correct the -1 + h5file.close() + dataset = [] + for line in txt_string.split("\n"): + image_filename, depth_filename = line.strip().split(" ") + sample = [image_filename, depth_filename] + dataset.append(sample) + + if not self.test_mode: + dataset = self.chunk(dataset, chunk_dim=1, pct=self.mini) + if self.test_mode and not self.benchmark: + dataset = self.chunk(dataset, chunk_dim=1, pct=0.33) + + self.dataset = DatasetFromList(dataset) + self.log_load_dataset() + + def get_intrinsics(self, idx, image_name): + return self.CAM_INTRINSIC[image_name.split("/")[0]][:, :3].clone() + + def get_mapper(self): + return { + "image_filename": 0, + "depth_filename": 1, + } + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [True] * self.num_copies + results["quality"] = [2] * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/futurehouse.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/futurehouse.py new file mode 100644 index 0000000000000000000000000000000000000000..87fbc681c78644cb366912b88de1d2efe9cbeb5e --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/futurehouse.py @@ -0,0 +1,56 @@ +from typing import Any + +import torch + +from unidepth.datasets.pipelines import Compose, PanoCrop, PanoRoll +from unidepth.datasets.sequence_dataset import SequenceDataset + + +class FutureHouse(SequenceDataset): + min_depth = 0.01 + max_depth = 10.0 + depth_scale = 1000.0 + test_split = "train.txt" + train_split = "train.txt" + sequences_file = "sequences.json" + hdf5_paths = [f"FutureHouse.hdf5"] + + def __init__( + self, + image_shape: tuple[int, int], + split_file: str, + test_mode: bool, + normalize: bool, + augmentations_db: dict[str, Any], + resize_method: str, + mini: float = 1.0, + num_frames: int = 1, + benchmark: bool = False, + decode_fields: list[str] = ["image", "depth"], + inplace_fields: list[str] = ["cam2w", "camera_params"], + **kwargs, + ) -> None: + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + num_frames=num_frames, + decode_fields=decode_fields, + inplace_fields=inplace_fields, + **kwargs, + ) + self.resizer = Compose( + [PanoCrop(), PanoRoll(test_mode=test_mode), self.resizer] + ) + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [True] * self.num_frames * self.num_copies + results["synthetic"] = [True] * self.num_frames * self.num_copies + results["quality"] = [0] * self.num_frames * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/gibson.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/gibson.py new file mode 100644 index 0000000000000000000000000000000000000000..ff99fa399b222c2fd5d3415dc1ccdcc2174a2ba1 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/gibson.py @@ -0,0 +1,56 @@ +from typing import Any + +import torch + +from unidepth.datasets.pipelines import Compose, PanoCrop, PanoRoll +from unidepth.datasets.sequence_dataset import SequenceDataset + + +class Gibson(SequenceDataset): + min_depth = 0.01 + max_depth = 10.0 + depth_scale = 1000.0 + test_split = "train.txt" + train_split = "train.txt" + sequences_file = "sequences.json" + hdf5_paths = [f"Gibson.hdf5"] + + def __init__( + self, + image_shape: tuple[int, int], + split_file: str, + test_mode: bool, + normalize: bool, + augmentations_db: dict[str, Any], + resize_method: str, + mini: float = 1.0, + num_frames: int = 1, + benchmark: bool = False, + decode_fields: list[str] = ["image", "depth"], + inplace_fields: list[str] = ["cam2w", "camera_params"], + **kwargs, + ) -> None: + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + num_frames=num_frames, + decode_fields=decode_fields, + inplace_fields=inplace_fields, + **kwargs, + ) + self.resizer = Compose( + [PanoCrop(), PanoRoll(test_mode=test_mode), self.resizer] + ) + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [True] * self.num_frames * self.num_copies + results["synthetic"] = [True] * self.num_frames * self.num_copies + results["quality"] = [1] * self.num_frames * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/hammer.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/hammer.py new file mode 100644 index 0000000000000000000000000000000000000000..a65fd25afc66f89235589097b8ae5bb3b72908e1 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/hammer.py @@ -0,0 +1,76 @@ +import json +import os + +import h5py +import numpy as np +import torch + +from unidepth.datasets.image_dataset import ImageDataset +from unidepth.datasets.utils import DatasetFromList + + +class HAMMER(ImageDataset): + min_depth = 0.005 + max_depth = 10.0 + depth_scale = 1000.0 + train_split = "test.txt" + test_split = "test.txt" + intrisics_file = "intrinsics.json" + hdf5_paths = ["hammer.hdf5"] + + def __init__( + self, + image_shape, + split_file, + test_mode, + crop=None, + benchmark=False, + augmentations_db={}, + normalize=True, + resize_method="hard", + mini=1.0, + **kwargs, + ): + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + **kwargs, + ) + self.test_mode = test_mode + + self.crop = crop + self.load_dataset() + + def load_dataset(self): + h5file = h5py.File( + os.path.join(self.data_root, self.hdf5_paths[0]), + "r", + libver="latest", + swmr=True, + ) + txt_file = np.array(h5file[self.split_file]) + txt_string = txt_file.tostring().decode("ascii")[:-1] # correct the -1 + intrinsics = np.array(h5file[self.intrisics_file]).tostring().decode("ascii") + intrinsics = json.loads(intrinsics) + h5file.close() + dataset = [] + for line in txt_string.split("\n"): + image_filename, depth_filename = line.strip().split(" ") + intrinsics_val = torch.tensor(intrinsics[image_filename]).squeeze()[:, :3] + sample = [image_filename, depth_filename, intrinsics_val] + dataset.append(sample) + + self.dataset = DatasetFromList(dataset) + self.log_load_dataset() + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [True] * self.num_frames * self.num_copies + results["quality"] = [1] * self.num_frames * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/hm3d.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/hm3d.py new file mode 100644 index 0000000000000000000000000000000000000000..f926158be3872e07eebfec791c99a681ce28a535 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/hm3d.py @@ -0,0 +1,49 @@ +from typing import Any + +from unidepth.datasets.sequence_dataset import SequenceDataset + + +class HM3D(SequenceDataset): + min_depth = 0.01 + max_depth = 10.0 + depth_scale = 1000.0 + test_split = "val.txt" + train_split = "full.txt" + sequences_file = "sequences.json" + hdf5_paths = [f"HM3D.hdf5"] + + def __init__( + self, + image_shape: tuple[int, int], + split_file: str, + test_mode: bool, + normalize: bool, + augmentations_db: dict[str, Any], + resize_method: str, + mini: float = 1.0, + num_frames: int = 1, + benchmark: bool = False, + decode_fields: list[str] = ["image", "depth"], + inplace_fields: list[str] = ["K", "cam2w"], + **kwargs, + ) -> None: + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + num_frames=num_frames, + decode_fields=decode_fields, + inplace_fields=inplace_fields, + **kwargs, + ) + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [True] * self.num_frames * self.num_copies + results["quality"] = [2] * self.num_frames * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/hoi4d.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/hoi4d.py new file mode 100644 index 0000000000000000000000000000000000000000..1326449d12c0172cec17fd560198b5ac063ad9e4 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/hoi4d.py @@ -0,0 +1,51 @@ +from typing import Any + +from unidepth.datasets.sequence_dataset import SequenceDataset + + +class HOI4D(SequenceDataset): + min_depth = 0.01 + max_depth = 10.0 + depth_scale = 1000.0 + default_fps = 5 + test_split = "train.txt" + train_split = "train.txt" + sequences_file = "sequences.json" + hdf5_paths = ["HOI4D.hdf5"] + + def __init__( + self, + image_shape: tuple[int, int], + split_file: str, + test_mode: bool, + normalize: bool, + augmentations_db: dict[str, Any], + resize_method: str, + mini: float = 1.0, + num_frames: int = 1, + benchmark: bool = False, + decode_fields: list[str] = ["image", "depth"], + inplace_fields: list[str] = ["K", "cam2w"], + **kwargs, + ) -> None: + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + num_frames=num_frames, + decode_fields=decode_fields, + inplace_fields=inplace_fields, + **kwargs, + ) + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [True] * self.num_frames * self.num_copies + results["synthetic"] = [False] * self.num_frames * self.num_copies + results["quality"] = [1] * self.num_frames * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/hrwsi.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/hrwsi.py new file mode 100644 index 0000000000000000000000000000000000000000..d643ff0f4e8186450640a1baae452bae34792148 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/hrwsi.py @@ -0,0 +1,83 @@ +import os + +import h5py +import numpy as np +import torch + +from unidepth.datasets.image_dataset import ImageDataset +from unidepth.datasets.utils import DatasetFromList + + +class HRWSI(ImageDataset): + min_depth = 0.01 + max_depth = 1000.0 + depth_scale = 50.0 + test_split = "val.txt" + train_split = "train.txt" + hdf5_paths = ["HRWSI.hdf5"] + + def __init__( + self, + image_shape, + split_file, + test_mode, + benchmark=False, + augmentations_db={}, + normalize=True, + resize_method="hard", + mini=1.0, + **kwargs, + ): + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + **kwargs, + ) + self.test_mode = test_mode + self.load_dataset() + + def load_dataset(self): + h5file = h5py.File( + os.path.join(self.data_root, self.hdf5_paths[0]), + "r", + libver="latest", + swmr=True, + ) + txt_file = np.array(h5file[self.split_file]) + txt_string = txt_file.tostring().decode("ascii") # [:-1] # correct the -1 + # with open(os.path.join(os.environ["TMPDIR"], self.split_file), "w") as f: + # f.write(txt_string) + + dataset = [] + + for line in txt_string.split("\n"): + image_filename, depth_filename = line.strip().split(" ") + sample = [ + image_filename, + depth_filename, + ] + dataset.append(sample) + h5file.close() + if not self.test_mode: + dataset = self.chunk(dataset, chunk_dim=1, pct=self.mini) + + self.dataset = DatasetFromList(dataset) + self.log_load_dataset() + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["ssi"] = [True] + results["valid_camera"] = [False] + return results + + def get_mapper(self): + return { + "image_filename": 0, + "depth_filename": 1, + } diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/hypersim.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/hypersim.py new file mode 100644 index 0000000000000000000000000000000000000000..29154170be78aa1ffc104e7ea195f0b2238c841e --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/hypersim.py @@ -0,0 +1,97 @@ +import json +import os + +import h5py +import numpy as np +import torch + +from unidepth.datasets.image_dataset import ImageDataset +from unidepth.datasets.utils import DatasetFromList + + +class HyperSim(ImageDataset): + min_depth = 0.01 + max_depth = 50.0 + depth_scale = 1000.0 + test_split = "val.txt" + train_split = "train.txt" + intrisics_file = "intrinsics.json" + hdf5_paths = [f"hypersim/hypersim_{i}.hdf5" for i in range(8)] + + def __init__( + self, + image_shape, + split_file, + test_mode, + benchmark=False, + augmentations_db={}, + normalize=True, + resize_method="hard", + mini=1.0, + **kwargs, + ): + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + **kwargs, + ) + self.test_mode = test_mode + + self.load_dataset() + + def load_dataset(self): + h5file = h5py.File( + os.path.join(self.data_root, self.hdf5_paths[0]), + "r", + libver="latest", + swmr=True, + ) + txt_file = np.array(h5file[self.split_file]) + txt_string = txt_file.tostring().decode("ascii").strip("\n") + intrinsics = np.array(h5file[self.intrisics_file]).tostring().decode("ascii") + intrinsics = json.loads(intrinsics) + + # with open(os.path.join(os.environ["TMPDIR"], self.split_file), "w") as f: + # f.write(txt_string) + # with open(os.path.join(os.environ["TMPDIR"], self.intrisics_file), "w") as f: + # json.dump(intrinsics, f) + + dataset = [] + for line in txt_string.split("\n"): + image_filename, depth_filename, chunk_idx = line.strip().split(" ") + intrinsics_val = torch.tensor( + intrinsics[os.path.join(*image_filename.split("/")[:2])] + ).squeeze()[:, :3] + sample = [image_filename, depth_filename, intrinsics_val, chunk_idx] + dataset.append(sample) + h5file.close() + + if not self.test_mode: + dataset = self.chunk(dataset, chunk_dim=1, pct=self.mini) + + if self.test_mode and not self.benchmark: # corresponds to 712 images + dataset = self.chunk(dataset, chunk_dim=1, pct=0.1) + + self.dataset = DatasetFromList(dataset) + self.log_load_dataset() + + def get_mapper(self): + return { + "image_filename": 0, + "depth_filename": 1, + "K": 2, + "chunk_idx": 3, + } + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [True] * self.num_copies + results["synthetic"] = [True] * self.num_copies + results["quality"] = [0] * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/ibims.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/ibims.py new file mode 100644 index 0000000000000000000000000000000000000000..b27e49fc0f47b6d9388ec32207a2f25b114cf288 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/ibims.py @@ -0,0 +1,125 @@ +import json +import os + +import h5py +import numpy as np +import torch + +from unidepth.datasets.image_dataset import ImageDataset +from unidepth.datasets.sequence_dataset import SequenceDataset +from unidepth.datasets.utils import DatasetFromList + + +class IBims(ImageDataset): + min_depth = 0.005 + max_depth = 25.0 + depth_scale = 1000.0 + train_split = "ibims_val.txt" + test_split = "ibims_val.txt" + intrisics_file = "ibims_intrinsics.json" + hdf5_paths = ["ibims.hdf5"] + + def __init__( + self, + image_shape, + split_file, + test_mode, + crop=None, + benchmark=False, + augmentations_db={}, + normalize=True, + resize_method="hard", + mini=1.0, + **kwargs, + ): + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + **kwargs, + ) + self.test_mode = test_mode + + self.crop = crop + self.load_dataset() + + def load_dataset(self): + h5file = h5py.File( + os.path.join(self.data_root, self.hdf5_paths[0]), + "r", + libver="latest", + swmr=True, + ) + txt_file = np.array(h5file[self.split_file]) + txt_string = txt_file.tostring().decode("ascii")[:-1] # correct the -1 + intrinsics = np.array(h5file[self.intrisics_file]).tostring().decode("ascii") + intrinsics = json.loads(intrinsics) + h5file.close() + dataset = [] + for line in txt_string.split("\n"): + image_filename, depth_filename = line.strip().split(" ") + intrinsics_val = torch.tensor(intrinsics[image_filename]).squeeze()[:, :3] + sample = [image_filename, depth_filename, intrinsics_val] + dataset.append(sample) + + self.dataset = DatasetFromList(dataset) + self.log_load_dataset() + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [True] * self.num_copies + results["quality"] = [1] * self.num_copies + return results + + +class IBims_F(SequenceDataset): + min_depth = 0.01 + max_depth = 25.0 + depth_scale = 1000.0 + test_split = "train.txt" + train_split = "train.txt" + sequences_file = "sequences.json" + hdf5_paths = ["IBims-F.hdf5"] + + def __init__( + self, + image_shape: tuple[int, int], + split_file: str, + test_mode: bool, + normalize: bool, + augmentations_db: dict[str, float], + resize_method: str, + mini: float, + num_frames: int = 1, + benchmark: bool = False, + decode_fields: list[str] = ["image", "depth"], + inplace_fields: list[str] = ["camera_params", "cam2w"], + **kwargs, + ) -> None: + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + num_frames=num_frames, + decode_fields=( + decode_fields if not test_mode else [*decode_fields, "points"] + ), + inplace_fields=inplace_fields, + **kwargs, + ) + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [True] * self.num_frames * self.num_copies + results["quality"] = [1] * self.num_frames * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/image_dataset.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/image_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..9c6fffbcede8e7c6dd0eb73ffe800b875210da9b --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/image_dataset.py @@ -0,0 +1,192 @@ +import io +import os +from time import time +from typing import Any, Dict, List, Tuple + +import numpy as np +import tables +import torch +import torchvision +import torchvision.transforms.v2.functional as TF +from PIL import Image + +from unidepth.datasets.base_dataset import BaseDataset +from unidepth.utils import is_main_process +from unidepth.utils.camera import BatchCamera, Pinhole + +""" +Awful class for legacy reasons, we assume only pinhole cameras +And we "fake" sequences by setting sequence_fields to [(0, 0)] and cam2w as eye(4) +""" + + +class ImageDataset(BaseDataset): + def __init__( + self, + image_shape: Tuple[int, int], + split_file: str, + test_mode: bool, + normalize: bool, + augmentations_db: Dict[str, Any], + resize_method: str, + mini: float, + benchmark: bool = False, + **kwargs, + ) -> None: + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + **kwargs, + ) + self.mapper = self.get_mapper() + + def get_single_item(self, idx, sample=None, mapper=None): + sample = self.dataset[idx] if sample is None else sample + mapper = self.mapper if mapper is None else mapper + + results = { + (0, 0): dict( + gt_fields=set(), + image_fields=set(), + mask_fields=set(), + camera_fields=set(), + ) + } + results = self.pre_pipeline(results) + results["sequence_fields"] = [(0, 0)] + + chunk_idx = ( + int(sample[self.mapper["chunk_idx"]]) if "chunk_idx" in self.mapper else 0 + ) + h5_path = os.path.join(self.data_root, self.hdf5_paths[chunk_idx]) + with tables.File( + h5_path, + mode="r", + libver="latest", + swmr=True, + ) as h5file_chunk: + for key_mapper, idx_mapper in mapper.items(): + if "image" not in key_mapper and "depth" not in key_mapper: + continue + value = sample[idx_mapper] + results[(0, 0)][key_mapper] = value + name = key_mapper.replace("_filename", "") + value_root = "/" + value + + if "image" in key_mapper: + results[(0, 0)]["filename"] = value + file = h5file_chunk.get_node(value_root).read() + image = ( + torchvision.io.decode_image(torch.from_numpy(file)) + .to(torch.uint8) + .squeeze() + ) + results[(0, 0)]["image_fields"].add(name) + results[(0, 0)][f"image_ori_shape"] = image.shape[-2:] + results[(0, 0)][name] = image[None, ...] + + # collect camera information for the given image + name = name.replace("image_", "") + results[(0, 0)]["camera_fields"].update({"camera", "cam2w"}) + K = self.get_intrinsics(idx, value) + if K is None: + K = torch.eye(3) + K[0, 0] = K[1, 1] = 0.7 * self.image_shape[1] + K[0, 2] = 0.5 * self.image_shape[1] + K[1, 2] = 0.5 * self.image_shape[0] + + camera = Pinhole(K=K[None, ...].clone()) + results[(0, 0)]["camera"] = BatchCamera.from_camera(camera) + results[(0, 0)]["cam2w"] = self.get_extrinsics(idx, value)[ + None, ... + ] + + elif "depth" in key_mapper: + # start = time() + file = h5file_chunk.get_node(value_root).read() + depth = Image.open(io.BytesIO(file)) + depth = TF.pil_to_tensor(depth).squeeze().to(torch.float32) + if depth.ndim == 3: + depth = depth[2] + depth[1] * 255 + depth[0] * 255 * 255 + + results[(0, 0)]["gt_fields"].add(name) + results[(0, 0)][f"depth_ori_shape"] = depth.shape + + depth = ( + depth.view(1, 1, *depth.shape).contiguous() / self.depth_scale + ) + results[(0, 0)][name] = depth + + results = self.preprocess(results) + if not self.test_mode: + results = self.augment(results) + results = self.postprocess(results) + return results + + def preprocess(self, results): + results = self.replicate(results) + for i, seq in enumerate(results["sequence_fields"]): + self.resizer.ctx = None + results[seq] = self.resizer(results[seq]) + num_pts = torch.count_nonzero(results[seq]["depth"] > 0) + if num_pts < 50: + raise IndexError(f"Too few points in depth map ({num_pts})") + + for key in results[seq].get("image_fields", ["image"]): + results[seq][key] = results[seq][key].to(torch.float32) / 255 + + # update fields common in sequence + for key in ["image_fields", "gt_fields", "mask_fields", "camera_fields"]: + if key in results[(0, 0)]: + results[key] = results[(0, 0)][key] + results = self.pack_batch(results) + return results + + def postprocess(self, results): + # normalize after because color aug requires [0,255]? + for key in results.get("image_fields", ["image"]): + results[key] = TF.normalize(results[key], **self.normalization_stats) + results = self.filler(results) + results = self.unpack_batch(results) + results = self.masker(results) + results = self.collecter(results) + return results + + def __getitem__(self, idx): + try: + if isinstance(idx, (list, tuple)): + results = [self.get_single_item(i) for i in idx] + else: + results = self.get_single_item(idx) + except Exception as e: + print(f"Error loading sequence {idx} for {self.__class__.__name__}: {e}") + idx = np.random.randint(0, len(self.dataset)) + results = self[idx] + return results + + def get_intrinsics(self, idx, image_name): + idx_sample = self.mapper.get("K", 1000) + sample = self.dataset[idx] + if idx_sample >= len(sample): + return None + return sample[idx_sample] + + def get_extrinsics(self, idx, image_name): + idx_sample = self.mapper.get("cam2w", 1000) + sample = self.dataset[idx] + if idx_sample >= len(sample): + return torch.eye(4) + return sample[idx_sample] + + def get_mapper(self): + return { + "image_filename": 0, + "depth_filename": 1, + "K": 2, + } diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/ken_burns.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/ken_burns.py new file mode 100644 index 0000000000000000000000000000000000000000..c51b570a01ba05c4773bb99570bbcbd8f0ead3ec --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/ken_burns.py @@ -0,0 +1,95 @@ +import json +import os + +import h5py +import numpy as np +import torch + +from unidepth.datasets.image_dataset import ImageDataset +from unidepth.datasets.utils import DatasetFromList + + +class KenBurns(ImageDataset): + min_depth = 0.05 + max_depth = 50.0 + depth_scale = 256.0 + test_split = "val.txt" + train_split = "train.txt" + intrisics_file = "intrinsics.json" + hdf5_paths = [f"3dkenburns/3DKenBurns_{i}.hdf5" for i in range(8)] + + def __init__( + self, + image_shape, + split_file, + test_mode, + benchmark=False, + augmentations_db={}, + normalize=True, + resize_method="hard", + mini=1.0, + **kwargs, + ): + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + **kwargs, + ) + self.test_mode = test_mode + + self.load_dataset() + + def load_dataset(self): + h5file = h5py.File( + os.path.join(self.data_root, self.hdf5_paths[0]), + "r", + libver="latest", + swmr=True, + ) + txt_file = np.array(h5file[self.split_file]) + txt_string = txt_file.tostring().decode("ascii").strip("\n") + intrinsics = np.array(h5file[self.intrisics_file]).tostring().decode("ascii") + intrinsics = json.loads(intrinsics) + + # with open(os.path.join(os.environ["TMPDIR"], self.split_file), "w") as f: + # f.write(txt_string) + # with open(os.path.join(os.environ["TMPDIR"], self.intrisics_file), "w") as f: + # json.dump(intrinsics, f) + + dataset = [] + for line in txt_string.split("\n"): + image_filename, depth_filename, chunk_idx = line.strip().split(" ") + intrinsics_val = torch.tensor(intrinsics[image_filename]).squeeze()[:, :3] + sample = [image_filename, depth_filename, intrinsics_val, chunk_idx] + dataset.append(sample) + h5file.close() + + if not self.test_mode: + dataset = self.chunk(dataset, chunk_dim=1, pct=self.mini) + + if self.test_mode and not self.benchmark: # corresponds to 500 images + dataset = self.chunk(dataset, chunk_dim=1, pct=0.25) + + self.dataset = DatasetFromList(dataset) + self.log_load_dataset() + + def get_mapper(self): + return { + "image_filename": 0, + "depth_filename": 1, + "K": 2, + "chunk_idx": 3, + } + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [True] * self.num_copies + results["synthetic"] = [True] * self.num_copies + results["quality"] = [0] * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/kitti.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/kitti.py new file mode 100644 index 0000000000000000000000000000000000000000..c67ee86163c25d7a0b0ca921e4e4080971db0c6f --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/kitti.py @@ -0,0 +1,253 @@ +import os + +import h5py +import numpy as np +import torch + +from unidepth.datasets.image_dataset import ImageDataset +from unidepth.datasets.pipelines import AnnotationMask, KittiCrop +from unidepth.datasets.utils import DatasetFromList +from unidepth.utils import identity + + +class KITTI(ImageDataset): + CAM_INTRINSIC = { + "2011_09_26": torch.tensor( + [ + [7.215377e02, 0.000000e00, 6.095593e02, 4.485728e01], + [0.000000e00, 7.215377e02, 1.728540e02, 2.163791e-01], + [0.000000e00, 0.000000e00, 1.000000e00, 2.745884e-03], + ] + ), + "2011_09_28": torch.tensor( + [ + [7.070493e02, 0.000000e00, 6.040814e02, 4.575831e01], + [0.000000e00, 7.070493e02, 1.805066e02, -3.454157e-01], + [0.000000e00, 0.000000e00, 1.000000e00, 4.981016e-03], + ] + ), + "2011_09_29": torch.tensor( + [ + [7.183351e02, 0.000000e00, 6.003891e02, 4.450382e01], + [0.000000e00, 7.183351e02, 1.815122e02, -5.951107e-01], + [0.000000e00, 0.000000e00, 1.000000e00, 2.616315e-03], + ] + ), + "2011_09_30": torch.tensor( + [ + [7.070912e02, 0.000000e00, 6.018873e02, 4.688783e01], + [0.000000e00, 7.070912e02, 1.831104e02, 1.178601e-01], + [0.000000e00, 0.000000e00, 1.000000e00, 6.203223e-03], + ] + ), + "2011_10_03": torch.tensor( + [ + [7.188560e02, 0.000000e00, 6.071928e02, 4.538225e01], + [0.000000e00, 7.188560e02, 1.852157e02, -1.130887e-01], + [0.000000e00, 0.000000e00, 1.000000e00, 3.779761e-03], + ] + ), + } + min_depth = 0.05 + max_depth = 80.0 + depth_scale = 256.0 + log_mean = 2.5462 + log_std = 0.5871 + test_split = "kitti_eigen_test.txt" + train_split = "kitti_eigen_train.txt" + test_split_benchmark = "kitti_test.txt" + hdf5_paths = ["kitti.hdf5"] + + def __init__( + self, + image_shape, + split_file, + test_mode, + crop=None, + benchmark=False, + augmentations_db={}, + normalize=True, + resize_method="hard", + mini=1.0, + **kwargs, + ): + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + **kwargs, + ) + self.masker = AnnotationMask( + min_value=0.0, + max_value=self.max_depth if test_mode else None, + custom_fn=self.eval_mask if test_mode else lambda x, *args, **kwargs: x, + ) + self.test_mode = test_mode + self.crop = crop + self.cropper_base = KittiCrop(crop_size=(352, 1216)) + self.load_dataset() + + def load_dataset(self): + h5file = h5py.File( + os.path.join(self.data_root, self.hdf5_paths[0]), + "r", + libver="latest", + swmr=True, + ) + txt_file = np.array(h5file[self.split_file]) + txt_string = txt_file.tostring().decode("ascii")[:-1] # correct the -1 + h5file.close() + dataset = [] + for line in txt_string.split("\n"): + image_filename = line.strip().split(" ")[0] + depth_filename = line.strip().split(" ")[1] + if depth_filename == "None": + self.invalid_depth_num += 1 + continue + sample = [ + image_filename, + depth_filename, + ] + dataset.append(sample) + + if not self.test_mode: + dataset = self.chunk(dataset, chunk_dim=1, pct=self.mini) + + self.dataset = DatasetFromList(dataset) + self.log_load_dataset() + + def get_intrinsics(self, idx, image_name): + return self.CAM_INTRINSIC[image_name.split("/")[0]][:, :3].clone() + + def preprocess(self, results): + results = self.replicate(results) + for i, seq in enumerate(results["sequence_fields"]): + self.resizer.ctx = None + results[seq] = self.cropper_base(results[seq]) + results[seq] = self.resizer(results[seq]) + num_pts = torch.count_nonzero(results[seq]["depth"] > 0) + if num_pts < 50: + raise IndexError(f"Too few points in depth map ({num_pts})") + + for key in results[seq].get("image_fields", ["image"]): + results[seq][key] = results[seq][key].to(torch.float32) / 255 + + # update fields common in sequence + for key in ["image_fields", "gt_fields", "mask_fields", "camera_fields"]: + if key in results[(0, 0)]: + results[key] = results[(0, 0)][key] + results = self.pack_batch(results) + return results + + def eval_mask(self, valid_mask, info={}): + """Do grag_crop or eigen_crop for testing""" + mask_height, mask_width = valid_mask.shape[-2:] + eval_mask = torch.zeros_like(valid_mask) + if "garg" in self.crop: + eval_mask[ + ..., + int(0.40810811 * mask_height) : int(0.99189189 * mask_height), + int(0.03594771 * mask_width) : int(0.96405229 * mask_width), + ] = 1 + elif "eigen" in self.crop: + eval_mask[ + ..., + int(0.3324324 * mask_height) : int(0.91351351 * mask_height), + int(0.03594771 * mask_width) : int(0.96405229 * mask_width), + ] = 1 + return torch.logical_and(valid_mask, eval_mask) + + def get_mapper(self): + return { + "image_filename": 0, + "depth_filename": 1, + } + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [False] * self.num_copies + results["quality"] = [1] * self.num_copies + return results + + +import json + + +class KITTIBenchmark(ImageDataset): + min_depth = 0.05 + max_depth = 80.0 + depth_scale = 256.0 + test_split = "test_split.txt" + train_split = "val_split.txt" + intrinsics_file = "intrinsics.json" + hdf5_paths = ["kitti_benchmark.hdf5"] + + def __init__( + self, + image_shape, + split_file, + test_mode, + crop=None, + benchmark=False, + augmentations_db={}, + normalize=True, + resize_method="hard", + mini=1.0, + **kwargs, + ): + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=True, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + **kwargs, + ) + self.test_mode = test_mode + + self.crop = crop + + self.masker = AnnotationMask( + min_value=self.min_depth, + max_value=self.max_depth if test_mode else None, + custom_fn=lambda x, *args, **kwargs: x, + ) + self.collecter = Collect(keys=["image_fields", "mask_fields", "gt_fields"]) + self.load_dataset() + + def load_dataset(self): + h5file = h5py.File( + os.path.join(self.data_root, self.hdf5_path), + "r", + libver="latest", + swmr=True, + ) + txt_file = np.array(self.h5file[self.split_file]) + txt_string = txt_file.tostring().decode("ascii")[:-1] # correct the -1 + intrinsics = np.array(h5file[self.intrinsics_file]).tostring().decode("ascii") + intrinsics = json.loads(intrinsics) + h5file.close() + dataset = [] + for line in txt_string.split("\n"): + image_filename, depth_filename = line.strip().split(" ") + intrinsics = torch.tensor( + intrinsics[os.path.join(*image_filename.split("/")[:2])] + ).squeeze()[:, :3] + sample = { + "image_filename": image_filename, + "depth_filename": depth_filename, + "K": intrinsics, + } + dataset.append(sample) + + self.dataset = DatasetFromList(dataset) + + self.log_load_dataset() diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/kitti360.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/kitti360.py new file mode 100644 index 0000000000000000000000000000000000000000..d315528fc68bbef44d653134e0db2751519116a6 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/kitti360.py @@ -0,0 +1,65 @@ +from typing import Any + +import torch + +from unidepth.datasets.sequence_dataset import SequenceDataset + + +class KITTI360(SequenceDataset): + min_depth = 0.01 + max_depth = 80.0 + depth_scale = 256.0 + train_split = "train.txt" + test_split = "val_split.txt" + sequences_file = "sequences_split.json" + hdf5_paths = [f"KITTI360.hdf5"] + + def __init__( + self, + image_shape: tuple[int, int], + split_file: str, + test_mode: bool, + normalize: bool, + augmentations_db: dict[str, Any], + resize_method: str, + mini: float = 1.0, + num_frames: int = 1, + benchmark: bool = False, + decode_fields: list[str] = ["image", "depth"], + inplace_fields: list[str] = ["camera_params", "cam2w"], + **kwargs, + ) -> None: + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + num_frames=num_frames, + decode_fields=( + decode_fields if not test_mode else [*decode_fields, "points"] + ), + inplace_fields=inplace_fields, + **kwargs, + ) + + def preprocess(self, results): + self.resizer.ctx = None + for i, seq in enumerate(results["sequence_fields"]): + # Create a mask where the distance from the center is less than H/2 + H, W = results[seq]["image"].shape[-2:] + x = torch.linspace(-W / 2, W / 2, W) + y = torch.linspace(-H / 2, H / 2, H) + xv, yv = torch.meshgrid(x, y, indexing="xy") + distance_from_center = torch.sqrt(xv**2 + yv**2).reshape(1, 1, H, W) + results[seq]["validity_mask"] = distance_from_center < (H / 2) + return super().preprocess(results) + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [False] * self.num_frames * self.num_copies + results["quality"] = [1] * self.num_frames * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/kitti_multi.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/kitti_multi.py new file mode 100644 index 0000000000000000000000000000000000000000..d614d93a54eff1a7a8043f40bf6a4fda6721dd27 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/kitti_multi.py @@ -0,0 +1,104 @@ +import json +import os +from typing import Any + +import h5py +import numpy as np +import torch + +from unidepth.datasets.image_dataset import ImageDataset +from unidepth.datasets.pipelines import AnnotationMask, KittiCrop +from unidepth.datasets.sequence_dataset import SequenceDataset +from unidepth.datasets.utils import DatasetFromList +from unidepth.utils import identity + + +class KITTIMulti(SequenceDataset): + min_depth = 0.05 + max_depth = 80.0 + depth_scale = 256.0 + default_fps = 10.0 + test_split = "val.txt" + train_split = "train.txt" + sequences_file = "sequences.json" + hdf5_paths = ["KITTI_sequence.hdf5"] + + def __init__( + self, + image_shape, + split_file, + test_mode, + crop=None, + augmentations_db={}, + normalize=True, + resize_method="hard", + mini: float = 1.0, + num_frames: int = 1, + benchmark: bool = False, + decode_fields: list[str] = ["image", "depth"], + inplace_fields: list[str] = ["K", "cam2w"], + **kwargs, + ): + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + num_frames=num_frames, + decode_fields=decode_fields, + inplace_fields=inplace_fields, + **kwargs, + ) + self.test_mode = test_mode + + self.crop = crop + + self.cropper_base = KittiCrop(crop_size=(352, 1216)) + + self.masker = AnnotationMask( + min_value=0.0, + max_value=self.max_depth if test_mode else None, + custom_fn=self.eval_mask if test_mode else identity, + ) + self.eval_last = True + + def __len__(self): + if self.test_mode: + return 64 # FIXME: Hardcoded for now + return len(self.dataset) + + def preprocess(self, results): + self.resizer.ctx = None + for i, seq in enumerate(results["sequence_fields"]): + results[seq] = self.cropper_base(results[seq]) + results[seq] = self.resizer(results[seq]) + for key in results[seq].get("image_fields", ["image"]): + results[seq][key] = results[seq][key].to(torch.float32) / 255 + results.update({k: v for k, v in results[(0, 0)].items() if "fields" in k}) + + results = self.pack_batch(results) + return results + + def eval_mask(self, valid_mask, info={}): + """Do grag_crop or eigen_crop for testing""" + mask_height, mask_width = valid_mask.shape[-2:] + eval_mask = torch.zeros_like(valid_mask) + if "garg" in self.crop: + eval_mask[ + ..., + int(0.40810811 * mask_height) : int(0.99189189 * mask_height), + int(0.03594771 * mask_width) : int(0.96405229 * mask_width), + ] = 1 + elif "eigen" in self.crop: + eval_mask[ + ..., + int(0.3324324 * mask_height) : int(0.91351351 * mask_height), + int(0.03594771 * mask_width) : int(0.96405229 * mask_width), + ] = 1 + else: + return valid_mask + return torch.logical_and(valid_mask, eval_mask) diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/kitti_rmvd.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/kitti_rmvd.py new file mode 100644 index 0000000000000000000000000000000000000000..2de1be72d0cb3700ca34eb63241a2a5cc7c54754 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/kitti_rmvd.py @@ -0,0 +1,75 @@ +import json +import os +from typing import Any + +import h5py +import numpy as np +import torch + +from unidepth.datasets.pipelines import AnnotationMask, Compose, KittiCrop +from unidepth.datasets.sequence_dataset import SequenceDataset +from unidepth.utils import identity + + +class KITTIRMVD(SequenceDataset): + min_depth = 0.05 + max_depth = 80.0 + depth_scale = 256.0 + default_fps = 10 + test_split = "test.txt" + train_split = "test.txt" + sequences_file = "sequences.json" + hdf5_paths = ["kitti_rmvd.hdf5"] + + def __init__( + self, + image_shape, + split_file, + test_mode, + crop=None, + augmentations_db={}, + normalize=True, + resize_method="hard", + mini: float = 1.0, + num_frames: int = 1, + benchmark: bool = False, + decode_fields: list[str] = ["image", "depth"], + inplace_fields: list[str] = ["K", "cam2w"], + **kwargs, + ): + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + num_frames=num_frames, + decode_fields=decode_fields, + inplace_fields=inplace_fields, + **kwargs, + ) + self.crop = crop + self.resizer = Compose([KittiCrop(crop_size=(352, 1216)), self.resizer]) + + def eval_mask(self, valid_mask, info={}): + """Do grag_crop or eigen_crop for testing""" + mask_height, mask_width = valid_mask.shape[-2:] + eval_mask = torch.zeros_like(valid_mask) + if "garg" in self.crop: + eval_mask[ + ..., + int(0.40810811 * mask_height) : int(0.99189189 * mask_height), + int(0.03594771 * mask_width) : int(0.96405229 * mask_width), + ] = 1 + elif "eigen" in self.crop: + eval_mask[ + ..., + int(0.3324324 * mask_height) : int(0.91351351 * mask_height), + int(0.03594771 * mask_width) : int(0.96405229 * mask_width), + ] = 1 + else: + return valid_mask + return torch.logical_and(valid_mask, eval_mask) diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/lyft.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/lyft.py new file mode 100644 index 0000000000000000000000000000000000000000..aafc5ce47fd5edf5cf26d8581d89d9807b391d7b --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/lyft.py @@ -0,0 +1,84 @@ +import json +import os + +import h5py +import numpy as np +import torch + +from unidepth.datasets.image_dataset import ImageDataset +from unidepth.datasets.utils import DatasetFromList + + +class Lyft(ImageDataset): + min_depth = 0.05 + max_depth = 80.0 + depth_scale = 256.0 + test_split = "test.txt" + train_split = "train.txt" + intrisics_file = "intrinsics.json" + hdf5_paths = ["Lyft2.hdf5"] + + def __init__( + self, + image_shape, + split_file, + test_mode, + benchmark=False, + augmentations_db={}, + normalize=True, + resize_method="hard", + mini=1.0, + **kwargs, + ): + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + **kwargs, + ) + self.test_mode = test_mode + self.load_dataset() + + def load_dataset(self): + h5file = h5py.File( + os.path.join(self.data_root, self.hdf5_paths[0]), + "r", + libver="latest", + swmr=True, + ) + txt_file = np.array(h5file[self.split_file]) + txt_string = txt_file.tostring().decode("ascii") # [:-1] # correct the -1 + intrinsics = np.array(h5file[self.intrisics_file]).tostring().decode("ascii") + intrinsics = json.loads(intrinsics) + # with open(os.path.join(os.environ["TMPDIR"], self.split_file), "w") as f: + # f.write(txt_string) + # with open(os.path.join(os.environ["TMPDIR"], self.intrisics_file), "w") as f: + # json.dump(intrinsics, f) + + dataset = [] + for line in txt_string.split("\n"): + image_filename, depth_filename = line.strip().split(" ") + intrinsics_val = torch.tensor(intrinsics[image_filename]).squeeze()[:, :3] + sample = [ + image_filename, + depth_filename, + intrinsics_val, + ] + dataset.append(sample) + h5file.close() + + if not self.test_mode: + dataset = self.chunk(dataset, chunk_dim=1, pct=self.mini) + + self.dataset = DatasetFromList(dataset) + self.log_load_dataset() + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [False] + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/mapillary.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/mapillary.py new file mode 100644 index 0000000000000000000000000000000000000000..536dd6895057f6fa12fd6c47069d36ada8c45e90 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/mapillary.py @@ -0,0 +1,84 @@ +import json +import os + +import h5py +import numpy as np +import torch + +from unidepth.datasets.image_dataset import ImageDataset +from unidepth.datasets.utils import DatasetFromList + + +class Mapillary(ImageDataset): + min_depth = 0.01 + max_depth = 70.0 + depth_scale = 256.0 + test_split = "mapillary_val.txt" + train_split = "mapillary_train_clean.txt" + intrisics_file = "intrinsics.json" + hdf5_paths = ["Mapillary.hdf5"] + + def __init__( + self, + image_shape, + split_file, + test_mode, + crop=None, + benchmark=False, + augmentations_db={}, + normalize=True, + resize_method="hard", + mini=1.0, + **kwargs, + ): + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + **kwargs, + ) + self.test_mode = test_mode + + self.crop = crop + self.load_dataset() + + def load_dataset(self): + h5file = h5py.File( + os.path.join(self.data_root, self.hdf5_paths[0]), + "r", + libver="latest", + swmr=True, + ) + txt_file = np.array(h5file[self.split_file]) + txt_string = txt_file.tostring().decode("ascii") # [:-1] # correct the -1 + intrinsics = np.array(h5file[self.intrisics_file]).tostring().decode("ascii") + intrinsics = json.loads(intrinsics) + + dataset = [] + for line in txt_string.split("\n"): + image_filename, depth_filename = line.strip().split(" ") + intrinsics_val = torch.tensor(intrinsics[image_filename]).squeeze()[:, :3] + sample = [image_filename, depth_filename, intrinsics_val] + dataset.append(sample) + h5file.close() + + if not self.test_mode: + dataset = self.chunk(dataset, chunk_dim=1, pct=self.mini) + if self.test_mode and not self.benchmark: + dataset = self.chunk(dataset, chunk_dim=1, pct=0.05) + + self.dataset = DatasetFromList(dataset) + self.log_load_dataset() + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["si"] = [True] * self.num_copies + results["valid_camera"] = [False] * self.num_copies + results["dense"] = [False] * self.num_copies + results["quality"] = [2] * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/matrix_city.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/matrix_city.py new file mode 100644 index 0000000000000000000000000000000000000000..568571d2530c3ca8ba820c364fdb126850dd204c --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/matrix_city.py @@ -0,0 +1,50 @@ +from typing import Any + +from unidepth.datasets.sequence_dataset import SequenceDataset + + +class MatrixCity(SequenceDataset): + min_depth = 0.01 + max_depth = 200.0 + depth_scale = 1000.0 + test_split = "test.txt" + train_split = "train_full.txt" + sequences_file = "sequences.json" + hdf5_paths = [f"MatrixCity.hdf5"] + + def __init__( + self, + image_shape: tuple[int, int], + split_file: str, + test_mode: bool, + normalize: bool, + augmentations_db: dict[str, Any], + resize_method: str, + mini: float = 1.0, + num_frames: int = 1, + benchmark: bool = False, + decode_fields: list[str] = ["image", "depth"], + inplace_fields: list[str] = ["K", "cam2w"], + **kwargs, + ) -> None: + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + num_frames=num_frames, + decode_fields=decode_fields, + inplace_fields=inplace_fields, + **kwargs, + ) + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [True] * self.num_frames * self.num_copies + results["synthetic"] = [True] * self.num_frames * self.num_copies + results["quality"] = [0] * self.num_frames * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/matterport3d.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/matterport3d.py new file mode 100644 index 0000000000000000000000000000000000000000..993aed0a171be5290904492b64cb60b78bef4a14 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/matterport3d.py @@ -0,0 +1,56 @@ +from typing import Any + +import torch + +from unidepth.datasets.pipelines import Compose, PanoCrop, PanoRoll +from unidepth.datasets.sequence_dataset import SequenceDataset + + +class Matterport3D(SequenceDataset): + min_depth = 0.01 + max_depth = 10.0 + depth_scale = 1000.0 + test_split = "train.txt" + train_split = "train.txt" + sequences_file = "sequences.json" + hdf5_paths = [f"Matterport3D.hdf5"] + + def __init__( + self, + image_shape: tuple[int, int], + split_file: str, + test_mode: bool, + normalize: bool, + augmentations_db: dict[str, Any], + resize_method: str, + mini: float = 1.0, + num_frames: int = 1, + benchmark: bool = False, + decode_fields: list[str] = ["image", "depth"], + inplace_fields: list[str] = ["cam2w", "camera_params"], + **kwargs, + ) -> None: + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + num_frames=num_frames, + decode_fields=decode_fields, + inplace_fields=inplace_fields, + **kwargs, + ) + self.resizer = Compose( + [PanoCrop(), PanoRoll(test_mode=test_mode), self.resizer] + ) + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [True] * self.num_frames * self.num_copies + results["synthetic"] = [True] * self.num_frames * self.num_copies + results["quality"] = [1] * self.num_frames * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/megadepth.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/megadepth.py new file mode 100644 index 0000000000000000000000000000000000000000..b7cfeab8f48e0c2878844811d883614a77aa30c2 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/megadepth.py @@ -0,0 +1,83 @@ +import os + +import h5py +import numpy as np + +from unidepth.datasets.image_dataset import ImageDataset +from unidepth.datasets.utils import DatasetFromList + + +class MegaDepth(ImageDataset): + min_depth = 0.01 + max_depth = 1000.0 + depth_scale = 50.0 + test_split = "test.txt" + train_split = "train.txt" + hdf5_paths = ["MegaDepth.hdf5"] + + def __init__( + self, + image_shape, + split_file, + test_mode, + benchmark=False, + augmentations_db={}, + normalize=True, + resize_method="hard", + mini=1.0, + **kwargs, + ): + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + **kwargs, + ) + self.test_mode = test_mode + self.load_dataset() + + def load_dataset(self): + h5file = h5py.File( + os.path.join(self.data_root, self.hdf5_paths[0]), + "r", + libver="latest", + swmr=True, + ) + txt_file = np.array(h5file[self.split_file]) + txt_string = txt_file.tostring().decode("ascii") # [:-1] # correct the -1 + # with open(os.path.join(os.environ["TMPDIR"], self.split_file), "w") as f: + # f.write(txt_string) + dataset = [] + for line in txt_string.split("\n"): + image_filename, depth_filename = line.strip().split(" ") + sample = [ + image_filename, + depth_filename, + ] + dataset.append(sample) + h5file.close() + if not self.test_mode: + dataset = self.chunk(dataset, chunk_dim=1, pct=self.mini) + else: + dataset = self.chunk(dataset, chunk_dim=1, pct=0.5) + + self.dataset = DatasetFromList(dataset) + self.log_load_dataset() + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["ssi"] = [True] + results["valid_camera"] = [False] + results["dense"] = [False] + return results + + def get_mapper(self): + return { + "image_filename": 0, + "depth_filename": 1, + } diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/megadepth_s.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/megadepth_s.py new file mode 100644 index 0000000000000000000000000000000000000000..9a5a852462726d2033ba420b1167d65f7752a123 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/megadepth_s.py @@ -0,0 +1,50 @@ +from typing import Any + +from unidepth.datasets.sequence_dataset import SequenceDataset + + +class MegaDepthS(SequenceDataset): + min_depth = 0.001 + max_depth = 10000.0 + depth_scale = 512.0 + test_split = "train.txt" + train_split = "train.txt" + sequences_file = "sequences_filter_clean.json" + hdf5_paths = ["MegaDepthS.hdf5"] + + def __init__( + self, + image_shape: tuple[int, int], + split_file: str, + test_mode: bool, + normalize: bool, + augmentations_db: dict[str, Any], + resize_method: str, + mini: float = 1.0, + num_frames: int = 1, + benchmark: bool = False, + decode_fields: list[str] = ["image", "depth"], + inplace_fields: list[str] = ["intrinsics", "cam2w"], + **kwargs, + ) -> None: + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + num_frames=num_frames, + decode_fields=decode_fields, + inplace_fields=inplace_fields, + **kwargs, + ) + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["si"] = [True] * self.num_frames * self.num_copies + results["dense"] = [False] * self.num_frames * self.num_copies + results["quality"] = [2] * self.num_frames * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/midair.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/midair.py new file mode 100644 index 0000000000000000000000000000000000000000..c8b4fb6cbb4f4adb0635a0ba976e7b7daf598762 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/midair.py @@ -0,0 +1,51 @@ +from typing import Any + +from unidepth.datasets.sequence_dataset import SequenceDataset + + +class MidAir(SequenceDataset): + min_depth = 0.1 + max_depth = 1000.0 + depth_scale = 1000.0 + default_fps = 6 + test_split = "train.txt" + train_split = "train.txt" + sequences_file = "sequences.json" + hdf5_paths = ["MidAir.hdf5"] + + def __init__( + self, + image_shape: tuple[int, int], + split_file: str, + test_mode: bool, + normalize: bool, + augmentations_db: dict[str, Any], + resize_method: str, + mini: float = 1.0, + num_frames: int = 1, + benchmark: bool = False, + decode_fields: list[str] = ["image", "depth"], + inplace_fields: list[str] = ["K", "cam2w"], + **kwargs, + ) -> None: + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + num_frames=num_frames, + decode_fields=decode_fields, + inplace_fields=inplace_fields, + **kwargs, + ) + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [True] * self.num_frames * self.num_copies + results["synthetic"] = [True] * self.num_frames * self.num_copies + results["quality"] = [0] * self.num_frames * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/mip.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/mip.py new file mode 100644 index 0000000000000000000000000000000000000000..0a18f780b9f5ae70fc1613e0421391f67831ee27 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/mip.py @@ -0,0 +1,52 @@ +from typing import Any + +from unidepth.datasets.sequence_dataset import SequenceDataset + + +class MIP(SequenceDataset): + min_depth = 0.01 + max_depth = 100.0 + depth_scale = 1000.0 + default_fps = 10 + test_split = "train.txt" + train_split = "train.txt" + sequences_file = "sequences.json" + hdf5_paths = ["MIP.hdf5"] + + def __init__( + self, + image_shape: tuple[int, int], + split_file: str, + test_mode: bool, + normalize: bool, + augmentations_db: dict[str, Any], + resize_method: str, + mini: float = 1.0, + num_frames: int = 1, + benchmark: bool = False, + decode_fields: list[str] = ["image", "depth"], + inplace_fields: list[str] = ["K", "cam2w"], + **kwargs, + ) -> None: + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + num_frames=num_frames, + decode_fields=decode_fields, + inplace_fields=inplace_fields, + **kwargs, + ) + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [True] * self.num_frames * self.num_copies + results["synthetic"] = [False] * self.num_frames * self.num_copies + results["si"] = [True] * self.num_frames * self.num_copies + results["quality"] = [2] * self.num_frames * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/ms2.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/ms2.py new file mode 100644 index 0000000000000000000000000000000000000000..37de10a9b0cd2a7b005c752cf9b6dfff22190dc3 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/ms2.py @@ -0,0 +1,51 @@ +from typing import Any + +from unidepth.datasets.sequence_dataset import SequenceDataset + + +class MS2(SequenceDataset): + min_depth = 0.01 + max_depth = 100.0 + depth_scale = 256.0 + default_fps = 5 + test_split = "train.txt" + train_split = "train.txt" + sequences_file = "sequences.json" + hdf5_paths = ["MS2.hdf5"] + + def __init__( + self, + image_shape: tuple[int, int], + split_file: str, + test_mode: bool, + normalize: bool, + augmentations_db: dict[str, Any], + resize_method: str, + mini: float = 1.0, + num_frames: int = 1, + benchmark: bool = False, + decode_fields: list[str] = ["image", "depth"], + inplace_fields: list[str] = ["K", "cam2w"], + **kwargs, + ) -> None: + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + num_frames=num_frames, + decode_fields=decode_fields, + inplace_fields=inplace_fields, + **kwargs, + ) + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [False] * self.num_frames * self.num_copies + results["synthetic"] = [False] * self.num_frames * self.num_copies + results["quality"] = [1] * self.num_frames * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/mvimgnet.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/mvimgnet.py new file mode 100644 index 0000000000000000000000000000000000000000..92f5b933ff2486c9b7225905740bb692e366d364 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/mvimgnet.py @@ -0,0 +1,137 @@ +from typing import Any + +from unidepth.datasets.sequence_dataset import SequenceDataset + +INVALID_SEQUENCES = [ + "1/000121f2-0", + "15/1600ae56-0", + "26/000000f3-0", + "33/1d00e677-0", + "43/22008925-0", + "49/000147db-0", + "51/23002a43-0", + "51/23000916-0", + "108/000133ae-0", + "129/000037f2-0", + "141/17012545-0", + "141/1700f3de-0", + "152/1b00e061-0", + "154/1d00decb-0", + "154/1d017c1c-0", + "154/1d0019a5-0", + "154/1d00334d-0", + "154/1d012ed6-0", + "154/1d016b8a-0", + "154/1d016cc1-0", + "154/1d008d5f-0", + "159/000157f9-0", + "159/00000b96-0", + "159/000075c0-0", + "159/0000445c-0", + "159/000056a0-0", + "159/00010c68-0", + "159/0000573b-0", + "159/00002698-0", + "159/00008fca-0", + "159/00009ef8-0", + "159/00015f05-0", + "159/0000c6df-0", + "159/0000ee59-0", + "163/290159d2-0", + "163/29016c7c-0", + "163/2900239c-0", + "163/29002f7b-0", + "163/29014b05-0", + "163/29000196-0", + "163/2901750f-0", + "164/1b0145cf-0", + "164/1b00eb1d-0", + "164/1b00c28b-0", + "164/1b0110d0-0", + "164/1b00dd20-0", + "165/2600e15a-0", + "165/26008444-0", + "165/260145c5-0", + "165/26003a0c-0", + "165/260106ba-0", + "165/26001548-0", + "167/2a0092b0-0", + "167/2a014dbe-0", + "167/2a003ce6-0", + "169/1800c645-0", + "171/2500014d-0", + "176/1d0021c2-0", + "176/1d014abf-0", + "176/1d00e714-0", + "176/1d0159cb-0", + "176/1e016629-0", + "178/000102b8-0", + "191/23008fdb-0", + "191/2300187f-0", + "191/2300ae68-0", + "191/230076dd-0", + "191/24007d7e-0", + "192/000107b5-0", + "195/1f012359-0", + "195/1f00f751-0", + "195/1f011331-0", + "195/1e00d999-0", + "196/1c01304e-0", + "198/1a00e02f-0", + "198/050084ac-0", + "198/1a0075fa-0", + "199/1e001742-0", + "199/1e00116a-0", + "199/1e011d00-0", + "199/1e018040-0", + "199/1e001107-0", +] + + +class MVImgNet(SequenceDataset): + min_depth = 0.005 + max_depth = 10.0 + # weird scale issue, should be 1000, but avg depth is ~10meters... + depth_scale = 1000.0 + test_split = "train.txt" + train_split = "train.txt" + sequences_file = "sequences.json" + hdf5_paths = ["MVImgNet.hdf5"] + invalid_sequences = INVALID_SEQUENCES + + def __init__( + self, + image_shape: tuple[int, int], + split_file: str, + test_mode: bool, + normalize: bool, + augmentations_db: dict[str, Any], + resize_method: str, + mini: float = 1.0, + num_frames: int = 1, + benchmark: bool = False, + decode_fields: list[str] = ["image", "depth"], + inplace_fields: list[str] = ["intrinsics", "cam2w"], + **kwargs, + ) -> None: + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + num_frames=num_frames, + decode_fields=decode_fields, + inplace_fields=inplace_fields, + **kwargs, + ) + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["si"] = [True] * self.num_frames * self.num_copies + results["dense"] = [False] * self.num_frames * self.num_copies + results["quality"] = [2] * self.num_frames * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/mvsynth.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/mvsynth.py new file mode 100644 index 0000000000000000000000000000000000000000..2418ce2646ccaf6ec12824199cb7c75d071c9fce --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/mvsynth.py @@ -0,0 +1,51 @@ +from typing import Any + +from unidepth.datasets.sequence_dataset import SequenceDataset + + +class MVSynth(SequenceDataset): + min_depth = 0.1 + max_depth = 1000.0 + depth_scale = 256.0 + test_split = "val.txt" + train_split = "train.txt" + sequences_file = "sequences.json" + hdf5_paths = [f"MVSynth.hdf5"] + + def __init__( + self, + image_shape: tuple[int, int], + split_file: str, + test_mode: bool, + normalize: bool, + augmentations_db: dict[str, Any], + resize_method: str, + mini: float = 1.0, + num_frames: int = 1, + benchmark: bool = False, + decode_fields: list[str] = ["image", "depth"], + inplace_fields: list[str] = ["K", "cam2w"], + **kwargs, + ) -> None: + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + num_frames=num_frames, + decode_fields=decode_fields, + inplace_fields=inplace_fields, + **kwargs, + ) + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [True] * self.num_frames * self.num_copies + results["synthetic"] = [True] * self.num_frames * self.num_copies + results["si"] = [True] * self.num_frames * self.num_copies + results["quality"] = [0] * self.num_frames * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/nerds360.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/nerds360.py new file mode 100644 index 0000000000000000000000000000000000000000..e9051087d1cb23178cb7c79dab8c57f7741261b4 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/nerds360.py @@ -0,0 +1,49 @@ +from typing import Any + +from unidepth.datasets.sequence_dataset import SequenceDataset + + +class NeRDS360(SequenceDataset): + min_depth = 0.01 + max_depth = 1000.0 + depth_scale = 1000.0 + test_split = "val.txt" + train_split = "train.txt" + sequences_file = "sequences.json" + hdf5_paths = ["NeRDS360.hdf5"] + + def __init__( + self, + image_shape: tuple[int, int], + split_file: str, + test_mode: bool, + normalize: bool, + augmentations_db: dict[str, Any], + resize_method: str, + mini: float = 1.0, + num_frames: int = 1, + benchmark: bool = False, + decode_fields: list[str] = ["image", "depth"], + inplace_fields: list[str] = ["K", "cam2w"], + **kwargs, + ) -> None: + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + num_frames=num_frames, + decode_fields=decode_fields, + inplace_fields=inplace_fields, + **kwargs, + ) + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [True] * self.num_frames * self.num_copies + results["quality"] = [1] * self.num_frames * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/niantic_mapfree.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/niantic_mapfree.py new file mode 100644 index 0000000000000000000000000000000000000000..ba61f361b58aeee795ee359915377962b67b1bea --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/niantic_mapfree.py @@ -0,0 +1,50 @@ +from typing import Any + +from unidepth.datasets.sequence_dataset import SequenceDataset + + +class NianticMapFree(SequenceDataset): + min_depth = 0.1 + max_depth = 250.0 + depth_scale = 512.0 + test_split = "train.txt" + train_split = "train.txt" + sequences_file = "sequences.json" + hdf5_paths = [f"NianticMapFree.hdf5"] + + def __init__( + self, + image_shape: tuple[int, int], + split_file: str, + test_mode: bool, + normalize: bool, + augmentations_db: dict[str, Any], + resize_method: str, + mini: float = 1.0, + num_frames: int = 1, + benchmark: bool = False, + decode_fields: list[str] = ["image", "depth"], + inplace_fields: list[str] = ["K", "cam2w"], + **kwargs, + ) -> None: + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + num_frames=num_frames, + decode_fields=decode_fields, + inplace_fields=inplace_fields, + **kwargs, + ) + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["si"] = [True] * self.num_frames * self.num_copies + results["dense"] = [False] * self.num_frames * self.num_copies + results["quality"] = [2] * self.num_frames * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/nuscenes.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/nuscenes.py new file mode 100644 index 0000000000000000000000000000000000000000..60c4f04de802a27d8313dffc302ce2212b2a1904 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/nuscenes.py @@ -0,0 +1,89 @@ +import json +import os + +import h5py +import numpy as np +import torch + +from unidepth.datasets.image_dataset import ImageDataset +from unidepth.datasets.utils import DatasetFromList + + +class Nuscenes(ImageDataset): + min_depth = 0.05 + max_depth = 80.0 + depth_scale = 256.0 + test_split = "val.txt" + train_split = "train.txt" + intrisics_file = "intrinsics.json" + # hdf5_paths = ["Nuscenes2.hdf5"] + hdf5_paths = [f"nuscenes/nuscenes_{i}.hdf5" for i in range(8)] + + def __init__( + self, + image_shape, + split_file, + test_mode, + benchmark=False, + augmentations_db={}, + normalize=True, + resize_method="hard", + mini=1.0, + **kwargs, + ): + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + **kwargs, + ) + self.test_mode = test_mode + + self.load_dataset() + + def load_dataset(self): + h5file = h5py.File( + os.path.join(self.data_root, self.hdf5_paths[0]), + "r", + libver="latest", + swmr=True, + ) + txt_file = np.array(h5file[self.split_file]) + txt_string = txt_file.tostring().decode("ascii").strip("\n") + intrinsics = np.array(h5file[self.intrisics_file]).tostring().decode("ascii") + intrinsics = json.loads(intrinsics) + + dataset = [] + for line in txt_string.split("\n"): + image_filename, depth_filename, chunk_idx = line.strip().split(" ") + intrinsics_val = torch.tensor(intrinsics[image_filename]).squeeze()[:, :3] + sample = [image_filename, depth_filename, intrinsics_val, chunk_idx] + dataset.append(sample) + h5file.close() + + if not self.test_mode: + dataset = self.chunk(dataset, chunk_dim=6, pct=self.mini) + if self.test_mode and not self.benchmark: + dataset = self.chunk(dataset, chunk_dim=6, pct=0.1) + + self.dataset = DatasetFromList(dataset) + self.log_load_dataset() + + def get_mapper(self): + return { + "image_filename": 0, + "depth_filename": 1, + "K": 2, + "chunk_idx": 3, + } + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [False] * self.num_copies + results["quality"] = [1] * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/nyuv2.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/nyuv2.py new file mode 100644 index 0000000000000000000000000000000000000000..e597ad000349e5d79c0b27e8214b1cbdbb515a56 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/nyuv2.py @@ -0,0 +1,112 @@ +import os + +import h5py +import numpy as np +import torch + +from unidepth.datasets.image_dataset import ImageDataset +from unidepth.datasets.pipelines import AnnotationMask +from unidepth.datasets.utils import DatasetFromList +from unidepth.utils import identity + + +class NYUv2Depth(ImageDataset): + CAM_INTRINSIC = { + "ALL": torch.tensor( + [ + [5.1885790117450188e02, 0, 3.2558244941119034e02], + [0, 5.1946961112127485e02, 2.5373616633400465e02], + [0, 0, 1], + ] + ) + } + min_depth = 0.005 + max_depth = 10.0 + depth_scale = 1000.0 + log_mean = 0.9140 + log_std = 0.4825 + test_split = "nyu_test.txt" + train_split = "nyu_train.txt" + hdf5_paths = ["nyuv2.hdf5"] + + def __init__( + self, + image_shape, + split_file, + test_mode, + crop=None, + benchmark=False, + augmentations_db={}, + normalize=True, + resize_method="hard", + mini=1.0, + **kwargs, + ): + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + **kwargs, + ) + self.masker = AnnotationMask( + min_value=0.0, + max_value=self.max_depth if test_mode else None, + custom_fn=self.eval_mask if test_mode else lambda x, *args, **kwargs: x, + ) + self.test_mode = test_mode + self.load_dataset() + + def load_dataset(self): + h5file = h5py.File( + os.path.join(self.data_root, self.hdf5_paths[0]), + "r", + libver="latest", + swmr=True, + ) + txt_file = np.array(h5file[self.split_file]) + txt_string = txt_file.tostring().decode("ascii")[:-1] # correct the -1 + h5file.close() + dataset = [] + for line in txt_string.split("\n"): + image_filename, depth_filename, _ = line.strip().split(" ") + sample = [ + image_filename, + depth_filename, + ] + dataset.append(sample) + + if not self.test_mode: + dataset = self.chunk(dataset, chunk_dim=1, pct=self.mini) + + self.dataset = DatasetFromList(dataset) + self.log_load_dataset() + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [True] * self.num_copies + return results + + def get_intrinsics(self, idx, image_name): + return self.CAM_INTRINSIC["ALL"].clone() + + def eval_mask(self, valid_mask, info={}): + border_mask = torch.zeros_like(valid_mask) + border_mask[..., 45:-9, 41:-39] = 1 + return torch.logical_and(valid_mask, border_mask) + + def get_mapper(self): + return { + "image_filename": 0, + "depth_filename": 1, + } + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [True] * self.num_copies + results["quality"] = [2] * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/oasis.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/oasis.py new file mode 100644 index 0000000000000000000000000000000000000000..60473717cb8dc2ecf3a7d1e83e80b2895b902a86 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/oasis.py @@ -0,0 +1,80 @@ +import os + +import h5py +import numpy as np +import torch + +from unidepth.datasets.image_dataset import ImageDataset +from unidepth.datasets.utils import DatasetFromList + + +class OASISv2(ImageDataset): + min_depth = 0.01 + max_depth = 400.0 + depth_scale = 1000.0 + test_split = "val.txt" + train_split = "train.txt" + hdf5_paths = ["Oasis2.hdf5"] + + def __init__( + self, + image_shape, + split_file, + test_mode, + crop=None, + benchmark=False, + augmentations_db={}, + normalize=True, + resize_method="hard", + mini=1.0, + **kwargs, + ): + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + **kwargs, + ) + self.test_mode = test_mode + self.load_dataset() + + def load_dataset(self): + h5file = h5py.File( + os.path.join(self.data_root, self.hdf5_paths[0]), + "r", + libver="latest", + swmr=True, + ) + txt_file = np.array(h5file[self.split_file]) + txt_string = txt_file.tostring().decode("ascii") # [:-1] # correct the -1 + + dataset = [] + # with open(os.path.join(os.environ["TMPDIR"], self.split_file), "w") as f: + # f.write(txt_string) + for line in txt_string.split("\n"): + image_filename, depth_filename = line.strip().split(" ") + sample = [image_filename, depth_filename] + dataset.append(sample) + h5file.close() + if not self.test_mode: + dataset = self.chunk(dataset, chunk_dim=1, pct=self.mini) + + self.dataset = DatasetFromList(dataset) + self.log_load_dataset() + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["ssi"] = [True] + results["valid_camera"] = [False] + return results + + def get_mapper(self): + return { + "image_filename": 0, + "depth_filename": 1, + } diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/pipelines/__init__.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/pipelines/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d7c09b39628a504f431a4266304e0f0d7ca1bfac --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/pipelines/__init__.py @@ -0,0 +1,9 @@ +from .formating import AnnotationMask, Collect +from .transforms import (Compose, ContextCrop, Crop, GaussianBlur, KittiCrop, + PanoCrop, PanoRoll, RandomAutoContrast, + RandomBrightness, RandomColor, RandomColorJitter, + RandomContrast, RandomEqualize, RandomFiller, + RandomFlip, RandomGamma, RandomGrayscale, + RandomInvert, RandomMasking, RandomPosterize, + RandomSaturation, RandomSharpness, RandomShear, + RandomSolarize, RandomTranslate, Rotate) diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/pipelines/formating.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/pipelines/formating.py new file mode 100644 index 0000000000000000000000000000000000000000..51b000b91321727f8c49a996d4455f84d527ce4d --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/pipelines/formating.py @@ -0,0 +1,95 @@ +from collections.abc import Sequence + +import numpy as np +import torch + + +class Collect(object): + def __init__( + self, + keys, + meta_keys=( + "filename", + "keyframe_idx", + "sequence_name", + "image_filename", + "depth_filename", + "image_ori_shape", + "camera", + "original_camera", + "sfm", + "image_shape", + "resized_shape", + "scale_factor", + "rotation", + "resize_factor", + "flip", + "flip_direction", + "dataset_name", + "paddings", + "max_value", + "log_mean", + "log_std", + "image_rescale", + "focal_rescale", + "depth_rescale", + ), + ): + self.keys = keys + self.meta_keys = meta_keys + + def __call__(self, results): + data_keys = [key for field in self.keys for key in results.get(field, [])] + data = { + key: { + sequence_key: results[key][sequence_key] + for sequence_key in results["sequence_fields"] + } + for key in data_keys + } + data["img_metas"] = { + key: value for key, value in results.items() if key not in data_keys + } + return data + + def __repr__(self): + return ( + self.__class__.__name__ + f"(keys={self.keys}, meta_keys={self.meta_keys})" + ) + + +class AnnotationMask(object): + def __init__(self, min_value, max_value, custom_fn=lambda x: x): + self.min_value = min_value + self.max_value = max_value + self.custom_fn = custom_fn + + def __call__(self, results): + for key in results.get("gt_fields", []): + if key + "_mask" in results["mask_fields"]: + if "flow" in key: + for sequence_idx in results.get("sequence_fields", []): + boundaries = (results[key][sequence_idx] >= -1) & ( + results[key][sequence_idx] <= 1 + ) + boundaries = boundaries[:, :1] & boundaries[:, 1:] + results[key + "_mask"][sequence_idx] = ( + results[key + "_mask"][sequence_idx] & boundaries + ) + continue + for sequence_idx in results.get("sequence_fields", []): + mask = results[key][sequence_idx] > self.min_value + if self.max_value is not None: + mask = mask & (results[key][sequence_idx] < self.max_value) + mask = self.custom_fn(mask, info=results) + if key + "_mask" not in results: + results[key + "_mask"] = {} + results[key + "_mask"][sequence_idx] = mask.bool() + results["mask_fields"].add(key + "_mask") + return results + + def __repr__(self): + return ( + self.__class__.__name__ + + f"(min_value={self.min_value}, max_value={ self.max_value})" + ) diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/pipelines/transforms.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/pipelines/transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..c08f49e61cfbabd0b40b01e0e60cf3c9977a0d55 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/pipelines/transforms.py @@ -0,0 +1,1464 @@ +import os +import random +from copy import deepcopy +from math import ceil, exp, log, log2, log10, tanh +from typing import Dict, List, Tuple + +import numpy as np +import torch +import torch.nn.functional as F +import torchvision.transforms.v2.functional as TF + +from unidepth.utils.geometric import downsample + + +class PanoCrop: + def __init__(self, crop_v=0.1): + self.crop_v = crop_v + + def _crop_data(self, results, crop_size): + """Function to randomly crop images, bounding boxes, masks, semantic + segmentation maps. + + Args: + results (dict): Result dict from loading pipeline. + crop_size (tuple): Expected absolute size after cropping, (h, w). + allow_negative_crop (bool): Whether to allow a crop that does not + contain any bbox area. Default to False. + + Returns: + dict: Randomly cropped results, 'image_shape' key in result dict is + updated according to crop size. + """ + offset_w, offset_h = crop_size + left, top, right, bottom = offset_w[0], offset_h[0], offset_w[1], offset_h[1] + H, W = results["image"].shape[-2:] + for key in results.get("image_fields", ["image"]): + img = results[key][..., top : H - bottom, left : W - right] + results[key] = img + results["image_shape"] = tuple(img.shape) + + for key in results.get("gt_fields", []): + results[key] = results[key][..., top : H - bottom, left : W - right] + + for key in results.get("mask_fields", []): + results[key] = results[key][..., top : H - bottom, left : W - right] + + results["camera"].crop(left, top, right, bottom) + return results + + def __call__(self, results): + H, W = results["image"].shape[-2:] + crop_w = (0, 0) + crop_h = (int(H * self.crop_v), int(H * self.crop_v)) + results = self._crop_data(results, (crop_w, crop_h)) + return results + + +class PanoRoll: + def __init__(self, roll=[-0.5, 0.5]): + self.roll = roll + + def __call__(self, results): + W = results["image"].shape[-1] + roll = random.randint(int(W * self.roll[0]), int(W * self.roll[1])) + for key in results.get("image_fields", ["image"]): + img = results[key] + img = torch.roll(img, roll, dims=-1) + results[key] = img + for key in results.get("gt_fields", []): + results[key] = torch.roll(results[key], roll, dims=-1) + for key in results.get("mask_fields", []): + results[key] = torch.roll(results[key], roll, dims=-1) + return results + + +class RandomFlip: + """Flip the points & bbox. + + If the input dict contains the key "flip", then the flag will be used, + otherwise it will be randomly decided by a ratio specified in the init + method. + + Args: + flip_ratio_bev_horizontal (float, optional): The flipping probability + in horizontal direction. Defaults to 0.0. + flip_ratio_bev_vertical (float, optional): The flipping probability + in vertical direction. Defaults to 0.0. + """ + + def __init__(self, direction="horizontal", prob=0.5, **kwargs): + self.flip_ratio = prob + valid_directions = ["horizontal", "vertical", "diagonal"] + if isinstance(direction, str): + assert direction in valid_directions + elif isinstance(direction, list): + assert set(direction).issubset(set(valid_directions)) + else: + raise ValueError("direction must be either str or list of str") + self.direction = direction + + def __call__(self, results): + """Call function to flip points, values in the ``bbox3d_fields`` and + also flip 2D image and its annotations. + + Args: + results (dict): Result dict from loading pipeline. + + Returns: + dict: Flipped results, 'flip', 'flip_direction', + """ + if "flip" not in results: + if isinstance(self.direction, list): + # None means non-flip + direction_list = self.direction + [None] + else: + # None means non-flip + direction_list = [self.direction, None] + + if isinstance(self.flip_ratio, list): + non_flip_ratio = 1 - sum(self.flip_ratio) + flip_ratio_list = self.flip_ratio + [non_flip_ratio] + else: + non_flip_ratio = 1 - self.flip_ratio + # exclude non-flip + single_ratio = self.flip_ratio / (len(direction_list) - 1) + flip_ratio_list = [single_ratio] * (len(direction_list) - 1) + [ + non_flip_ratio + ] + + cur_dir = np.random.choice(direction_list, p=flip_ratio_list) + + results["flip"] = cur_dir is not None + + if "flip_direction" not in results: + results["flip_direction"] = cur_dir + + if results["flip"]: + # flip image + if results["flip_direction"] != "vertical": + for key in results.get("image_fields", ["image"]): + results[key] = TF.hflip(results[key]) + for key in results.get("mask_fields", []): + results[key] = TF.hflip(results[key]) + for key in results.get("gt_fields", []): + results[key] = TF.hflip(results[key]) + if "flow" in key: # flip u direction + results[key][:, 0] = -results[key][:, 0] + + H, W = results["image"].shape[-2:] + results["camera"] = results["camera"].flip( + H=H, W=W, direction="horizontal" + ) + # results["K"][..., 0, 2] = results["image"].shape[-1] - results["K"][..., 0, 2] + # flip: - t_x rotate around y by: pi - angle_y * 2 + flip_transform = torch.tensor( + [[-1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]], + dtype=torch.float32, + ).unsqueeze(0) + repeats = (results["cam2w"].shape[0],) + (1,) * ( + results["cam2w"].ndim - 1 + ) + results["cam2w"] = flip_transform.repeat(*repeats) @ results["cam2w"] + + if results["flip_direction"] != "horizontal": + for key in results.get("image_fields", ["image"]): + results[key] = TF.vflip(results[key]) + for key in results.get("mask_fields", []): + results[key] = TF.vflip(results[key]) + for key in results.get("gt_fields", []): + results[key] = TF.vflip(results[key]) + results["K"][..., 1, 2] = ( + results["image"].shape[-2] - results["K"][..., 1, 2] + ) + results["flip"] = [results["flip"]] * len(results["image"]) + return results + + def __repr__(self): + """str: Return a string that describes the module.""" + repr_str = self.__class__.__name__ + repr_str += f" flip_ratio={self.flip_ratio})" + return repr_str + + +class Crop: + def __init__( + self, + crop_size, + crop_type="absolute", + crop_offset=(0, 0), + ): + if crop_type not in [ + "relative_range", + "relative", + "absolute", + "absolute_range", + ]: + raise ValueError(f"Invalid crop_type {crop_type}.") + if crop_type in ["absolute", "absolute_range"]: + assert crop_size[0] > 0 and crop_size[1] > 0 + assert isinstance(crop_size[0], int) and isinstance(crop_size[1], int) + else: + assert 0 < crop_size[0] <= 1 and 0 < crop_size[1] <= 1 + self.crop_size = crop_size + self.crop_type = crop_type + self.offset_h, self.offset_w = ( + crop_offset[: len(crop_offset) // 2], + crop_offset[len(crop_offset) // 2 :], + ) + + def _get_crop_size(self, image_shape): + h, w = image_shape + if self.crop_type == "absolute": + return (min(self.crop_size[0], h), min(self.crop_size[1], w)) + elif self.crop_type == "absolute_range": + assert self.crop_size[0] <= self.crop_size[1] + crop_h = np.random.randint( + min(h, self.crop_size[0]), min(h, self.crop_size[1]) + 1 + ) + crop_w = np.random.randint( + min(w, self.crop_size[0]), min(w, self.crop_size[1]) + 1 + ) + return crop_h, crop_w + elif self.crop_type == "relative": + crop_h, crop_w = self.crop_size + return int(h * crop_h + 0.5), int(w * crop_w + 0.5) + elif self.crop_type == "relative_range": + crop_size = np.asarray(self.crop_size, dtype=np.float32) + crop_h, crop_w = crop_size + np.random.rand(2) * (1 - crop_size) + return int(h * crop_h + 0.5), int(w * crop_w + 0.5) + + def _crop_data(self, results, crop_size): + assert crop_size[0] > 0 and crop_size[1] > 0 + for key in results.get("image_fields", ["image"]): + img = results[key] + img = TF.crop( + img, self.offset_h[0], self.offset_w[0], crop_size[0], crop_size[1] + ) + results[key] = img + results["image_shape"] = tuple(img.shape) + + for key in results.get("gt_fields", []): + gt = results[key] + results[key] = TF.crop( + gt, self.offset_h[0], self.offset_w[0], crop_size[0], crop_size[1] + ) + + # crop semantic seg + for key in results.get("mask_fields", []): + mask = results[key] + results[key] = TF.crop( + mask, self.offset_h[0], self.offset_w[0], crop_size[0], crop_size[1] + ) + + results["K"][..., 0, 2] = results["K"][..., 0, 2] - self.offset_w[0] + results["K"][..., 1, 2] = results["K"][..., 1, 2] - self.offset_h[0] + return results + + def __call__(self, results): + image_shape = results["image"].shape[-2:] + crop_size = self._get_crop_size(image_shape) + results = self._crop_data(results, crop_size) + + return results + + def __repr__(self): + repr_str = self.__class__.__name__ + repr_str += f"(crop_size={self.crop_size}, " + repr_str += f"crop_type={self.crop_type}, " + return repr_str + + +class KittiCrop: + def __init__(self, crop_size): + self.crop_size = crop_size + + def _crop_data(self, results, crop_size): + """Function to randomly crop images, bounding boxes, masks, semantic + segmentation maps. + + Args: + results (dict): Result dict from loading pipeline. + crop_size (tuple): Expected absolute size after cropping, (h, w). + allow_negative_crop (bool): Whether to allow a crop that does not + contain any bbox area. Default to False. + + Returns: + dict: Randomly cropped results, 'image_shape' key in result dict is + updated according to crop size. + """ + assert crop_size[0] > 0 and crop_size[1] > 0 + for key in results.get("image_fields", ["image"]): + img = results[key] + h, w = img.shape[-2:] + offset_h, offset_w = int(h - self.crop_size[0]), int( + (w - self.crop_size[1]) / 2 + ) + + # crop the image + img = TF.crop(img, offset_h, offset_w, crop_size[0], crop_size[1]) + results[key] = img + results["image_shape"] = tuple(img.shape) + + for key in results.get("gt_fields", []): + gt = results[key] + results[key] = TF.crop(gt, offset_h, offset_w, crop_size[0], crop_size[1]) + + # crop semantic seg + for key in results.get("mask_fields", []): + mask = results[key] + results[key] = TF.crop(mask, offset_h, offset_w, crop_size[0], crop_size[1]) + + results["camera"].crop(offset_w, offset_h) + return results + + def __call__(self, results): + """Call function to randomly crop images, bounding boxes, masks, + semantic segmentation maps. + + Args: + results (dict): Result dict from loading pipeline. + + Returns: + dict: Randomly cropped results, 'image_shape' key in result dict is + updated according to crop size. + """ + results = self._crop_data(results, self.crop_size) + + return results + + def __repr__(self): + repr_str = self.__class__.__name__ + repr_str += f"(crop_size={self.crop_size}, " + return repr_str + + +class RandomMasking: + def __init__( + self, + mask_ratio, + mask_patch=16, + prob=0.5, + warmup_steps=50000, + sampling="random", + curriculum=False, + ): + self.mask_patch = mask_patch + self.prob = prob + self.mask_ratio = mask_ratio + self.warmup_steps = max(1, warmup_steps) + self.hard_bound = 1 + self.idx = 0 + self.curriculum = curriculum + self.sampling = sampling + self.low_bound = 0.0 + self.up_bound = 0.0 + + def __call__(self, results): + B, _, H, W = results["image"].shape + device = results["image"].device + down_size = H // self.mask_patch, W // self.mask_patch + if np.random.random() > self.prob: # fill with dummy + return self._nop(results, down_size, device) + + validity_mask = results["validity_mask"].float().reshape(B, -1, H, W) + validity_mask = F.interpolate(validity_mask, size=down_size).bool() + validity_mask = validity_mask.reshape(B, 1, *down_size) + is_random = self.is_warmup or results.get("guidance") is None + + if not is_random: + guidance = F.interpolate(results["guidance"], size=(H, W), mode="bilinear") + results["guidance"] = -F.max_pool2d( + -guidance, kernel_size=self.mask_patch, stride=self.mask_patch + ) + + if is_random and self.sampling == "inverse": + sampling = self.inverse_sampling + elif is_random and self.sampling == "random": + sampling = self.random_sampling + else: + sampling = self.guided_sampling + mask_ratio = np.random.uniform(self.low_bound, self.up_bound) + for key in results.get("image_fields", ["image"]): + mask = sampling(results, mask_ratio, down_size, validity_mask, device) + results[key + "_mask"] = mask + return results + + def _nop(self, results, down_size, device): + B = results["image"].shape[0] + for key in results.get("image_fields", ["image"]): + mask_blocks = torch.zeros(size=(B, 1, *down_size), device=device) + results[key + "_mask"] = mask_blocks + return results + + def random_sampling(self, results, mask_ratio, down_size, validity_mask, device): + B = results["image"].shape[0] + prob_blocks = torch.rand(size=(B, 1, *down_size), device=device) + mask_blocks = torch.logical_and(prob_blocks < mask_ratio, validity_mask) + return mask_blocks + + def inverse_sampling(self, results, mask_ratio, down_size, validity_mask, device): + # from PIL import Image + # from unidepth.utils import colorize + def area_sample(depth, fx, fy): + dtype = depth.dtype + B = depth.shape[0] + H, W = down_size + depth = downsample(depth, depth.shape[-2] // H) + depth[depth > 200] = 50 # set sky as if depth 50 meters + pixel_area3d = depth / torch.sqrt(fx * fy) + + # Set invalid as -1 (no div problem) -> then clip to 0.0 + pixel_area3d[depth == 0.0] = -1 + prob_density = (1 / pixel_area3d).clamp(min=0.0).square() + prob_density = prob_density / prob_density.sum( + dim=(-1, -2), keepdim=True + ).clamp(min=1e-5) + # Image.fromarray((prob_density[0] * 255 * 100).clamp(min=0.0, max=255.0).squeeze().cpu().byte().numpy()).save("prob_density.png") + + # Sample locations based on prob_density + prob_density_flat = prob_density.view(B, -1) + + # Get the avgerage valid locations, of those we mask self.mask_ratio + valid_locations = (prob_density_flat > 0).to(dtype).sum(dim=1) + + masks = [] + for i in range(B): + num_samples = int(valid_locations[i] * mask_ratio) + mask = torch.zeros_like(prob_density_flat[i]) + # Sample indices + if num_samples > 0: + sampled_indices_flat = torch.multinomial( + prob_density_flat[i], num_samples, replacement=False + ) + mask.scatter_(0, sampled_indices_flat, 1) + masks.append(mask) + return torch.stack(masks).bool().view(B, 1, H, W) + + def random_sample(validity_mask): + prob_blocks = torch.rand( + size=(validity_mask.shape[0], 1, *down_size), device=device + ) + mask = torch.logical_and(prob_blocks < mask_ratio, validity_mask) + return mask + + fx = results["K"][..., 0, 0].view(-1, 1, 1, 1) / self.mask_patch + fy = results["K"][..., 1, 1].view(-1, 1, 1, 1) / self.mask_patch + + valid = ~results["ssi"] & ~results["si"] & results["valid_camera"] + mask_blocks = torch.zeros_like(validity_mask) + if valid.any(): + out = area_sample(results["depth"][valid], fx[valid], fy[valid]) + mask_blocks[valid] = out + if (~valid).any(): + mask_blocks[~valid] = random_sample(validity_mask[~valid]) + + # mask_blocks_ = (mask_blocks.float() * 255).squeeze(1).byte().cpu().numpy() + # Image.fromarray(mask_blocks_[0]).save("mask1.png") + # Image.fromarray(mask_blocks_[-1]).save("mask2.png") + # dd = results["depth"] + # Image.fromarray(colorize(dd[0].squeeze().cpu().numpy())).save("depth1_p.png") + # Image.fromarray(colorize(dd[-1].squeeze().cpu().numpy())).save("depth2_p.png") + # dd = downsample(dd, dd.shape[-2] // down_size[0]) + # Image.fromarray(colorize(dd[0].squeeze().cpu().numpy())).save("depth1.png") + # Image.fromarray(colorize(dd[-1].squeeze().cpu().numpy())).save("depth2.png") + # raise ValueError + + return mask_blocks + + def guided_sampling(self, results, mask_ratio, down_size, validity_mask, device): + # get the lowest (based on guidance) "mask_ratio" quantile of the patches that are in validity mask + B = results["image"].shape[0] + guidance = results["guidance"] + mask_blocks = torch.zeros(size=(B, 1, *down_size), device=device) + for b in range(B): + low_bound = torch.quantile( + guidance[b][validity_mask[b]], max(0.0, self.hard_bound - mask_ratio) + ) + up_bound = torch.quantile( + guidance[b][validity_mask[b]], min(1.0, self.hard_bound) + ) + mask_blocks[b] = torch.logical_and( + guidance[b] < up_bound, guidance[b] > low_bound + ) + mask_blocks = torch.logical_and(mask_blocks, validity_mask) + return mask_blocks + + def step(self): + self.idx += 1 + # schedule hard from 1.0 to self.mask_ratio + if self.curriculum: + step = max(0, self.idx / self.warmup_steps / 2 - 0.5) + self.hard_bound = 1 - (1 - self.mask_ratio) * tanh(step) + self.up_bound = self.mask_ratio * tanh(step) + self.low_bound = 0.2 * tanh(step) + + @property + def is_warmup(self): + return self.idx < self.warmup_steps + + +class Rotate: + def __init__( + self, angle, center=None, img_fill_val=(123.68, 116.28, 103.53), prob=0.5 + ): + if isinstance(img_fill_val, (float, int)): + img_fill_val = tuple([float(img_fill_val)] * 3) + elif isinstance(img_fill_val, tuple): + assert len(img_fill_val) == 3, ( + "image_fill_val as tuple must " + f"have 3 elements. got {len(img_fill_val)}." + ) + img_fill_val = tuple([float(val) for val in img_fill_val]) + else: + raise ValueError("image_fill_val must be float or tuple with 3 elements.") + assert np.all( + [0 <= val <= 255 for val in img_fill_val] + ), f"all elements of img_fill_val should between range [0,255] got {img_fill_val}." + assert 0 <= prob <= 1.0, f"The probability should be in range [0,1]bgot {prob}." + self.center = center + self.img_fill_val = img_fill_val + self.prob = prob + self.random = not isinstance(angle, (float, int)) + self.angle = angle + + def _rotate(self, results, angle, center=None, fill_val=0.0): + for key in results.get("image_fields", ["image"]): + img = results[key] + img_rotated = TF.rotate( + img, + angle, + center=center, + interpolation=TF.InterpolationMode.NEAREST_EXACT, + fill=self.img_fill_val, + ) + results[key] = img_rotated.to(img.dtype) + results["image_shape"] = results[key].shape + + for key in results.get("mask_fields", []): + results[key] = TF.rotate( + results[key], + angle, + center=center, + interpolation=TF.InterpolationMode.NEAREST_EXACT, + fill=fill_val, + ) + + for key in results.get("gt_fields", []): + results[key] = TF.rotate( + results[key], + angle, + center=center, + interpolation=TF.InterpolationMode.NEAREST_EXACT, + fill=fill_val, + ) + + def __call__(self, results): + if np.random.random() > self.prob: + return results + + angle = ( + (self.angle[1] - self.angle[0]) * np.random.rand() + self.angle[0] + if self.random + else np.random.choice([-1, 1], size=1) * self.angle + ) + self._rotate(results, angle, None, fill_val=0.0) + results["rotation"] = angle + return results + + +class RandomColor: + def __init__(self, level, prob=0.5): + self.random = not isinstance(level, (float, int)) + self.level = level + self.prob = prob + + def _adjust_color_img(self, results, factor=1.0): + for key in results.get("image_fields", ["image"]): + results[key] = TF.adjust_hue(results[key], factor) # .to(img.dtype) + + def __call__(self, results): + if np.random.random() > self.prob: + return results + factor = ( + ((self.level[1] - self.level[0]) * np.random.rand() + self.level[0]) + if self.random + else self.level + ) + self._adjust_color_img(results, factor) + return results + + +class RandomSaturation: + def __init__(self, level, prob=0.5): + self.random = not isinstance(level, (float, int)) + self.level = level + self.prob = prob + + def _adjust_saturation_img(self, results, factor=1.0): + for key in results.get("image_fields", ["image"]): + # NOTE defaultly the image should be BGR format + results[key] = TF.adjust_saturation(results[key], factor) # .to(img.dtype) + + def __call__(self, results): + if np.random.random() > self.prob: + return results + factor = ( + 2 ** ((self.level[1] - self.level[0]) * np.random.rand() + self.level[0]) + if self.random + else 2**self.level + ) + self._adjust_saturation_img(results, factor) + return results + + +class RandomSharpness: + def __init__(self, level, prob=0.5): + self.random = not isinstance(level, (float, int)) + self.level = level + self.prob = prob + + def _adjust_sharpeness_img(self, results, factor=1.0): + for key in results.get("image_fields", ["image"]): + # NOTE defaultly the image should be BGR format + results[key] = TF.adjust_sharpness(results[key], factor) # .to(img.dtype) + + def __call__(self, results): + if np.random.random() > self.prob: + return results + factor = ( + 2 ** ((self.level[1] - self.level[0]) * np.random.rand() + self.level[0]) + if self.random + else 2**self.level + ) + self._adjust_sharpeness_img(results, factor) + return results + + def __repr__(self): + repr_str = self.__class__.__name__ + repr_str += f"(level={self.level}, " + repr_str += f"prob={self.prob})" + return repr_str + + +class RandomSolarize: + def __init__(self, level, prob=0.5): + self.random = not isinstance(level, (float, int)) + self.level = level + self.prob = prob + + def _adjust_solarize_img(self, results, factor=255.0): + for key in results.get("image_fields", ["image"]): + results[key] = TF.solarize(results[key], factor) # .to(img.dtype) + + def __call__(self, results): + if np.random.random() > self.prob: + return results + factor = ( + ((self.level[1] - self.level[0]) * np.random.rand() + self.level[0]) + if self.random + else self.level + ) + self._adjust_solarize_img(results, factor) + return results + + +class RandomPosterize: + def __init__(self, level, prob=0.5): + self.random = not isinstance(level, (float, int)) + self.level = level + self.prob = prob + + def _posterize_img(self, results, factor=1.0): + for key in results.get("image_fields", ["image"]): + results[key] = TF.posterize(results[key], int(factor)) # .to(img.dtype) + + def __call__(self, results): + if np.random.random() > self.prob: + return results + factor = ( + ((self.level[1] - self.level[0]) * np.random.rand() + self.level[0]) + if self.random + else self.level + ) + self._posterize_img(results, factor) + return results + + +class RandomEqualize: + def __init__(self, prob=0.5): + assert 0 <= prob <= 1.0, "The probability should be in range [0,1]." + self.prob = prob + + def _imequalize(self, results): + for key in results.get("image_fields", ["image"]): + results[key] = TF.equalize(results[key]) # .to(img.dtype) + + def __call__(self, results): + if np.random.random() > self.prob: + return results + self._imequalize(results) + return results + + +class RandomBrightness: + def __init__(self, level, prob=0.5): + self.random = not isinstance(level, (float, int)) + self.level = level + self.prob = prob + + def _adjust_brightness_img(self, results, factor=1.0): + for key in results.get("image_fields", ["image"]): + results[key] = TF.adjust_brightness(results[key], factor) # .to(img.dtype) + + def __call__(self, results, level=None): + if np.random.random() > self.prob: + return results + factor = ( + 2 ** ((self.level[1] - self.level[0]) * np.random.rand() + self.level[0]) + if self.random + else 2**self.level + ) + self._adjust_brightness_img(results, factor) + return results + + +class RandomContrast: + def __init__(self, level, prob=0.5): + self.random = not isinstance(level, (float, int)) + self.level = level + self.prob = prob + + def _adjust_contrast_img(self, results, factor=1.0): + for key in results.get("image_fields", ["image"]): + results[key] = TF.adjust_contrast(results[key], factor) # .to(img.dtype) + + def __call__(self, results, level=None): + if np.random.random() > self.prob: + return results + factor = ( + 2 ** ((self.level[1] - self.level[0]) * np.random.rand() + self.level[0]) + if self.random + else 2**self.level + ) + self._adjust_contrast_img(results, factor) + return results + + +class RandomGamma: + def __init__(self, level, prob=0.5): + self.random = not isinstance(level, (float, int)) + self.level = level + self.prob = prob + + def __call__(self, results, level=None): + if np.random.random() > self.prob: + return results + factor = (self.level[1] - self.level[0]) * np.random.rand() + self.level[0] + for key in results.get("image_fields", ["image"]): + if "original" not in key: + results[key] = TF.adjust_gamma(results[key], 1 + factor) + return results + + +class RandomInvert: + def __init__(self, prob=0.5): + self.prob = prob + + def __call__(self, results): + if np.random.random() > self.prob: + return results + for key in results.get("image_fields", ["image"]): + if "original" not in key: + results[key] = TF.invert(results[key]) # .to(img.dtype) + return results + + +class RandomAutoContrast: + def __init__(self, prob=0.5): + self.prob = prob + + def _autocontrast_img(self, results): + for key in results.get("image_fields", ["image"]): + img = results[key] + results[key] = TF.autocontrast(img) # .to(img.dtype) + + def __call__(self, results): + if np.random.random() > self.prob: + return results + self._autocontrast_img(results) + return results + + +class RandomShear(object): + def __init__( + self, + level, + prob=0.5, + direction="horizontal", + ): + self.random = not isinstance(level, (float, int)) + self.level = level + self.prob = prob + self.direction = direction + + def _shear_img(self, results, magnitude): + for key in results.get("image_fields", ["image"]): + img_sheared = TF.affine( + results[key], + angle=0.0, + translate=[0.0, 0.0], + scale=1.0, + shear=magnitude, + interpolation=TF.InterpolationMode.BILINEAR, + fill=0.0, + ) + results[key] = img_sheared + + def _shear_masks(self, results, magnitude): + for key in results.get("mask_fields", []): + mask_sheared = TF.affine( + results[key], + angle=0.0, + translate=[0.0, 0.0], + scale=1.0, + shear=magnitude, + interpolation=TF.InterpolationMode.NEAREST_EXACT, + fill=0.0, + ) + results[key] = mask_sheared + + def _shear_gt( + self, + results, + magnitude, + ): + for key in results.get("gt_fields", []): + mask_sheared = TF.affine( + results[key], + angle=0.0, + translate=[0.0, 0.0], + scale=1.0, + shear=magnitude, + interpolation=TF.InterpolationMode.NEAREST_EXACT, + fill=0.0, + ) + results[key] = mask_sheared + + def __call__(self, results): + if np.random.random() > self.prob: + return results + magnitude = ( + ((self.level[1] - self.level[0]) * np.random.rand() + self.level[0]) + if self.random + else np.random.choice([-1, 1], size=1) * self.level + ) + if self.direction == "horizontal": + magnitude = [magnitude, 0.0] + else: + magnitude = [0.0, magnitude] + self._shear_img(results, magnitude) + self._shear_masks(results, magnitude) + self._shear_gt(results, magnitude) + return results + + +class RandomTranslate(object): + def __init__( + self, + range, + prob=0.5, + direction="horizontal", + ): + self.range = range + self.prob = prob + self.direction = direction + + def _translate_img(self, results, magnitude): + """Shear the image. + + Args: + results (dict): Result dict from loading pipeline. + magnitude (int | float): The magnitude used for shear. + direction (str): The direction for shear, either "horizontal" + or "vertical". + interpolation (str): Same as in :func:`mmcv.imshear`. + """ + for key in results.get("image_fields", ["image"]): + img_sheared = TF.affine( + results[key], + angle=0.0, + translate=magnitude, + scale=1.0, + shear=[0.0, 0.0], + interpolation=TF.InterpolationMode.BILINEAR, + fill=(123.68, 116.28, 103.53), + ) + results[key] = img_sheared + + def _translate_mask(self, results, magnitude): + """Shear the masks.""" + for key in results.get("mask_fields", []): + mask_sheared = TF.affine( + results[key], + angle=0.0, + translate=magnitude, + scale=1.0, + shear=[0.0, 0.0], + interpolation=TF.InterpolationMode.NEAREST_EXACT, + fill=0.0, + ) + results[key] = mask_sheared + + def _translate_gt( + self, + results, + magnitude, + ): + """Shear the segmentation maps.""" + for key in results.get("gt_fields", []): + mask_sheared = TF.affine( + results[key], + angle=0.0, + translate=magnitude, + scale=1.0, + shear=[0.0, 0.0], + interpolation=TF.InterpolationMode.NEAREST_EXACT, + fill=0.0, + ) + results[key] = mask_sheared + + def __call__(self, results): + """Call function to shear images, bounding boxes, masks and semantic + segmentation maps. + + Args: + results (dict): Result dict from loading pipeline. + + Returns: + dict: Sheared results. + """ + if np.random.random() > self.prob: + return results + magnitude = (self.range[1] - self.range[0]) * np.random.rand() + self.range[0] + if self.direction == "horizontal": + magnitude = [magnitude * results["image"].shape[1], 0] + else: + magnitude = [0, magnitude * results["image"].shape[0]] + self._translate_img(results, magnitude) + self._translate_mask(results, magnitude) + self._translate_gt(results, magnitude) + results["K"][..., 0, 2] = results["K"][..., 0, 2] + magnitude[0] + results["K"][..., 1, 2] = results["K"][..., 1, 2] + magnitude[1] + return results + + def __repr__(self): + repr_str = self.__class__.__name__ + repr_str += f"(range={self.range}, " + repr_str += f"prob={self.prob}, " + repr_str += f"direction={self.direction}, " + return repr_str + + +class RandomColorJitter: + def __init__(self, level, prob=0.9): + self.level = level + self.prob = prob + self.list_transform = [ + self._adjust_brightness_img, + # self._adjust_sharpness_img, + self._adjust_contrast_img, + self._adjust_saturation_img, + self._adjust_color_img, + ] + + def _adjust_contrast_img(self, results, factor=1.0): + """Adjust the image contrast.""" + for key in results.get("image_fields", ["image"]): + if "original" not in key: + img = results[key] + results[key] = TF.adjust_contrast(img, factor) + + def _adjust_sharpness_img(self, results, factor=1.0): + """Adjust the image contrast.""" + for key in results.get("image_fields", ["image"]): + if "original" not in key: + img = results[key] + results[key] = TF.adjust_sharpness(img, factor) + + def _adjust_brightness_img(self, results, factor=1.0): + """Adjust the brightness of image.""" + for key in results.get("image_fields", ["image"]): + if "original" not in key: + img = results[key] + results[key] = TF.adjust_brightness(img, factor) + + def _adjust_saturation_img(self, results, factor=1.0): + """Apply Color transformation to image.""" + for key in results.get("image_fields", ["image"]): + if "original" not in key: + img = results[key] + results[key] = TF.adjust_saturation(img, factor / 2.0) + + def _adjust_color_img(self, results, factor=1.0): + """Apply Color transformation to image.""" + for key in results.get("image_fields", ["image"]): + if "original" not in key: + img = results[key] + results[key] = TF.adjust_hue(img, (factor - 1.0) / 4.0) + + def __call__(self, results): + """Call function for color transformation. + Args: + results (dict): Results dict from loading pipeline. + + Returns: + dict: Results after the transformation. + """ + random.shuffle(self.list_transform) + for op in self.list_transform: + if np.random.random() < self.prob: + factor = 1.0 + ( + (self.level[1] - self.level[0]) * np.random.random() + self.level[0] + ) + op(results, factor) + return results + + +class RandomGrayscale: + def __init__(self, prob=0.1, num_output_channels=3): + super().__init__() + self.prob = prob + self.num_output_channels = num_output_channels + + def __call__(self, results): + if np.random.random() > self.prob: + return results + + for key in results.get("image_fields", ["image"]): + if "original" not in key: + results[key] = TF.rgb_to_grayscale( + results[key], num_output_channels=self.num_output_channels + ) + return results + + +def masked_nearest_interpolation(input, mask, target_size): + """ + Resize the depth map using bilinear interpolation, considering only valid pixels within NxN neighbors. + + Args: + depth (torch.Tensor): The depth map tensor of shape (H, W). + mask (torch.Tensor): The mask tensor of shape (H, W) where 1 indicates valid depth and 0 indicates missing depth. + target_size (tuple): The desired output size (target_H, target_W). + + Returns: + torch.Tensor: The resized depth map. + """ + B, C, H, W = input.shape + target_H, target_W = target_size + mask = mask.float() + + # Generate a grid of coordinates in the target space + grid_y, grid_x = torch.meshgrid( + torch.linspace(0, H - 1, target_H), + torch.linspace(0, W - 1, target_W), + indexing="ij", + ) + grid_y = grid_y.to(input.device) + grid_x = grid_x.to(input.device) + + # Calculate the floor and ceil of the grid coordinates to get the bounding box + x0 = torch.floor(grid_x).long().clamp(0, W - 1) + x1 = (x0 + 1).clamp(0, W - 1) + y0 = torch.floor(grid_y).long().clamp(0, H - 1) + y1 = (y0 + 1).clamp(0, H - 1) + + # Gather depth values at the four corners + Ia = input[..., y0, x0] + Ib = input[..., y1, x0] + Ic = input[..., y0, x1] + Id = input[..., y1, x1] + + # Gather corresponding mask values + ma = mask[..., y0, x0] + mb = mask[..., y1, x0] + mc = mask[..., y0, x1] + md = mask[..., y1, x1] + + # Calculate distances to each neighbor + # The distances are calculated from the center (grid_x, grid_y) to each corner + dist_a = (grid_x - x0.float()) ** 2 + (grid_y - y0.float()) ** 2 # Top-left + dist_b = (grid_x - x0.float()) ** 2 + (grid_y - y1.float()) ** 2 # Bottom-left + dist_c = (grid_x - x1.float()) ** 2 + (grid_y - y0.float()) ** 2 # Top-right + dist_d = (grid_x - x1.float()) ** 2 + (grid_y - y1.float()) ** 2 # Bottom-right + + # Stack the neighbors, their masks, and distances + stacked_values = torch.stack( + [Ia, Ib, Ic, Id], dim=-1 + ) # Shape: (B, C, target_H, target_W, 4) + stacked_masks = torch.stack( + [ma, mb, mc, md], dim=-1 + ) # Shape: (B, 1, target_H, target_W, 4) + stacked_distances = torch.stack( + [dist_a, dist_b, dist_c, dist_d], dim=-1 + ) # Shape: (target_H, target_W, 4) + stacked_distances = ( + stacked_distances.unsqueeze(0).unsqueeze(1).repeat(B, 1, 1, 1, 1) + ) # Shape: (B, 1, target_H, target_W, 4) + + # Set distances to infinity for invalid neighbors (so that invalid neighbors are never chosen) + stacked_distances[stacked_masks == 0] = float("inf") + + # Find the index of the nearest valid neighbor (the one with the smallest distance) + nearest_indices = stacked_distances.argmin(dim=-1, keepdim=True)[ + ..., :1 + ] # Shape: (B, 1, target_H, target_W, 1) + + # Select the corresponding depth value using the nearest valid neighbor index + interpolated_depth = torch.gather( + stacked_values, dim=-1, index=nearest_indices.repeat(1, C, 1, 1, 1) + ).squeeze(-1) + + # Set depth to zero where no valid neighbors were found + interpolated_depth = interpolated_depth * stacked_masks.sum(dim=-1).clip( + min=0.0, max=1.0 + ) + + return interpolated_depth + + +class ContextCrop: + def __init__( + self, + image_shape, + keep_original=False, + test_min_ctx=1.0, + train_ctx_range=[0.5, 1.5], + shape_constraints={}, + ): + self.image_shape = image_shape + self.keep_original = keep_original + self.test_min_ctx = test_min_ctx + self.train_ctx_range = train_ctx_range + self.shape_mult = shape_constraints["shape_mult"] + self.sample = shape_constraints["sample"] + self.ratio_bounds = shape_constraints["ratio_bounds"] + pixels_min = shape_constraints["pixels_min"] / ( + self.shape_mult * self.shape_mult + ) + pixels_max = shape_constraints["pixels_max"] / ( + self.shape_mult * self.shape_mult + ) + self.pixels_bounds = (pixels_min, pixels_max) + self.ctx = None + + def _transform_img(self, results, shapes): + for key in results.get("image_fields", ["image"]): + img = self.crop(results[key], **shapes) + img = TF.resize( + img, + results["resized_shape"], + interpolation=TF.InterpolationMode.BICUBIC, + antialias=True, + ) + results[key] = img + + def _transform_masks(self, results, shapes): + for key in results.get("mask_fields", []): + mask = self.crop(results[key].float(), **shapes).byte() + mask = masked_nearest_interpolation( + mask, mask > 0, results["resized_shape"] + ) + results[key] = mask + + def _transform_gt(self, results, shapes): + for key in results.get("gt_fields", []): + gt = self.crop(results[key], **shapes) + gt = masked_nearest_interpolation(gt, gt > 0, results["resized_shape"]) + results[key] = gt + + @staticmethod + def crop(img, height, width, top, left) -> torch.Tensor: + h, w = img.shape[-2:] + right = left + width + bottom = top + height + padding_ltrb = [ + max(-left + min(0, right), 0), + max(-top + min(0, bottom), 0), + max(right - max(w, left), 0), + max(bottom - max(h, top), 0), + ] + image_cropped = img[..., max(top, 0) : bottom, max(left, 0) : right] + return TF.pad(image_cropped, padding_ltrb) + + def test_closest_shape(self, image_shape): + h, w = image_shape + input_ratio = w / h + if self.sample: + input_pixels = int(ceil(h / self.shape_mult * w / self.shape_mult)) + pixels = max( + min(input_pixels, self.pixels_bounds[1]), self.pixels_bounds[0] + ) + ratio = min(max(input_ratio, self.ratio_bounds[0]), self.ratio_bounds[1]) + h = round((pixels / ratio) ** 0.5) + w = h * ratio + self.image_shape[0] = int(h) * self.shape_mult + self.image_shape[1] = int(w) * self.shape_mult + + def _get_crop_shapes(self, image_shape, ctx=None): + h, w = image_shape + input_ratio = w / h + if self.keep_original: + self.test_closest_shape(image_shape) + ctx = 1.0 + elif ctx is None: + ctx = float( + torch.empty(1) + .uniform_(self.train_ctx_range[0], self.train_ctx_range[1]) + .item() + ) + output_ratio = self.image_shape[1] / self.image_shape[0] + + if output_ratio <= input_ratio: # out like 4:3 in like kitti + if ( + ctx >= 1 + ): # fully in -> use just max_length with sqrt(ctx), here max is width + new_w = w * ctx**0.5 + # sporge un po in una sola dim + # we know that in_width will stick out before in_height, partial overshoot (sporge) + # new_h > old_h via area -> new_h ** 2 * ratio_new = old_h ** 2 * ratio_old * ctx + elif output_ratio / input_ratio * ctx > 1: + new_w = w * ctx + else: # fully contained -> use area + new_w = w * (ctx * output_ratio / input_ratio) ** 0.5 + new_h = new_w / output_ratio + else: + if ctx >= 1: + new_h = h * ctx**0.5 + elif input_ratio / output_ratio * ctx > 1: + new_h = h * ctx + else: + new_h = h * (ctx * input_ratio / output_ratio) ** 0.5 + new_w = new_h * output_ratio + return (int(ceil(new_h - 0.5)), int(ceil(new_w - 0.5))), ctx + + def __call__(self, results): + h, w = results["image"].shape[-2:] + results["image_ori_shape"] = (h, w) + + results.get("mask_fields", set()).add("validity_mask") + if "validity_mask" not in results: + results["validity_mask"] = torch.ones( + (results["image"].shape[0], 1, h, w), + dtype=torch.uint8, + device=results["image"].device, + ) + + n_iter = 1 if self.keep_original or not self.sample else 100 + + min_valid_area = 0.5 + results["camera_fields"].add("camera_original") + results["camera_original"] = results["camera"].clone() + max_hfov, max_vfov = results["camera"].max_fov[0] # it is a 1-dim list + ctx = None + for ii in range(n_iter): + + (height, width), ctx = self._get_crop_shapes((h, w), ctx=self.ctx or ctx) + margin_h = h - height + margin_w = w - width + + # keep it centered in y direction + top = margin_h // 2 + left = margin_w // 2 + if not self.keep_original: + left = left + np.random.randint( + -self.shape_mult // 2, self.shape_mult // 2 + 1 + ) + top = top + np.random.randint( + -self.shape_mult // 2, self.shape_mult // 2 + 1 + ) + + right = left + width + bottom = top + height + x_zoom = self.image_shape[0] / height + paddings = [ + max(-left + min(0, right), 0), + max(bottom - max(h, top), 0), + max(right - max(w, left), 0), + max(-top + min(0, bottom), 0), + ] + + valid_area = ( + h + * w + / (h + paddings[1] + paddings[3]) + / (w + paddings[0] + paddings[2]) + ) + + new_hfov, new_vfov = results["camera_original"].get_new_fov( + new_shape=(height, width), original_shape=(h, w) + )[0] + + if ( + valid_area >= min_valid_area + and new_hfov < max_hfov + and new_vfov < max_vfov + ): + results["camera"] = results["camera"].crop( + left, top, right=w - right, bottom=h - bottom + ) + results["camera"] = results["camera"].resize(x_zoom) + break + ctx = ( + ctx * 0.96 + ) # if not enough valid area, try again with less ctx (more zoom) + + # save ctx for next iteration of sequences? + self.ctx = ctx + + results["resized_shape"] = self.image_shape + results["paddings"] = paddings # left ,top ,right, bottom + results["image_rescale"] = x_zoom + results["scale_factor"] = results.get("scale_factor", 1.0) * x_zoom + + shapes = dict(height=height, width=width, top=top, left=left) + self._transform_img(results, shapes) + if not self.keep_original: + self._transform_gt(results, shapes) + self._transform_masks(results, shapes) + else: + # only validity_mask (rgb's masks follows rgb transform) #FIXME + mask = results["validity_mask"].float() + mask = self.crop(mask, **shapes).byte() + mask = TF.resize( + mask, + results["resized_shape"], + interpolation=TF.InterpolationMode.NEAREST, + ) + results["validity_mask"] = mask + + # keep original images before photo-augment + results["image_original"] = results["image"].clone() + results["image_fields"].add( + *[ + field.replace("image", "image_original") + for field in results["image_fields"] + ] + ) + + # repeat for batch resized shape and paddings + results["paddings"] = [results["paddings"]] * results["image"].shape[0] + results["resized_shape"] = [results["resized_shape"]] * results["image"].shape[ + 0 + ] + return results + + +class RandomFiller: + def __init__(self, *args, **kwargs): + super().__init__() + + def _transform(self, results): + def fill_noise(size, device): + return torch.normal(0, 2.0, size=size, device=device) + + def fill_black(size, device): + return -4 * torch.ones(size, device=device, dtype=torch.float32) + + def fill_white(size, device): + return 4 * torch.ones(size, device=device, dtype=torch.float32) + + def fill_zero(size, device): + return torch.zeros(size, device=device, dtype=torch.float32) + + B, C = results["image"].shape[:2] + mismatch = B // results["validity_mask"].shape[0] + if mismatch: + results["validity_mask"] = results["validity_mask"].repeat( + mismatch, 1, 1, 1 + ) + validity_mask = results["validity_mask"].repeat(1, C, 1, 1).bool() + filler_fn = np.random.choice([fill_noise, fill_black, fill_white, fill_zero]) + for key in results.get("image_fields", ["image"]): + results[key][~validity_mask] = filler_fn( + size=results[key][~validity_mask].shape, device=results[key].device + ) + + def __call__(self, results): + # generate mask for filler + if "validity_mask" not in results: + paddings = results.get("padding_size", [0] * 4) + height, width = results["image"].shape[-2:] + results.get("mask_fields", []).add("validity_mask") + results["validity_mask"] = torch.zeros_like(results["image"][:, :1]) + results["validity_mask"][ + ..., + paddings[1] : height - paddings[3], + paddings[0] : width - paddings[2], + ] = 1.0 + self._transform(results) + return results + + +class GaussianBlur: + def __init__(self, kernel_size, sigma=(0.1, 2.0), prob=0.9): + super().__init__() + self.kernel_size = kernel_size + self.sigma = sigma + self.prob = prob + self.padding = kernel_size // 2 + + def apply(self, x, kernel): + # Pad the input tensor + x = F.pad( + x, (self.padding, self.padding, self.padding, self.padding), mode="reflect" + ) + # Apply the convolution with the Gaussian kernel + return F.conv2d(x, kernel, stride=1, padding=0, groups=x.size(1)) + + def _create_kernel(self, sigma): + # Create a 1D Gaussian kernel + kernel_1d = torch.exp( + -torch.arange(-self.padding, self.padding + 1) ** 2 / (2 * sigma**2) + ) + kernel_1d = kernel_1d / kernel_1d.sum() + + # Expand the kernel to 2D and match size of the input + kernel_2d = kernel_1d.unsqueeze(0) * kernel_1d.unsqueeze(1) + kernel_2d = kernel_2d.view(1, 1, self.kernel_size, self.kernel_size).expand( + 3, 1, -1, -1 + ) + return kernel_2d + + def __call__(self, results): + if np.random.random() > self.prob: + return results + sigma = (self.sigma[1] - self.sigma[0]) * np.random.rand() + self.sigma[0] + kernel = self._create_kernel(sigma) + for key in results.get("image_fields", ["image"]): + if "original" not in key: + results[key] = self.apply(results[key], kernel) + return results + + +class Compose: + def __init__(self, transforms): + self.transforms = deepcopy(transforms) + + def __call__(self, results): + for t in self.transforms: + results = t(results) + return results + + def __setattr__(self, name: str, value) -> None: + super().__setattr__(name, value) + for t in self.transforms: + setattr(t, name, value) + + def __repr__(self): + format_string = self.__class__.__name__ + "(" + for t in self.transforms: + format_string += f"\n {t}" + format_string += "\n)" + return format_string diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/point_odyssey.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/point_odyssey.py new file mode 100644 index 0000000000000000000000000000000000000000..6689f905989a160b26a193baeba205f78ea22f19 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/point_odyssey.py @@ -0,0 +1,50 @@ +from typing import Any + +from unidepth.datasets.sequence_dataset import SequenceDataset + + +class PointOdyssey(SequenceDataset): + min_depth = 0.01 + max_depth = 250.0 + depth_scale = 1000.0 + test_split = "test.txt" + train_split = "train.txt" + sequences_file = "sequences_clean.json" + hdf5_paths = [f"PointOdyssey.hdf5"] + + def __init__( + self, + image_shape: tuple[int, int], + split_file: str, + test_mode: bool, + normalize: bool, + augmentations_db: dict[str, Any], + resize_method: str, + mini: float = 1.0, + num_frames: int = 1, + benchmark: bool = False, + decode_fields: list[str] = ["image", "depth"], + inplace_fields: list[str] = ["K", "cam2w"], + **kwargs, + ) -> None: + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + num_frames=num_frames, + decode_fields=decode_fields, + inplace_fields=inplace_fields, + **kwargs, + ) + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [True] * self.num_frames * self.num_copies + results["synthetic"] = [True] * self.num_frames * self.num_copies + results["quality"] = [0] * self.num_frames * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/proteus.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/proteus.py new file mode 100644 index 0000000000000000000000000000000000000000..2cf30a0521398fd93b2d0c4c814e6ed87722d8bc --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/proteus.py @@ -0,0 +1,51 @@ +from typing import Any + +from unidepth.datasets.sequence_dataset import SequenceDataset + + +class Proteus(SequenceDataset): + min_depth = 0.01 + max_depth = 10.0 + depth_scale = 1000.0 + default_fps = 5 + test_split = "train.txt" + train_split = "train.txt" + sequences_file = "sequences.json" + hdf5_paths = ["Proteus.hdf5"] + + def __init__( + self, + image_shape: tuple[int, int], + split_file: str, + test_mode: bool, + normalize: bool, + augmentations_db: dict[str, Any], + resize_method: str, + mini: float = 1.0, + num_frames: int = 1, + benchmark: bool = False, + decode_fields: list[str] = ["image", "depth"], + inplace_fields: list[str] = ["K", "cam2w"], + **kwargs, + ) -> None: + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + num_frames=num_frames, + decode_fields=decode_fields, + inplace_fields=inplace_fields, + **kwargs, + ) + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [True] * self.num_frames * self.num_copies + results["synthetic"] = [True] * self.num_frames * self.num_copies + results["quality"] = [0] * self.num_frames * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/samplers copy.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/samplers copy.py new file mode 100644 index 0000000000000000000000000000000000000000..79b2c54170b5697f169eefee8ea254eed9e0c70b --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/samplers copy.py @@ -0,0 +1,242 @@ +import itertools +import warnings +from operator import itemgetter +from typing import Any, Optional + +import numpy as np +import torch +from torch.utils.data import Sampler + +from unidepth.utils import get_dist_info + + +def _get_numpy_dtype(size: int) -> Any: + return np.int32 if size <= 2**31 else np.int64 + + +def _get_torch_dtype(size: int) -> Any: + return torch.int32 if size <= 2**31 else torch.int64 + + +def _generate_randperm_indices(*, size: int, generator: torch.Generator): + """Generate the indices of a random permutation.""" + dtype = _get_torch_dtype(size) + # This is actually matching PyTorch's CPU implementation, see: https://github.com/pytorch/pytorch/blob/master/aten/src/ATen/native/TensorFactories.cpp#L900-L921 + perm = torch.arange(size, dtype=dtype) + for i in range(size): + j = torch.randint(i, size, size=(1,), generator=generator).item() + + # Always swap even if no-op + value = perm[j].item() + perm[j] = perm[i].item() + perm[i] = value + yield value + + +# The following function is somewhat equivalent to _new_shuffle_tensor_slice below, +# but avoids a full in-place random permutation generation. +def _shuffle_tensor_slice( + *, tensor: torch.Tensor, start: int = 0, step: int = 1, generator: torch.Generator +) -> np.ndarray: + stop = len(tensor) + count = stop // step + drop_count = stop - step * count + if drop_count: + warnings.warn(f"# of dropped samples: {drop_count}") + + dtype = _get_numpy_dtype(stop) + result = np.empty(count, dtype=dtype) + + for i in range(count): + j = ( + torch.randint(0, i + 1, size=(1,), generator=generator).item() + if i > 0 + else 0 + ) + + result[i] = result[j] + result[j] = tensor[start + i * step].item() + + return result + + +def _new_shuffle_tensor_slice( + *, tensor: torch.Tensor, start: int = 0, step: int = 1, generator: torch.Generator +) -> np.ndarray: + stop = len(tensor) + count = stop // step + dtype = torch.int64 # Needed for using randperm result as indices + count = stop // step + drop_count = stop - step * count + if drop_count: + warnings.warn(f"# of dropped samples: {drop_count}") + indices = torch.randperm(count, dtype=dtype, generator=generator) + return tensor[start::step][indices].numpy() + + +def _make_seed(seed: int, start: int, iter_count: int) -> int: + # NOTE: Tried a few variants (including iter_count << 32), this one worked best. + return seed + start + (iter_count << 24) + + +class ShardedInfiniteSampler(Sampler): + def __init__( + self, + *, + sample_count: int, + shuffle: bool = False, + seed: int = 0, + start: Optional[int] = None, + step: Optional[int] = None, + advance: int = 0, + use_new_shuffle_tensor_slice: bool = False, + ): + self._sample_count = sample_count + self._seed = seed + self._shuffle = shuffle + rank, world_size = get_dist_info() + self._start = rank if start is None else start + self._step = world_size if step is None else step + self._advance = advance + self._iter_count = 0 + self._shuffle_tensor_slice_fn = ( + _new_shuffle_tensor_slice + if use_new_shuffle_tensor_slice + else _shuffle_tensor_slice + ) + + def __iter__(self): + iter_count = self._advance // self._sample_count + if iter_count > 0: + self._advance -= iter_count * self._sample_count + self._iter_count += iter_count + + if self._shuffle: + iterator = self._shuffled_iterator() + else: + iterator = self._iterator() + + yield from itertools.islice(iterator, self._advance, None) + + def _iterator(self): + assert not self._shuffle + + while True: + iterable = range(self._sample_count) + yield from itertools.islice(iterable, self._start, None, self._step) + + def _shuffled_iterator(self): + assert self._shuffle + + # Instantiate a generator here (rather than in the ctor) to be keep the class + # picklable (requirement of mp.spawn) + generator = torch.Generator() + + # Always shuffle everything first + generator.manual_seed(self._seed) + dtype = _get_torch_dtype(self._sample_count) + perm = torch.randperm(self._sample_count, dtype=dtype, generator=generator) + + while True: + # Re-seed on each iteration to allow skipping whole permutations + seed = _make_seed(self._seed, self._start, self._iter_count) + generator.manual_seed(seed) + + iterable = self._shuffle_tensor_slice_fn( + tensor=perm, start=self._start, step=self._step, generator=generator + ) + yield from iterable + self._iter_count += 1 + + +class DistributedSamplerNoDuplicate(torch.utils.data.DistributedSampler): + """A distributed sampler that doesn't add duplicates. Arguments are the same as DistributedSampler""" + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + if not self.drop_last and len(self.dataset) % self.num_replicas != 0: + # some ranks may have less samples, that's fine + if self.rank >= len(self.dataset) % self.num_replicas: + self.num_samples -= 1 + self.total_size = len(self.dataset) + + +class DatasetFromSampler(torch.utils.data.Dataset): + """Dataset to create indexes from `Sampler`. + + Args: + sampler: PyTorch sampler + """ + + def __init__(self, sampler: Sampler): + """Initialisation for DatasetFromSampler.""" + self.sampler = sampler + self.sampler_list = None + + def __getitem__(self, index: int): + """Gets element of the dataset. + + Args: + index: index of the element in the dataset + + Returns: + Single element by index + """ + if self.sampler_list is None: + self.sampler_list = list(self.sampler) + return self.sampler_list[index] + + def __len__(self) -> int: + """ + Returns: + int: length of the dataset + """ + return len(self.sampler) + + +class DistributedSamplerWrapper(torch.utils.data.DistributedSampler): + """ + Wrapper over `Sampler` for distributed training + Allows you to use any sampler in distributed mode. + + It is especially useful in conjunction with + `torch.nn.parallel.DistributedDataParallel`. In such case, each + process can pass a DistributedSamplerWrapper instance as a DataLoader + sampler, and load a subset of subsampled data of the original dataset + that is exclusive to it. + + .. note:: + Sampler is assumed to be of constant size. + """ + + def __init__( + self, + sampler, + num_replicas: Optional[int] = None, + rank: Optional[int] = None, + shuffle: bool = True, + ): + """ + + Args: + sampler: Sampler used for subsampling + num_replicas (int, optional): Number of processes participating in + distributed training + rank (int, optional): Rank of the current process + within ``num_replicas`` + shuffle (bool, optional): If true (default), + sampler will shuffle the indices + """ + super(DistributedSamplerWrapper, self).__init__( + DatasetFromSampler(sampler), + num_replicas=num_replicas, + rank=rank, + shuffle=shuffle, + ) + self.sampler = sampler + + def __iter__(self): + self.dataset = DatasetFromSampler(self.sampler) + indexes_of_indexes = super().__iter__() + subsampler_indexes = self.dataset + return iter(itemgetter(*indexes_of_indexes)(subsampler_indexes)) diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/samplers.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/samplers.py new file mode 100644 index 0000000000000000000000000000000000000000..c999abc1a14de922e7900ded46b95246b3c17bae --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/samplers.py @@ -0,0 +1,13 @@ +import torch + + +class DistributedSamplerNoDuplicate(torch.utils.data.DistributedSampler): + """A distributed sampler that doesn't add duplicates. Arguments are the same as DistributedSampler""" + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + if not self.drop_last and len(self.dataset) % self.num_replicas != 0: + # some ranks may have less samples, that's fine + if self.rank >= len(self.dataset) % self.num_replicas: + self.num_samples -= 1 + self.total_size = len(self.dataset) diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/scannet.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/scannet.py new file mode 100644 index 0000000000000000000000000000000000000000..557b7e3b0316ef76647dadc26318a10efaa0981d --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/scannet.py @@ -0,0 +1,49 @@ +from typing import Any + +from unidepth.datasets.sequence_dataset import SequenceDataset + + +class ScanNet(SequenceDataset): + min_depth = 0.005 + max_depth = 10.0 + depth_scale = 1000.0 + test_split = "test.txt" + train_split = "train.txt" + sequences_file = "sequences.json" + hdf5_paths = ["ScanNetS.hdf5"] + + def __init__( + self, + image_shape: tuple[int, int], + split_file: str, + test_mode: bool, + normalize: bool, + augmentations_db: dict[str, Any], + resize_method: str, + mini: float = 1.0, + num_frames: int = 1, + benchmark: bool = False, + decode_fields: list[str] = ["image", "depth"], + inplace_fields: list[str] = ["K", "cam2w"], + **kwargs, + ) -> None: + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + num_frames=num_frames, + decode_fields=decode_fields, + inplace_fields=inplace_fields, + **kwargs, + ) + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [True] * self.num_frames * self.num_copies + results["quality"] = [1] * self.num_frames * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/scannetpp.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/scannetpp.py new file mode 100644 index 0000000000000000000000000000000000000000..0f51581fde5dddc47804f6c38307d5549491ee1f --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/scannetpp.py @@ -0,0 +1,98 @@ +from typing import Any + +from unidepth.datasets.sequence_dataset import SequenceDataset + + +class ScanNetpp(SequenceDataset): + min_depth = 0.001 + max_depth = 10.0 + depth_scale = 1000.0 + test_split = "val_iphone.txt" + train_split = "train_iphone.txt" + sequences_file = "sequences_iphone_clean.json" + hdf5_paths = [f"ScanNetpp_viz.hdf5"] + + def __init__( + self, + image_shape: tuple[int, int], + split_file: str, + test_mode: bool, + normalize: bool, + augmentations_db: dict[str, Any], + resize_method: str, + mini: float = 1.0, + num_frames: int = 1, + benchmark: bool = False, + decode_fields: list[str] = ["image", "depth"], + inplace_fields: list[str] = ["K", "cam2w"], + **kwargs, + ) -> None: + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + num_frames=num_frames, + decode_fields=decode_fields, + inplace_fields=inplace_fields, + **kwargs, + ) + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [True] * self.num_frames * self.num_copies + results["quality"] = [1] * self.num_frames * self.num_copies + return results + + +class ScanNetpp_F(SequenceDataset): + min_depth = 0.001 + max_depth = 10.0 + depth_scale = 1000.0 + train_split = "train.txt" + test_split = "val_split.txt" + + sequences_file = "sequences_split.json" + hdf5_paths = [f"ScanNetpp_F.hdf5"] + + def __init__( + self, + image_shape: tuple[int, int], + split_file: str, + test_mode: bool, + normalize: bool, + augmentations_db: dict[str, Any], + resize_method: str, + mini: float = 1.0, + num_frames: int = 1, + benchmark: bool = False, + decode_fields: list[str] = ["image", "depth"], + inplace_fields: list[str] = ["camera_params", "cam2w"], + **kwargs, + ) -> None: + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + num_frames=num_frames, + decode_fields=( + decode_fields if not test_mode else [*decode_fields, "points"] + ), + inplace_fields=inplace_fields, + **kwargs, + ) + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [True] * self.num_frames * self.num_copies + results["quality"] = [1] * self.num_frames * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/sequence_dataset.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/sequence_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..e82c5b5fdf5f25ebd2f840ac25eedd717c168ee0 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/sequence_dataset.py @@ -0,0 +1,294 @@ +import json +import os +from functools import partial +from typing import Any, Dict, Tuple + +import h5py +import numpy as np +import tables +import torch +import torchvision.transforms.v2.functional as TF + +from unidepth.datasets.base_dataset import BaseDataset +from unidepth.datasets.utils import DatasetFromList +from unidepth.datasets.utils_decode import (decode_camera, decode_depth, + decode_flow, decode_K, decode_mask, + decode_numpy, decode_rgb, + decode_tensor) +from unidepth.utils.distributed import is_main_process + + +class SequenceDataset(BaseDataset): + DECODE_FNS = { + "image": partial(decode_rgb, name="image"), + "points": partial(decode_numpy, name="points"), + "K": partial(decode_K, name="camera"), + "camera_params": partial(decode_camera, name="camera"), + "cam2w": partial(decode_tensor, name="cam2w"), + "depth": partial(decode_depth, name="depth"), + "flow_fwd": partial(decode_flow, name="flow_fwd"), + "flow_bwd": partial(decode_flow, name="flow_bwd"), + "flow_fwd_mask": partial(decode_mask, name="flow_fwd_mask"), + "flow_bwd_mask": partial(decode_mask, name="flow_bwd_mask"), + } + default_fps = 5 + + def __init__( + self, + image_shape: Tuple[int, int], + split_file: str, + test_mode: bool, + normalize: bool, + augmentations_db: Dict[str, Any], + resize_method: str, + mini: float, + num_frames: int = 1, + benchmark: bool = False, + decode_fields: list[str] = ["image", "depth", "flow_fwd", "flow_fwd_mask"], + inplace_fields: list[str] = ["K", "cam2w"], + **kwargs, + ) -> None: + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + **kwargs, + ) + self.num_frames = num_frames + self.original_num_frames = num_frames + self.decode_fields = decode_fields + self.inplace_fields = inplace_fields + self.fps = self.default_fps + self.fps_range = kwargs.get("fps_range", None) + if self.fps_range is not None: + self.fps_range[1] = min(self.default_fps, self.fps_range[1]) + + self.load_dataset() + + def load_dataset(self): + h5file = h5py.File( + os.path.join(self.data_root, self.hdf5_paths[0]), + "r", + libver="latest", + swmr=True, + ) + txt_file = np.array(h5file[self.split_file]) + txt_string = txt_file.tostring().decode("ascii").strip() + sequences = np.array(h5file[self.sequences_file]).tostring().decode("ascii") + sequences = json.loads(sequences) + h5file.close() + dataset = [] + for line in txt_string.split("\n"): + if len(line.strip().split(" ")) == 1: + print(line) + continue + sequence_name, num_samples = line.strip().split(" ") + dataset.append( + { + "sequence_name": sequence_name, + "num_samples": int(num_samples), + "chunk_idx": 0, + } + ) + + # filter dataset based on attr "invalid_sequences" + invalid_sequences = getattr(self, "invalid_sequences", []) + dataset = [ + sample + for sample in dataset + if sample["sequence_name"] not in invalid_sequences + ] + + self.dataset = DatasetFromList(dataset) + self.sequences = DatasetFromList( + [sequences[sample["sequence_name"]] for sample in dataset] + ) + self.log_load_dataset() + + def get_random_idxs(self, num_samples_sequence): + if self.num_frames == 1: + return [np.random.randint(0, num_samples_sequence)], 0 + + # Check if we can satisfy the required number of frames + if self.num_frames > num_samples_sequence: + raise ValueError( + "Cannot sample more frames than available in the sequence." + ) + + # Restrict FPS range to be within default FPS + min_fps, max_fps = self.fps_range + max_fps = min(max_fps, self.default_fps) + if min_fps > self.default_fps: + sampled_fps = self.default_fps + else: + # Compute minimal viable FPS + min_required_fps = ( + self.num_frames / num_samples_sequence + ) * self.default_fps + min_fps = max(min_fps, min_required_fps) + + # Sample an FPS from the viable range + sampled_fps = np.random.uniform(min_fps, max_fps) + + # Compute the stride based on the sampled FPS + stride = self.default_fps / sampled_fps + max_start_index = num_samples_sequence - int(stride * (self.num_frames - 1)) + + # Ensure a valid starting position + if max_start_index <= 0: + raise ValueError( + "No valid start position allows sampling num_frames with the chosen FPS." + ) + + start_index = np.random.randint(0, max_start_index + 1) + + # Compute indices based on the sampled FPS + indices = [int(start_index + i * stride) for i in range(self.num_frames)] + + return indices, np.random.randint(0, len(indices)) + + def get_test_idxs(self, num_samples_sequence, keyframe_idx): + if self.num_frames == 1: + return [ + keyframe_idx if keyframe_idx is not None else num_samples_sequence // 2 + ], 0 + + if self.num_frames == -1: + cap_idxs = min(32, num_samples_sequence) # CAP 32 images + idxs = list( + range(max(0, num_samples_sequence - cap_idxs), num_samples_sequence, 1) + ) + return idxs, keyframe_idx + + # pick closest keyframe_idx st they are around it or capped by the 0 and max num_samples_sequence + keyframe_idx = ( + keyframe_idx if keyframe_idx is not None else num_samples_sequence - 1 + ) + excess_tail = 0 - min(0, keyframe_idx - self.num_frames // 2) + excess_head = ( + max(num_samples_sequence, keyframe_idx + (self.num_frames - 1) // 2) + - num_samples_sequence + ) + start = keyframe_idx - self.num_frames // 2 + excess_tail - excess_head + end = keyframe_idx + (self.num_frames - 1) // 2 + excess_head - excess_tail + idxs = list(range(start, 1 + end)) + + return idxs, idxs.index(keyframe_idx) + + def get_single_sequence(self, idx): + self.num_frames = self.original_num_frames + # sequence_name = self.dataset[idx]["sequence_name"] + sample = self.sequences[idx] + chunk_idx = int(sample.get("chunk_idx", 0)) + h5_path = os.path.join(self.data_root, self.hdf5_paths[chunk_idx]) + + num_samples_sequence = len(sample["image"]) + if self.num_frames > 0 and num_samples_sequence < self.num_frames: + raise IndexError(f"Sequence {idx} has less than {self.num_frames} frames") + keyframe_idx = None + + if not self.test_mode: + idxs, keyframe_idx = self.get_random_idxs(num_samples_sequence) + else: + idxs, keyframe_idx = self.get_test_idxs( + num_samples_sequence, sample.get("keyframe_idx", None) + ) + + self.num_frames = len(idxs) + results = {} + results = self.pre_pipeline(results) + results["sequence_fields"] = [(i, 0) for i in range(self.num_frames)] + results["keyframe_idx"] = keyframe_idx + with tables.File( + h5_path, + mode="r", + libver="latest", + swmr=True, + ) as h5file_chunk: + + for i, j in enumerate(idxs): + results[(i, 0)] = { + k: v.copy() for k, v in results.items() if "fields" in k + } + for inplace_field in self.inplace_fields: + inplace_field_ = inplace_field.replace("intrinsics", "K").replace( + "extrinsics", "cam2w" + ) + results = self.DECODE_FNS[inplace_field_]( + results, sample[inplace_field][j], idx=i, sample=sample, j=j + ) + + for i, j in enumerate(idxs): + for decode_field in self.decode_fields: + results = self.DECODE_FNS[decode_field]( + results, + h5file_chunk, + sample[decode_field][j], + idx=i, + depth_scale=self.depth_scale, + ) + + results["filename"] = sample["image"][j] + + results = self.preprocess(results) + if not self.test_mode: + results = self.augment(results) + results = self.postprocess(results) + return results + + def preprocess(self, results): + results = self.replicate(results) + for i, seq in enumerate(results["sequence_fields"]): + results[seq] = self.resizer(results[seq]) + self.resizer.ctx = None if self.num_copies > 1 else self.resizer.ctx + num_pts = torch.count_nonzero(results[seq]["depth"] > 0) + if num_pts < 50: + raise IndexError(f"Too few points in depth map ({num_pts})") + + for key in results[seq].get("image_fields", ["image"]): + results[seq][key] = results[seq][key].to(torch.float32) / 255 + + # update fields common in sequence + for key in [ + "image_fields", + "gt_fields", + "mask_fields", + "camera_fields", + ]: + if key in results[(0, 0)]: + results[key] = results[(0, 0)][key] + + results = self.pack_batch(results) + return results + + def postprocess(self, results): + # # normalize after because color aug requires [0,255]? + for key in results.get("image_fields", ["image"]): + results[key] = TF.normalize(results[key], **self.normalization_stats) + results = self.filler(results) + results = self.unpack_batch(results) + results = self.masker(results) + results = self.collecter(results) + return results + + def __getitem__(self, idx): + try: + if isinstance(idx, (list, tuple)): + results = [self.get_single_sequence(i) for i in idx] + else: + results = self.get_single_sequence(idx) + except Exception as e: + print(f"Error loading sequence {idx} for {self.__class__.__name__}: {e}") + idx = np.random.randint(0, len(self.dataset)) + results = self[idx] + return results + + def log_load_dataset(self): + if is_main_process(): + info = f"Loaded {self.__class__.__name__} with {sum([len(x['image']) for x in self.sequences])} images in {len(self)} sequences." + print(info) diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/sintel copy.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/sintel copy.py new file mode 100644 index 0000000000000000000000000000000000000000..ad33104441353a1b090c1cab564766095ac12ea4 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/sintel copy.py @@ -0,0 +1,50 @@ +from typing import Any + +from unidepth.datasets.sequence_dataset import SequenceDataset + + +class Sintel(SequenceDataset): + min_depth = 0.001 + max_depth = 1000.0 + depth_scale = 1000.0 + test_split = "training.txt" + train_split = "training.txt" + sequences_file = "sequences.json" + hdf5_paths = ["Sintel.hdf5"] + + def __init__( + self, + image_shape: tuple[int, int], + split_file: str, + test_mode: bool, + normalize: bool, + augmentations_db: dict[str, Any], + resize_method: str, + mini: float = 1.0, + num_frames: int = 1, + benchmark: bool = False, + decode_fields: list[str] = ["image", "depth", "flow_fwd", "flow_fwd_mask"], + inplace_fields: list[str] = ["K", "cam2w"], + **kwargs, + ) -> None: + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + num_frames=num_frames, + decode_fields=decode_fields, + inplace_fields=inplace_fields, + **kwargs, + ) + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [True] * self.num_frames * self.num_copies + results["synthetic"] = [True] * self.num_frames * self.num_copies + results["quality"] = [0] * self.num_frames * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/sintel.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/sintel.py new file mode 100644 index 0000000000000000000000000000000000000000..a5f18590549c2f3ae3b43a3f417e16d743037e35 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/sintel.py @@ -0,0 +1,49 @@ +from typing import Any + +from unidepth.datasets.sequence_dataset import SequenceDataset + + +class Sintel(SequenceDataset): + min_depth = 0.001 + max_depth = 1000.0 + depth_scale = 1000.0 + test_split = "training.txt" + train_split = "training.txt" + sequences_file = "sequences.json" + hdf5_paths = ["Sintel.hdf5"] + + def __init__( + self, + image_shape: tuple[int, int], + split_file: str, + test_mode: bool, + normalize: bool, + augmentations_db: dict[str, Any], + resize_method: str, + mini: float, + num_frames: int = 1, + benchmark: bool = False, + decode_fields: list[str] = ["image", "depth"], + inplace_fields: list[str] = ["K", "cam2w"], + **kwargs, + ) -> None: + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + num_frames=num_frames, + decode_fields=decode_fields, + inplace_fields=inplace_fields, + **kwargs, + ) + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [True] * self.num_frames + results["synthetic"] = [True] * self.num_frames + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/sunrgbd.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/sunrgbd.py new file mode 100644 index 0000000000000000000000000000000000000000..377859fc045c0170869c1009f184332157b928d4 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/sunrgbd.py @@ -0,0 +1,73 @@ +import json +import os + +import h5py +import numpy as np +import torch + +from unidepth.datasets.image_dataset import ImageDataset +from unidepth.datasets.utils import DatasetFromList + + +class SUNRGBD(ImageDataset): + min_depth = 0.005 + max_depth = 8.0 + depth_scale = 1000.0 + test_split = "alltest.txt" + train_split = "alltrain.txt" + intrisics_file = "intrinsics.json" + hdf5_paths = ["SUNRGB.hdf5"] + + def __init__( + self, + image_shape, + split_file, + test_mode, + crop=None, + benchmark=False, + augmentations_db={}, + normalize=True, + resize_method="hard", + mini=1.0, + **kwargs, + ): + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + **kwargs, + ) + self.test_mode = test_mode + + self.crop = crop + self.load_dataset() + + def load_dataset(self): + h5file = h5py.File( + os.path.join(self.data_root, self.hdf5_paths[0]), + "r", + libver="latest", + swmr=True, + ) + txt_file = np.array(h5file[self.split_file]) + txt_string = txt_file.tostring().decode("ascii")[:-1] # correct the -1 + intrinsics = np.array(h5file[self.intrisics_file]).tostring().decode("ascii") + intrinsics = json.loads(intrinsics) + h5file.close() + dataset = [] + for line in txt_string.split("\n"): + image_filename, depth_filename = line.strip().split(" ") + intrinsics_val = torch.tensor(intrinsics[image_filename]).squeeze()[:, :3] + sample = [image_filename, depth_filename, intrinsics_val] + dataset.append(sample) + + if not self.test_mode: + dataset = self.chunk(dataset, chunk_dim=1, pct=self.mini) + + self.dataset = DatasetFromList(dataset) + self.log_load_dataset() diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/synscapes.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/synscapes.py new file mode 100644 index 0000000000000000000000000000000000000000..d56f7f925acc31f922eada76ccb23fd733d84d6b --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/synscapes.py @@ -0,0 +1,50 @@ +from typing import Any + +from unidepth.datasets.sequence_dataset import SequenceDataset + + +class Synscapes(SequenceDataset): + min_depth = 0.1 + max_depth = 1000.0 + depth_scale = 256.0 + test_split = "train.txt" + train_split = "train.txt" + sequences_file = "sequences.json" + hdf5_paths = [f"Synscapes.hdf5"] + + def __init__( + self, + image_shape: tuple[int, int], + split_file: str, + test_mode: bool, + normalize: bool, + augmentations_db: dict[str, Any], + resize_method: str, + mini: float = 1.0, + num_frames: int = 1, + benchmark: bool = False, + decode_fields: list[str] = ["image", "depth"], + inplace_fields: list[str] = ["K", "cam2w"], + **kwargs, + ) -> None: + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + num_frames=num_frames, + decode_fields=decode_fields, + inplace_fields=inplace_fields, + **kwargs, + ) + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [True] * self.num_frames * self.num_copies + results["synthetic"] = [True] * self.num_frames * self.num_copies + results["quality"] = [0] * self.num_frames * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/tartanair.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/tartanair.py new file mode 100644 index 0000000000000000000000000000000000000000..c25419f25bd48d84c3928a11e9ad0c01dda2d269 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/tartanair.py @@ -0,0 +1,51 @@ +from typing import Any + +from unidepth.datasets.sequence_dataset import SequenceDataset + + +class TartanAir(SequenceDataset): + min_depth = 0.01 + max_depth = 512.0 + depth_scale = 1000.0 + default_fps = 15 + test_split = "train.txt" + train_split = "train.txt" + sequences_file = "sequences.json" + hdf5_paths = ["TartanAir.hdf5"] + + def __init__( + self, + image_shape: tuple[int, int], + split_file: str, + test_mode: bool, + normalize: bool, + augmentations_db: dict[str, Any], + resize_method: str, + mini: float = 1.0, + num_frames: int = 1, + benchmark: bool = False, + decode_fields: list[str] = ["image", "depth"], + inplace_fields: list[str] = ["K", "cam2w"], + **kwargs, + ) -> None: + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + num_frames=num_frames, + decode_fields=decode_fields, + inplace_fields=inplace_fields, + **kwargs, + ) + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [True] * self.num_frames * self.num_copies + results["synthetic"] = [True] * self.num_frames * self.num_copies + results["quality"] = [0] * self.num_frames * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/taskonomy.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/taskonomy.py new file mode 100644 index 0000000000000000000000000000000000000000..04fab078336a31c26f96ddae182f659d343b02f1 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/taskonomy.py @@ -0,0 +1,91 @@ +import json +import os + +import h5py +import numpy as np +import torch + +from unidepth.datasets.image_dataset import ImageDataset +from unidepth.datasets.utils import DatasetFromList + + +class Taskonomy(ImageDataset): + min_depth = 0.005 + max_depth = 15.0 + depth_scale = 512.0 + test_split = "val.txt" + train_split = "train_clean.txt" + intrisics_file = "intrinsics.json" + hdf5_paths = ["Taskonomy.hdf5"] + + def __init__( + self, + image_shape, + split_file, + test_mode, + benchmark=False, + augmentations_db={}, + normalize=True, + resize_method="hard", + mini=1.0, + **kwargs, + ): + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + **kwargs, + ) + self.test_mode = test_mode + self.load_dataset() + + def load_dataset(self): + h5file = h5py.File( + os.path.join(self.data_root, self.hdf5_paths[0]), + "r", + libver="latest", + swmr=True, + ) + txt_file = np.array(h5file[self.split_file]) + txt_string = txt_file.tostring().decode("ascii") # [:-1] # correct the -1 + intrinsics = np.array(h5file[self.intrisics_file]).tostring().decode("ascii") + intrinsics = json.loads(intrinsics) + # with open(os.path.join(os.environ["TMPDIR"], self.split_file), "w") as f: + # f.write(txt_string) + # with open(os.path.join(os.environ["TMPDIR"], self.intrisics_file), "w") as f: + # json.dump(intrinsics, f) + + dataset = [] + for line in txt_string.split("\n"): + image_filename, depth_filename, chunk_idx = line.strip().split(" ") + intrinsics_val = torch.tensor(intrinsics[image_filename]).squeeze()[:, :3] + sample = [image_filename, depth_filename, intrinsics_val, chunk_idx] + dataset.append(sample) + h5file.close() + + if not self.test_mode: + dataset = self.chunk(dataset, chunk_dim=1, pct=self.mini) + + if self.test_mode and not self.benchmark: + dataset = self.chunk(dataset, chunk_dim=1, pct=0.01) + + self.dataset = DatasetFromList(dataset) + self.log_load_dataset() + + def get_mapper(self): + return { + "image_filename": 0, + "depth_filename": 1, + "K": 2, + } + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [True] * self.num_frames * self.num_copies + results["quality"] = [2] * self.num_frames * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/tat_rmvd.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/tat_rmvd.py new file mode 100644 index 0000000000000000000000000000000000000000..7de0f3c11f084c710f4d8587ac3eac3bdd4bb32e --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/tat_rmvd.py @@ -0,0 +1,63 @@ +import json +import os +from copy import deepcopy +from typing import Any + +import h5py +import numpy as np +import torch + +from unidepth.datasets.image_dataset import ImageDataset +from unidepth.datasets.pipelines import AnnotationMask, KittiCrop +from unidepth.datasets.sequence_dataset import SequenceDataset +from unidepth.datasets.utils import DatasetFromList +from unidepth.utils import identity + + +class TATRMVD(SequenceDataset): + min_depth = 0.001 + max_depth = 50.0 + depth_scale = 1000.0 + default_fps = 6 + test_split = "test.txt" + train_split = "test.txt" + sequences_file = "sequences.json" + hdf5_paths = ["tanks_and_temples_rmvd.hdf5"] + + def __init__( + self, + image_shape, + split_file, + test_mode, + crop=None, + augmentations_db={}, + normalize=True, + resize_method="hard", + mini: float = 1.0, + num_frames: int = 1, + benchmark: bool = False, + decode_fields: list[str] = ["image", "depth"], + inplace_fields: list[str] = ["K", "cam2w"], + **kwargs, + ): + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + num_frames=num_frames, + decode_fields=decode_fields, + inplace_fields=inplace_fields, + **kwargs, + ) + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [False] * self.num_frames * self.num_copies + results["si"] = [True] * self.num_frames * self.num_copies + results["quality"] = [2] * self.num_frames * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/theo.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/theo.py new file mode 100644 index 0000000000000000000000000000000000000000..30f91bda1fe1cb4c188046749704aab95de42faf --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/theo.py @@ -0,0 +1,66 @@ +from typing import Any + +import torch + +from unidepth.datasets.sequence_dataset import SequenceDataset + + +class Theo(SequenceDataset): + min_depth = 0.01 + max_depth = 10.0 + depth_scale = 1000.0 + default_fps = 5 + test_split = "train.txt" + train_split = "train.txt" + sequences_file = "sequences.json" + hdf5_paths = ["THEO.hdf5"] + + def __init__( + self, + image_shape: tuple[int, int], + split_file: str, + test_mode: bool, + normalize: bool, + augmentations_db: dict[str, Any], + resize_method: str, + mini: float = 1.0, + num_frames: int = 1, + benchmark: bool = False, + decode_fields: list[str] = ["image", "depth"], + inplace_fields: list[str] = ["camera_params", "cam2w"], + **kwargs, + ) -> None: + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + num_frames=num_frames, + decode_fields=decode_fields, + inplace_fields=inplace_fields, + **kwargs, + ) + + def preprocess(self, results): + self.resizer.ctx = None + for i, seq in enumerate(results["sequence_fields"]): + # Create a mask where the distance from the center is less than H/2 + H, W = results[seq]["image"].shape[-2:] + x = torch.linspace(-(W - 1) / 2, (W - 1) / 2, W) + y = torch.linspace(-(H - 1) / 2, (H - 1) / 2, H) + xv, yv = torch.meshgrid(x, y, indexing="xy") + distance_from_center = torch.sqrt(xv**2 + yv**2).reshape(1, 1, H, W) + results[seq]["validity_mask"] = distance_from_center < (H - 1) / 2 + + return super().preprocess(results) + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [True] * self.num_frames * self.num_copies + results["synthetic"] = [True] * self.num_frames * self.num_copies + results["quality"] = [0] * self.num_frames * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/unrealstereo4k.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/unrealstereo4k.py new file mode 100644 index 0000000000000000000000000000000000000000..7992c740d05be53cfeccd3e4a6e65f9bdb3e9ef6 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/unrealstereo4k.py @@ -0,0 +1,50 @@ +from typing import Any + +from unidepth.datasets.sequence_dataset import SequenceDataset + + +class UnrealStereo4K(SequenceDataset): + min_depth = 0.01 + max_depth = 200.0 + depth_scale = 1000.0 + test_split = "train.txt" + train_split = "train.txt" + sequences_file = "sequences.json" + hdf5_paths = [f"UnrealStereo4K.hdf5"] + + def __init__( + self, + image_shape: tuple[int, int], + split_file: str, + test_mode: bool, + normalize: bool, + augmentations_db: dict[str, Any], + resize_method: str, + mini: float = 1.0, + num_frames: int = 1, + benchmark: bool = False, + decode_fields: list[str] = ["image", "depth"], + inplace_fields: list[str] = ["K", "cam2w"], + **kwargs, + ) -> None: + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + num_frames=num_frames, + decode_fields=decode_fields, + inplace_fields=inplace_fields, + **kwargs, + ) + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [True] * self.num_frames * self.num_copies + results["synthetic"] = [True] * self.num_frames * self.num_copies + results["quality"] = [0] * self.num_frames * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/urbansyn.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/urbansyn.py new file mode 100644 index 0000000000000000000000000000000000000000..331a41aa0bcf231c6b1e1e937fc39f5615957d68 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/urbansyn.py @@ -0,0 +1,50 @@ +from typing import Any + +from unidepth.datasets.sequence_dataset import SequenceDataset + + +class UrbanSyn(SequenceDataset): + min_depth = 0.1 + max_depth = 1000.0 + depth_scale = 256.0 + test_split = "train.txt" + train_split = "train.txt" + sequences_file = "sequences.json" + hdf5_paths = [f"UrbanSyn.hdf5"] + + def __init__( + self, + image_shape: tuple[int, int], + split_file: str, + test_mode: bool, + normalize: bool, + augmentations_db: dict[str, Any], + resize_method: str, + mini: float = 1.0, + num_frames: int = 1, + benchmark: bool = False, + decode_fields: list[str] = ["image", "depth"], + inplace_fields: list[str] = ["K", "cam2w"], + **kwargs, + ) -> None: + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + num_frames=num_frames, + decode_fields=decode_fields, + inplace_fields=inplace_fields, + **kwargs, + ) + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [True] * self.num_frames * self.num_copies + results["synthetic"] = [True] * self.num_frames * self.num_copies + results["quality"] = [0] * self.num_frames * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/utils.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..d34c28574084a2de773d0506ed40febf737102cd --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/utils.py @@ -0,0 +1,235 @@ +import copy +import multiprocessing as mp +import pickle +from collections import defaultdict +from typing import Any, Dict, List + +import numpy as np +import torch +import torch.utils.data + +from unidepth.utils.distributed import (all_gather, get_local_rank, + get_local_size, get_rank, + get_world_size) + + +class ConcatDataset(torch.utils.data.ConcatDataset): + def __init__(self, datasets, shape_constraints: dict[str, list[int]] = {}): + super().__init__(datasets) + + self.sample = shape_constraints["sample"] + self.shape_mult = shape_constraints["shape_mult"] + self.ratio_bounds = shape_constraints["ratio_bounds"] + self.pixels_max = shape_constraints["pixels_max"] + self.pixels_min = shape_constraints["pixels_min"] + + self.height_min = shape_constraints["height_min"] + self.width_min = shape_constraints["width_min"] + + def sample_shape(self): + if not self.sample: + return + # 1: sample image ratio + ratio = np.random.uniform(*self.ratio_bounds) + pixels_min = self.pixels_min // (self.shape_mult * self.shape_mult) + pixels_max = self.pixels_max // (self.shape_mult * self.shape_mult) + # 2: sample image height or width, if ratio > 1 or < 1 + if ratio > 1: + height_min = max(self.height_min, np.sqrt(pixels_min / ratio)) + height = np.random.uniform(height_min, np.sqrt(pixels_max / ratio)) + width = height * ratio + else: + width_min = max(self.width_min, np.sqrt(pixels_min * ratio)) + width = np.random.uniform(width_min, np.sqrt(pixels_max * ratio)) + height = width / ratio + # 3: get final shape based on the shape_mult + shape = [int(height) * self.shape_mult, int(width) * self.shape_mult] + for dataset in self.datasets: + setattr(dataset, "image_shape", shape) + setattr(dataset.resizer, "image_shape", shape) + + def __getitem__(self, idxs): + self.sample_shape() + return [super(ConcatDataset, self).__getitem__(idx) for idx in idxs] + + +def _paddings(image_shape, network_shape): + cur_h, cur_w = image_shape + h, w = network_shape + pad_top, pad_bottom = (h - cur_h) // 2, h - cur_h - (h - cur_h) // 2 + pad_left, pad_right = (w - cur_w) // 2, w - cur_w - (w - cur_w) // 2 + return pad_left, pad_right, pad_top, pad_bottom + + +def collate_fn(in_data: List[List[Dict[str, Any]]], is_batched: bool = True): + out_data = defaultdict(list) + img_metas = [] + in_data = in_data[0] if is_batched else in_data + + # get max_shape and paddings + shapes = [tensor.shape[-2:] for x in in_data for tensor in x["depth"].values()] + max_shape_tuple = tuple(max(elements) for elements in zip(*shapes)) + paddings = [ + [ + _paddings(tensor.shape[-2:], max_shape_tuple) + for tensor in x["depth"].values() + ] + for x in in_data + ] + + for x in in_data: # here iter over batches + padding = paddings.pop(0) + for k, v in x.items(): + if "img_metas" not in k: + values = list(v.values()) + v = torch.cat(values) + out_data[k].append(v) + else: + v["depth_paddings"] = padding + img_metas.append(v) + + output_dict = { + "data": {k: torch.stack(v, dim=0) for k, v in out_data.items()}, + "img_metas": img_metas, + } + # camera are always flattened and the stack/cat so if list of B times (T, 3, 3) cameras + # it goes to (B * T, 3, 3), to be consistent with the image shape -> reshape + if "camera" in output_dict["data"]: + output_dict["data"]["camera"] = output_dict["data"]["camera"].reshape( + *output_dict["data"]["image"].shape[:2] + ) + return output_dict + + +def local_scatter(array: list[Any]): + """ + Scatter an array from local leader to all local workers. + The i-th local worker gets array[i]. + + Args: + array: Array with same size of #local workers. + """ + if get_world_size() == 1: + return array[0] + if get_local_rank() == 0: + assert len(array) == get_local_size() + all_gather(array) + else: + all_data = all_gather(None) + array = all_data[get_rank() - get_local_rank()] + return array[get_local_rank()] + + +class DatasetFromList(torch.utils.data.Dataset): # type: ignore + """Wrap a list to a torch Dataset. + + We serialize and wrap big python objects in a torch.Dataset due to a + memory leak when dealing with large python objects using multiple workers. + See: https://github.com/pytorch/pytorch/issues/13246 + """ + + def __init__(self, lst: List[Any], deepcopy: bool = False, serialize: bool = True): + """Creates an instance of the class. + + Args: + lst: a list which contains elements to produce. + deepcopy: whether to deepcopy the element when producing it, s.t. + the result can be modified in place without affecting the source + in the list. + serialize: whether to hold memory using serialized objects. When + enabled, data loader workers can use shared RAM from master + process instead of making a copy. + """ + self._copy = deepcopy + self._serialize = serialize + + def _serialize(data: Any): + buffer = pickle.dumps(data, protocol=pickle.HIGHEST_PROTOCOL) + return torch.frombuffer(buffer, dtype=torch.uint8) + + if self._serialize: + # load only on 0th rank + if get_local_rank() == 0: + _lst = [_serialize(x) for x in lst] + self._addr = torch.cumsum( + torch.tensor([len(x) for x in _lst], dtype=torch.int64), dim=0 + ) + self._lst = torch.concatenate(_lst) + # Move data to shared memory, obtain a handle to send to each local worker. + handles = [None] + [ + bytes(mp.reduction.ForkingPickler.dumps((self._addr, self._lst))) + for _ in range(get_local_size() - 1) + ] + else: + handles = None + + # Each worker receives the handle from local leader (rank 0) + # then materialize the tensor from shared memory + handle = local_scatter(handles) + if get_local_rank() > 0: + self._addr, self._lst = mp.reduction.ForkingPickler.loads(handle) + + else: + self._lst = lst + + def __len__(self) -> int: + """Return len of list.""" + if self._serialize: + return len(self._addr) + return len(self._lst) + + def __getitem__(self, idx: int) -> Any: + """Return item of list at idx.""" + if self._serialize: + start_addr = 0 if idx == 0 else self._addr[idx - 1] + end_addr = self._addr[idx] + bytes_ = memoryview(self._lst[start_addr:end_addr].numpy()) + return pickle.loads(bytes_) + if self._copy: + return copy.deepcopy(self._lst[idx]) + + return self._lst[idx] + + +def get_weights( + train_datasets: dict[str, torch.utils.data.Dataset], sampling: dict[str, float] +) -> torch.Tensor: + from .image_dataset import ImageDataset + from .sequence_dataset import SequenceDataset + + weights = [] + num_samples = 0 + info_weights = {} + for dataset_name, dataset in train_datasets.items(): + assert ( + dataset_name in sampling + ), f"Dataset {dataset_name} not found in {sampling.keys()}" + + if isinstance(dataset, ImageDataset): + # sum of all samples has weight as in sampling s.t. sampling dataset in general is as in sampling + # inside is uniform + weight = sampling[dataset_name] / len(dataset) + weights.append(torch.full((len(dataset),), weight).double()) + num_samples += len(dataset) + + elif isinstance(dataset, SequenceDataset): + # local weight is num_samples, but global must be as in sampling + # hence is num_samples / (sum num_samples / sampling[dataset_name]) + # s.t. sampling anything from the dataset is + # sum(num_samples / (sum num_samples / sampling[dataset_name])) + # -> sampling[dataset_name] + numerator = [int(data["num_samples"]) for data in dataset.dataset] + weights.append( + sampling[dataset_name] + * torch.tensor(numerator).double() + / sum(numerator) + ) + num_samples += sum(numerator) + + else: + weight = sampling[dataset_name] / len(dataset) + weights.append(torch.full((len(dataset),), weight).double()) + + info_weights[dataset_name] = weights[-1][-1] + + return torch.cat(weights), num_samples diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/utils_decode.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/utils_decode.py new file mode 100644 index 0000000000000000000000000000000000000000..b93d2d611f00bd9a3f50e0be197010e1fa2fda5c --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/utils_decode.py @@ -0,0 +1,122 @@ +import io + +import cv2 +import numpy as np +import torch +import torchvision +import torchvision.transforms.v2.functional as TF +from PIL import Image + +from unidepth.utils.camera import (EUCM, MEI, BatchCamera, Fisheye624, Pinhole, + Spherical) + + +def decode_depth(results, h5file, value, idx, depth_scale, name="depth", **kwargs): + file = h5file.get_node("/" + value).read() + decoded_data = Image.open(io.BytesIO(file)) + decoded_data = TF.pil_to_tensor(decoded_data).squeeze() + + if decoded_data.ndim == 3: # 24 channel loading + decoded_channels = [ + (decoded_data[0] & 0xFF).to(torch.int32), + (decoded_data[1] & 0xFF).to(torch.int32), + (decoded_data[2] & 0xFF).to(torch.int32), + ] + # Reshape and extract the original depth map + decoded_data = ( + decoded_channels[0] + | (decoded_channels[1] << 8) + | (decoded_channels[2] << 16) + ) + + decoded_data = decoded_data.to(torch.float32) + results.get("gt_fields", set()).add(name) + results[(idx, 0)].get("gt_fields", set()).add(name) + results[f"{name}_ori_shape"] = decoded_data.shape + results[(idx, 0)][name] = ( + decoded_data.view(1, 1, *decoded_data.shape).contiguous() / depth_scale + ) + return results + + +def decode_numpy(results, h5file, value, idx, name="points", **kwargs): + file = h5file.get_node("/" + value).read() + decoded_data = np.load(io.BytesIO(file), allow_pickle=False) + decoded_data = torch.from_numpy(decoded_data).to(torch.float32) + if decoded_data.ndim > 2: + decoded_data = decoded_data.permute(2, 0, 1) + results.get("gt_fields", set()).add(name) + results[(idx, 0)].get("gt_fields", set()).add(name) + results[(idx, 0)][name] = decoded_data.unsqueeze(0) + return results + + +def decode_tensor(results, value, idx, name, **kwargs): + results.get("camera_fields", set()).add(name) + results[(idx, 0)].get("camera_fields", set()).add(name) + results[(idx, 0)][name] = torch.tensor(value).unsqueeze(0) + return results + + +def decode_camera(results, value, idx, name, sample, j, **kwargs): + results.get("camera_fields", set()).add(name) + results[(idx, 0)].get("camera_fields", set()).add(name) + camera = eval(sample["camera_model"][j])(params=torch.tensor(value).unsqueeze(0)) + results[(idx, 0)][name] = BatchCamera.from_camera(camera) + return results + + +def decode_K(results, value, idx, name, **kwargs): + results.get("camera_fields", set()).add(name) + results[(idx, 0)].get("camera_fields", set()).add(name) + camera = Pinhole(K=torch.tensor(value).unsqueeze(0)) + results[(idx, 0)][name] = BatchCamera.from_camera(camera) + return results + + +def decode_mask(results, h5file, value, idx, name, **kwargs): + file = h5file.get_node("/" + value).read() + mask = torchvision.io.decode_image(torch.from_numpy(file)).bool().squeeze() + results.get("mask_fields", set()).add(name) + results[(idx, 0)].get("mask_fields", set()).add(name) + results[f"{name}_ori_shape"] = mask.shape[-2:] + results[(idx, 0)][name] = mask.view(1, 1, *mask.shape).contiguous() + return results + + +def decode_rgb(results, h5file, value, idx, name="image", **kwargs): + file = h5file.get_node("/" + value).read() + image = ( + torchvision.io.decode_image(torch.from_numpy(file)).to(torch.uint8).squeeze() + ) + results.get("image_fields", set()).add(name) + results[(idx, 0)].get("image_fields", set()).add(name) + results[f"{name}_ori_shape"] = image.shape[-2:] + if image.ndim == 2: + image = image.unsqueeze(0).repeat(3, 1, 1) + results[(idx, 0)][name] = image.unsqueeze(0) + return results + + +def decode_flow(results, h5file, value, idx, name, **kwargs): + file = h5file.get_node("/" + value).read() + image = ( + torchvision.io.decode_image(torch.from_numpy(file)).to(torch.uint8).squeeze() + ) + decoded_channels = [ + (image[0] & 0xFF).to(torch.int16), + (image[1] & 0xFF).to(torch.int16), + (image[2] & 0xFF).to(torch.int16), + ] + + # Reshape and extract the original 2-channel flow map + flow = torch.zeros((2, image.shape[1], image.shape[2]), dtype=torch.int16) + flow[0] = (decoded_channels[0] | decoded_channels[1] << 8) & 0xFFF + flow[1] = (decoded_channels[1] >> 4 | decoded_channels[2] << 4) & 0xFFF + + results.get("gt_fields", set()).add(name) + results[(idx, 0)].get("gt_fields", set()).add(name) + results[f"{name}_ori_shape"] = flow.shape[-2:] + flow = flow.unsqueeze(0).contiguous().float() + results[(idx, 0)][name] = (0.5 + flow) / 4095.0 * 2 - 1 + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/vkitti.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/vkitti.py new file mode 100644 index 0000000000000000000000000000000000000000..244dee937d0798d3982e1f90fe002774fdac6701 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/vkitti.py @@ -0,0 +1,50 @@ +from typing import Any + +from unidepth.datasets.sequence_dataset import SequenceDataset + + +class VKITTI(SequenceDataset): + min_depth = 0.01 + max_depth = 255.0 + depth_scale = 256.0 + test_split = "training.txt" + train_split = "training.txt" + sequences_file = "sequences.json" + hdf5_paths = ["VKITTI2.hdf5"] + + def __init__( + self, + image_shape: tuple[int, int], + split_file: str, + test_mode: bool, + normalize: bool, + augmentations_db: dict[str, Any], + resize_method: str, + mini: float = 1.0, + num_frames: int = 1, + benchmark: bool = False, + decode_fields: list[str] = ["image", "depth", "flow_fwd", "flow_fwd_mask"], + inplace_fields: list[str] = ["K", "cam2w"], + **kwargs, + ) -> None: + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + num_frames=num_frames, + decode_fields=decode_fields, + inplace_fields=inplace_fields, + **kwargs, + ) + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [True] * self.num_frames * self.num_copies + results["synthetic"] = [True] * self.num_frames * self.num_copies + results["quality"] = [0] * self.num_frames * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/void.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/void.py new file mode 100644 index 0000000000000000000000000000000000000000..c4c2d6876e5477fcd44fa1b923014ac1b0c619b5 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/void.py @@ -0,0 +1,79 @@ +import json +import os + +import h5py +import numpy as np +import torch + +from unidepth.datasets.image_dataset import ImageDataset +from unidepth.datasets.utils import DatasetFromList + + +class VOID(ImageDataset): + min_depth = 0.01 + max_depth = 10.0 + depth_scale = 256.0 + test_split = "void_val.txt" + train_split = "void_train.txt" + intrisics_file = "void_intrinsics.json" + hdf5_paths = ["void.hdf5"] + + def __init__( + self, + image_shape, + split_file, + test_mode, + crop=None, + benchmark=False, + augmentations_db={}, + normalize=True, + resize_method="hard", + mini=1.0, + **kwargs, + ): + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + **kwargs, + ) + self.test_mode = test_mode + + self.crop = crop + self.load_dataset() + + def load_dataset(self): + h5file = h5py.File( + os.path.join(self.data_root, self.hdf5_paths[0]), + "r", + libver="latest", + swmr=True, + ) + txt_file = np.array(h5file[self.split_file]) + txt_string = txt_file.tostring().decode("ascii")[:-1] # correct the -1 + intrinsics = np.array(h5file[self.intrisics_file]).tostring().decode("ascii") + intrinsics = json.loads(intrinsics) + h5file.close() + dataset = [] + for line in txt_string.split("\n"): + image_filename, depth_filename = line.strip().split(" ") + intrinsics_val = torch.tensor(intrinsics[image_filename]).squeeze()[:, :3] + sample = [image_filename, depth_filename, intrinsics_val] + dataset.append(sample) + + if not self.test_mode: + dataset = self.chunk(dataset, chunk_dim=1, pct=self.mini) + + self.dataset = DatasetFromList(dataset) + self.log_load_dataset() + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [True] * self.num_copies + results["quality"] = [2] * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/waymo.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/waymo.py new file mode 100644 index 0000000000000000000000000000000000000000..3febea75c717df5731a818fce8adc3425635bcb9 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/waymo.py @@ -0,0 +1,50 @@ +from typing import Any + +from unidepth.datasets.sequence_dataset import SequenceDataset + + +class Waymo(SequenceDataset): + min_depth = 0.05 + max_depth = 70.0 + depth_scale = 256.0 + test_split = "validation.txt" + train_split = "training.txt" + sequences_file = "sequences.json" + hdf5_paths = [f"Waymo_viz.hdf5"] + + def __init__( + self, + image_shape: tuple[int, int], + split_file: str, + test_mode: bool, + normalize: bool, + augmentations_db: dict[str, Any], + resize_method: str, + mini: float = 1.0, + num_frames: int = 1, + benchmark: bool = False, + decode_fields: list[str] = ["image", "depth"], + inplace_fields: list[str] = ["K", "cam2w"], + **kwargs, + ) -> None: + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + num_frames=num_frames, + decode_fields=decode_fields, + inplace_fields=inplace_fields, + **kwargs, + ) + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [False] * self.num_frames * self.num_copies + results["synthetic"] = [False] * self.num_frames * self.num_copies + results["quality"] = [1] * self.num_frames * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/wildrgbd.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/wildrgbd.py new file mode 100644 index 0000000000000000000000000000000000000000..3f8dc6a718407060e277dc2091b113f669f9662f --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/datasets/wildrgbd.py @@ -0,0 +1,50 @@ +from typing import Any + +from unidepth.datasets.sequence_dataset import SequenceDataset + + +class WildRGBD(SequenceDataset): + min_depth = 0.01 + max_depth = 10.0 + depth_scale = 1000.0 + test_split = "train.txt" + train_split = "train.txt" + sequences_file = "sequences.json" + hdf5_paths = ["WildRGBD.hdf5"] + default_fps = 30 + + def __init__( + self, + image_shape: tuple[int, int], + split_file: str, + test_mode: bool, + normalize: bool, + augmentations_db: dict[str, Any], + resize_method: str, + mini: float = 1.0, + num_frames: int = 1, + benchmark: bool = False, + decode_fields: list[str] = ["image", "depth"], + inplace_fields: list[str] = ["K", "cam2w"], + **kwargs, + ) -> None: + super().__init__( + image_shape=image_shape, + split_file=split_file, + test_mode=test_mode, + benchmark=benchmark, + normalize=normalize, + augmentations_db=augmentations_db, + resize_method=resize_method, + mini=mini, + num_frames=num_frames, + decode_fields=decode_fields, + inplace_fields=inplace_fields, + **kwargs, + ) + + def pre_pipeline(self, results): + results = super().pre_pipeline(results) + results["dense"] = [True] * self.num_frames * self.num_copies + results["quality"] = [1] * self.num_frames * self.num_copies + return results diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/layers/__init__.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/layers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..74fdf6e27b12cba012dd9cafcfa6093b7e32637e --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/layers/__init__.py @@ -0,0 +1,22 @@ +from .activation import GEGLU, SwiGLU +from .attention import AttentionBlock, AttentionDecoderBlock, AttentionLayer +from .convnext import CvnxtBlock +from .mlp import MLP +from .nystrom_attention import NystromBlock +from .positional_encoding import PositionEmbeddingSine +from .upsample import (ConvUpsample, ConvUpsampleShuffle, + ConvUpsampleShuffleResidual, ResUpsampleBil) + +__all__ = [ + "SwiGLU", + "GEGLU", + "CvnxtBlock", + "AttentionBlock", + "NystromBlock", + "PositionEmbeddingSine", + "ConvUpsample", + "MLP", + "ConvUpsampleShuffle", + "AttentionDecoderBlock", + "ConvUpsampleShuffleResidual", +] diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/layers/activation.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/layers/activation.py new file mode 100644 index 0000000000000000000000000000000000000000..f5787a340013ba59e2956b6b829f724d9cfb7fcc --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/layers/activation.py @@ -0,0 +1,15 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F + + +class SwiGLU(nn.Module): + def forward(self, x: torch.Tensor) -> torch.Tensor: + x, gates = x.chunk(2, dim=-1) + return x * F.silu(gates) + + +class GEGLU(nn.Module): + def forward(self, x: torch.Tensor) -> torch.Tensor: + x, gates = x.chunk(2, dim=-1) + return x * F.gelu(gates) diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/layers/attention.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/layers/attention.py new file mode 100644 index 0000000000000000000000000000000000000000..58fec228b169977d8f5d055508390039204b82ce --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/layers/attention.py @@ -0,0 +1,351 @@ +""" +Author: Luigi Piccinelli +Licensed under the CC-BY NC 4.0 license (http://creativecommons.org/licenses/by-nc/4.0/) +""" + +from functools import partial + +import torch +import torch.nn as nn +import torch.nn.functional as F +from einops import rearrange + +from .layer_scale import LayerScale +from .mlp import MLP + + +class SimpleAttention(nn.Module): + def __init__( + self, + dim: int, + num_heads: int = 4, + dropout: float = 0.0, + cosine: bool = False, + context_dim: int | None = None, + ): + super().__init__() + self.dropout = dropout + self.num_heads = num_heads + self.hidden_dim = dim + context_dim = context_dim or dim + + self.kv = nn.Linear(context_dim, dim * 2, bias=False) + self.q = nn.Linear(dim, dim, bias=False) + self.norm_attnx = nn.LayerNorm(dim) + self.norm_attnctx = nn.LayerNorm(context_dim) + self.cosine = cosine + self.out = nn.Linear(dim, dim) + + def forward( + self, + x: torch.Tensor, + attn_bias: torch.Tensor | None = None, + context: torch.Tensor | None = None, + pos_embed: torch.Tensor | None = None, + pos_embed_context: torch.Tensor | None = None, + rope: nn.Module | None = None, + ) -> torch.Tensor: + context = x if context is None else context + x = self.norm_attnx(x) + context = self.norm_attnctx(context) + k, v = rearrange( + self.kv(context), "b n (kv h d) -> b h n d kv", h=self.num_heads, kv=2 + ).unbind(dim=-1) + q = rearrange(self.q(x), "b n (h d) -> b h n d", h=self.num_heads) + + if rope is not None: + q = rope(q) + k = rope(k) + else: + if pos_embed is not None: + pos_embed = rearrange( + pos_embed, "b n (h d) -> b h n d", h=self.num_heads + ) + q = q + pos_embed + if pos_embed_context is not None: + pos_embed_context = rearrange( + pos_embed_context, "b n (h d) -> b h n d", h=self.num_heads + ) + k = k + pos_embed_context + + if self.cosine: + q, k = map(partial(F.normalize, p=2, dim=-1), (q, k)) # cosine sim + x = F.scaled_dot_product_attention( + q, k, v, dropout_p=self.dropout, attn_mask=attn_bias + ) + x = rearrange(x, "b h n d -> b n (h d)") + x = self.out(x) + return x + + +class AttentionBlock(nn.Module): + def __init__( + self, + dim: int, + num_heads: int = 4, + expansion: int = 4, + dropout: float = 0.0, + cosine: bool = False, + gated: bool = False, + layer_scale: float = 1.0, + context_dim: int | None = None, + use_bias: bool = True, + ): + super().__init__() + self.dropout = dropout + self.num_heads = num_heads + self.hidden_dim = dim + context_dim = context_dim or dim + self.mlp = MLP(dim, expansion=expansion, dropout=dropout, gated=gated) + self.kv = nn.Linear(context_dim, dim * 2, bias=use_bias) + self.q = nn.Linear(dim, dim, bias=use_bias) + self.norm_attnx = nn.LayerNorm(dim) + self.norm_attnctx = nn.LayerNorm(context_dim) + self.cosine = cosine + self.out = nn.Linear(dim, dim, bias=use_bias) + self.ls1 = LayerScale(dim, layer_scale) if layer_scale > 0.0 else nn.Identity() + self.ls2 = LayerScale(dim, layer_scale) if layer_scale > 0.0 else nn.Identity() + + def attn( + self, + x: torch.Tensor, + attn_bias: torch.Tensor | None = None, + context: torch.Tensor | None = None, + pos_embed: torch.Tensor | None = None, + pos_embed_context: torch.Tensor | None = None, + ) -> torch.Tensor: + x = self.norm_attnx(x) + context = self.norm_attnctx(context) + k, v = rearrange( + self.kv(context), "b n (kv h d) -> b h n d kv", h=self.num_heads, kv=2 + ).unbind(dim=-1) + q = rearrange(self.q(x), "b n (h d) -> b h n d", h=self.num_heads) + + if pos_embed is not None: + pos_embed = rearrange(pos_embed, "b n (h d) -> b h n d", h=self.num_heads) + q = q + pos_embed + if pos_embed_context is not None: + pos_embed_context = rearrange( + pos_embed_context, "b n (h d) -> b h n d", h=self.num_heads + ) + k = k + pos_embed_context + + if self.cosine: + q, k = map(partial(F.normalize, p=2, dim=-1), (q, k)) # cosine sim + + x = F.scaled_dot_product_attention( + q, k, v, dropout_p=self.dropout, attn_mask=attn_bias + ) + x = rearrange(x, "b h n d -> b n (h d)") + x = self.out(x) + return x + + def forward( + self, + x: torch.Tensor, + attn_bias: torch.Tensor | None = None, + context: torch.Tensor | None = None, + pos_embed: torch.Tensor | None = None, + pos_embed_context: torch.Tensor | None = None, + ) -> torch.Tensor: + context = x if context is None else context + x = ( + self.ls1( + self.attn( + x, + attn_bias=attn_bias, + context=context, + pos_embed=pos_embed, + pos_embed_context=pos_embed_context, + ) + ) + + x + ) + x = self.ls2(self.mlp(x)) + x + return x + + +class AttentionLayer(nn.Module): + def __init__( + self, + num_blocks: int, + dim: int, + num_heads: int = 4, + expansion: int = 4, + dropout: float = 0.0, + cosine: bool = False, + gated: bool = False, + layer_scale: float = 1.0, + context_dim: int | None = None, + use_bias: bool = True, + ): + super().__init__() + self.layers = nn.ModuleList( + [ + AttentionBlock( + dim=dim, + num_heads=num_heads, + expansion=expansion, + dropout=dropout, + cosine=cosine, + gated=gated, + layer_scale=layer_scale, + context_dim=context_dim, + use_bias=use_bias, + ) + for _ in range(num_blocks) + ] + ) + + def forward( + self, + x: torch.Tensor, + context: torch.Tensor | None = None, + pos_embed: torch.Tensor | None = None, + pos_embed_context: torch.Tensor | None = None, + attn_bias: torch.Tensor | None = None, + ) -> torch.Tensor: + for layer in self.layers: + x = layer( + x, + context=context, + pos_embed=pos_embed, + pos_embed_context=pos_embed_context, + attn_bias=attn_bias, + ) + return x + + +class AttentionDecoderBlock(nn.Module): + def __init__( + self, + dim: int, + num_heads: int = 4, + expansion: int = 4, + dropout: float = 0.0, + cosine: bool = False, + gated: bool = False, + layer_scale: float = 1.0, + context_dim: int | None = None, + single_head_ca: bool = True, + ): + super().__init__() + self.dropout = dropout + self.num_heads = num_heads + self.hidden_dim = dim + self.single_head_ca = single_head_ca + context_dim = context_dim or dim + self.mlp = MLP(dim, expansion=expansion, dropout=dropout, gated=gated) + self.kv_ca = nn.Linear(context_dim, dim * 2) + self.q_ca = nn.Linear(dim, dim) + self.kv_sa = nn.Linear(dim, dim * 2) + self.q_sa = nn.Linear(dim, dim) + self.norm_x_sa = nn.LayerNorm(dim) + self.norm_x_ca = nn.LayerNorm(dim) + self.norm_ctx_ca = nn.LayerNorm(context_dim) + self.cosine = cosine + self.out_ca = nn.Linear(dim, dim) + self.out_sa = nn.Linear(dim, dim) + self.ls1 = LayerScale(dim, layer_scale) if layer_scale > 0.0 else nn.Identity() + self.ls2 = LayerScale(dim, layer_scale) if layer_scale > 0.0 else nn.Identity() + self.ls3 = LayerScale(dim, layer_scale) if layer_scale > 0.0 else nn.Identity() + + def cross_attn( + self, + x: torch.Tensor, + attn_bias: torch.Tensor | None = None, + context: torch.Tensor | None = None, + pos_embed: torch.Tensor | None = None, + pos_embed_context: torch.Tensor | None = None, + rope: nn.Module | None = None, + ) -> torch.Tensor: + num_heads = 1 if self.single_head_ca else self.num_heads + x = self.norm_x_ca(x) + context = self.norm_ctx_ca(context) + k, v = rearrange( + self.kv_ca(context), "b n (kv h d) -> b h n d kv", h=num_heads, kv=2 + ).unbind(dim=-1) + q = rearrange(self.q_ca(x), "b n (h d) -> b h n d", h=num_heads) + + if rope is not None: + q = rope(q) + k = rope(k) + else: + if pos_embed is not None: + pos_embed = rearrange(pos_embed, "b n (h d) -> b h n d", h=num_heads) + q = q + pos_embed + if pos_embed_context is not None: + pos_embed_context = rearrange( + pos_embed_context, "b n (h d) -> b h n d", h=num_heads + ) + k = k + pos_embed_context + + if self.cosine: + q, k = map(partial(F.normalize, p=2, dim=-1), (q, k)) # cosine sim + x = F.scaled_dot_product_attention( + q, k, v, dropout_p=self.dropout, attn_mask=attn_bias + ) + x = rearrange(x, "b h n d -> b n (h d)") + x = self.out_ca(x) + return x + + def self_attn( + self, + x: torch.Tensor, + attn_bias: torch.Tensor | None = None, + pos_embed: torch.Tensor | None = None, + rope: nn.Module | None = None, + ) -> torch.Tensor: + x = self.norm_x_sa(x) + k, v = rearrange( + self.kv_sa(x), "b n (kv h d) -> b h n d kv", h=self.num_heads, kv=2 + ).unbind(dim=-1) + q = rearrange(self.q_sa(x), "b n (h d) -> b h n d", h=self.num_heads) + + if rope is not None: + q = rope(q) + k = rope(k) + elif pos_embed is not None: + pos_embed = rearrange(pos_embed, "b n (h d) -> b h n d", h=self.num_heads) + q = q + pos_embed + + if self.cosine: + q, k = map(partial(F.normalize, p=2, dim=-1), (q, k)) # cosine sim + x = F.scaled_dot_product_attention( + q, k, v, dropout_p=self.dropout, attn_mask=attn_bias + ) + x = rearrange(x, "b h n d -> b n (h d)") + x = self.out_sa(x) + return x + + def forward( + self, + x: torch.Tensor, + attn_bias: torch.Tensor | None = None, + context: torch.Tensor | None = None, + pos_embed: torch.Tensor | None = None, + pos_embed_context: torch.Tensor | None = None, + rope: nn.Module | None = None, + ) -> torch.Tensor: + context = x if context is None else context + x = ( + self.ls1( + self.cross_attn( + x, + rope=rope, + attn_bias=attn_bias, + context=context, + pos_embed=pos_embed, + pos_embed_context=pos_embed_context, + ) + ) + + x + ) + x = ( + self.ls2( + self.self_attn(x, rope=rope, attn_bias=attn_bias, pos_embed=pos_embed) + ) + + x + ) + x = self.ls3(self.mlp(x)) + x + return x diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/layers/convnext.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/layers/convnext.py new file mode 100644 index 0000000000000000000000000000000000000000..23a104b1b444313b84aff0a1a92a5600ec42d288 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/layers/convnext.py @@ -0,0 +1,44 @@ +import torch +import torch.nn as nn + + +class CvnxtBlock(nn.Module): + def __init__( + self, + dim, + kernel_size=7, + layer_scale=1.0, + expansion=4, + dilation=1, + padding_mode: str = "zeros", + ): + super().__init__() + self.dwconv = nn.Conv2d( + dim, + dim, + kernel_size=kernel_size, + padding=dilation * (kernel_size - 1) // 2, + groups=dim, + dilation=dilation, + padding_mode=padding_mode, + ) # depthwise conv + self.norm = nn.LayerNorm(dim) + self.pwconv1 = nn.Linear(dim, expansion * dim) + self.act = nn.GELU() + self.pwconv2 = nn.Linear(expansion * dim, dim) + self.gamma = ( + nn.Parameter(layer_scale * torch.ones((dim))) if layer_scale > 0.0 else 1.0 + ) + + def forward(self, x): + input = x + x = self.dwconv(x) + x = x.permute(0, 2, 3, 1) # (N, C, H, W) -> (N, H, W, C) + x = self.norm(x) + x = self.pwconv1(x) + x = self.act(x) + x = self.pwconv2(x) + + x = self.gamma * x + x = input + x.permute(0, 3, 1, 2) # (N, H, W, C) -> (N, C, H, W) + return x diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/layers/drop_path.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/layers/drop_path.py new file mode 100644 index 0000000000000000000000000000000000000000..781ff566500c923b1f199542b0c7dfb862a077ca --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/layers/drop_path.py @@ -0,0 +1,25 @@ +import torch +import torch.nn as nn + + +def drop_path(x: torch.Tensor, drop_prob: float = 0.0, training: bool = False): + if drop_prob == 0.0 or not training: + return x + keep_prob = 1 - drop_prob + shape = (x.shape[0],) + (1,) * ( + x.ndim - 1 + ) # work with diff dim tensors, not just 2D ConvNets + random_tensor = x.new_empty(shape).bernoulli_(keep_prob) + if keep_prob > 0.0: + random_tensor.div_(keep_prob) + output = x * random_tensor + return output + + +class DropPath(nn.Module): + def __init__(self, drop_prob=None): + super(DropPath, self).__init__() + self.drop_prob = drop_prob + + def forward(self, x): + return drop_path(x, self.drop_prob, self.training) diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/layers/layer_scale.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/layers/layer_scale.py new file mode 100644 index 0000000000000000000000000000000000000000..01b6662490d7296725f103d1abf8790cac84d0f8 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/layers/layer_scale.py @@ -0,0 +1,17 @@ +import torch +import torch.nn as nn + + +class LayerScale(nn.Module): + def __init__( + self, + dim: int, + init_values: float | torch.Tensor = 1e-5, + inplace: bool = False, + ) -> None: + super().__init__() + self.inplace = inplace + self.gamma = nn.Parameter(init_values * torch.ones(dim)) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return x.mul_(self.gamma) if self.inplace else x * self.gamma diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/layers/mlp.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/layers/mlp.py new file mode 100644 index 0000000000000000000000000000000000000000..c9340834b0ad047bf87915d12a124276248d713f --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/layers/mlp.py @@ -0,0 +1,35 @@ +import torch +import torch.nn as nn + +from unidepth.utils.misc import default + +from .activation import SwiGLU + + +class MLP(nn.Module): + def __init__( + self, + input_dim: int, + expansion: int = 4, + dropout: float = 0.0, + gated: bool = False, + output_dim: int | None = None, + ): + super().__init__() + if gated: + expansion = int(expansion * 2 / 3) + hidden_dim = int(input_dim * expansion) + output_dim = default(output_dim, input_dim) + self.norm = nn.LayerNorm(input_dim) + self.proj1 = nn.Linear(input_dim, hidden_dim) + self.proj2 = nn.Linear(hidden_dim, output_dim) + self.act = nn.GELU() if not gated else SwiGLU() + self.dropout = nn.Dropout(dropout) if dropout > 0.0 else nn.Identity() + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = self.norm(x) + x = self.proj1(x) + x = self.act(x) + x = self.proj2(x) + x = self.dropout(x) + return x diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/layers/nystrom_attention.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/layers/nystrom_attention.py new file mode 100644 index 0000000000000000000000000000000000000000..9f7476f114a68617bf64bc4cb51eec6c98445df5 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/layers/nystrom_attention.py @@ -0,0 +1,74 @@ +from functools import partial + +import torch +import torch.nn as nn +import torch.nn.functional as F +from einops import rearrange +from xformers.components.attention import NystromAttention + +from .attention import AttentionBlock + + +class NystromBlock(AttentionBlock): + def __init__( + self, + dim: int, + num_heads: int = 4, + expansion: int = 4, + dropout: float = 0.0, + cosine: bool = False, + gated: bool = False, + layer_scale: float = 1.0, + context_dim: int | None = None, + ): + super().__init__( + dim=dim, + num_heads=num_heads, + expansion=expansion, + dropout=dropout, + cosine=cosine, + gated=gated, + layer_scale=layer_scale, + context_dim=context_dim, + ) + self.attention_fn = NystromAttention( + num_landmarks=128, num_heads=num_heads, dropout=dropout + ) + + def attn( + self, + x: torch.Tensor, + attn_bias: torch.Tensor | None = None, + context: torch.Tensor | None = None, + pos_embed: torch.Tensor | None = None, + pos_embed_context: torch.Tensor | None = None, + rope: nn.Module | None = None, + ) -> torch.Tensor: + x = self.norm_attnx(x) + context = self.norm_attnctx(context) + k, v = rearrange( + self.kv(context), "b n (kv h d) -> b n h d kv", h=self.num_heads, kv=2 + ).unbind(dim=-1) + q = rearrange(self.q(x), "b n (h d) -> b n h d", h=self.num_heads) + + if rope is not None: + q = rope(q) + k = rope(k) + else: + if pos_embed is not None: + pos_embed = rearrange( + pos_embed, "b n (h d) -> b n h d", h=self.num_heads + ) + q = q + pos_embed + if pos_embed_context is not None: + pos_embed_context = rearrange( + pos_embed_context, "b n (h d) -> b n h d", h=self.num_heads + ) + k = k + pos_embed_context + + if self.cosine: + q, k = map(partial(F.normalize, p=2, dim=-1), (q, k)) # cosine sim + x = self.attention_fn(q, k, v, key_padding_mask=attn_bias) + x = rearrange(x, "b n h d -> b n (h d)") + x = self.out(x) + return x diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/layers/positional_encoding.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/layers/positional_encoding.py new file mode 100644 index 0000000000000000000000000000000000000000..431918d6b281bd7e3588d6c04425e2eacd6c23e4 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/layers/positional_encoding.py @@ -0,0 +1,227 @@ +""" +Author: Luigi Piccinelli +Licensed under the CC-BY NC 4.0 license (http://creativecommons.org/licenses/by-nc/4.0/) +""" + +from math import pi +from typing import Optional + +import torch +import torch.nn as nn +from einops import rearrange, repeat + + +class PositionEmbeddingSine(nn.Module): + def __init__( + self, num_pos_feats=64, temperature=10000, normalize=False, scale=None + ): + super().__init__() + self.num_pos_feats = num_pos_feats + self.temperature = temperature + self.normalize = normalize + if scale is not None and normalize is False: + raise ValueError("normalize should be True if scale is passed") + if scale is None: + scale = 2 * pi + self.scale = scale + + def forward( + self, x: torch.Tensor, mask: Optional[torch.Tensor] = None + ) -> torch.Tensor: + if mask is None: + mask = torch.zeros( + (x.size(0), x.size(2), x.size(3)), device=x.device, dtype=torch.bool + ) + not_mask = ~mask + y_embed = not_mask.cumsum(1, dtype=torch.float32) + x_embed = not_mask.cumsum(2, dtype=torch.float32) + if self.normalize: + eps = 1e-6 + y_embed = y_embed / (y_embed[:, -1:, :] + eps) * self.scale + x_embed = x_embed / (x_embed[:, :, -1:] + eps) * self.scale + + dim_t = torch.arange(self.num_pos_feats, dtype=torch.float32, device=x.device) + dim_t = self.temperature ** ( + 2 * torch.div(dim_t, 2, rounding_mode="floor") / self.num_pos_feats + ) + + pos_x = x_embed[:, :, :, None] / dim_t + pos_y = y_embed[:, :, :, None] / dim_t + pos_x = torch.stack( + (pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()), dim=4 + ).flatten(3) + pos_y = torch.stack( + (pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()), dim=4 + ).flatten(3) + pos = torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2) + return pos + + def __repr__(self, _repr_indent=4): + head = "Positional encoding " + self.__class__.__name__ + body = [ + "num_pos_feats: {}".format(self.num_pos_feats), + "temperature: {}".format(self.temperature), + "normalize: {}".format(self.normalize), + "scale: {}".format(self.scale), + ] + # _repr_indent = 4 + lines = [head] + [" " * _repr_indent + line for line in body] + return "\n".join(lines) + + +class LearnedSinusoidalPosEmb(nn.Module): + def __init__(self, dim): + super().__init__() + assert (dim % 2) == 0 + half_dim = dim // 2 + self.weights = nn.Parameter(torch.randn(half_dim)) + + def forward(self, x): + x = rearrange(x, "b -> b 1") + freqs = x * rearrange(self.weights, "d -> 1 d") * 2 * pi + fouriered = torch.cat((freqs.sin(), freqs.cos()), dim=-1) + fouriered = torch.cat((x, fouriered), dim=-1) + return fouriered + + +def generate_fourier_features(x, max_freq=64, num_bands=16): + x = x.unsqueeze(-1) + device, dtype, orig_x = x.device, x.dtype, x + + scales = torch.linspace( + -max_freq / 2, max_freq / 2, num_bands, device=device, dtype=dtype + ) + scales = scales[(*((None,) * (len(x.shape) - 1)), Ellipsis)] + + x = x * scales * pi + x = torch.cat([x.sin(), x.cos()], dim=-1) + x = torch.cat((x, orig_x), dim=-1) + return x.flatten(-2) + + +def broadcat(tensors, dim=-1): + num_tensors = len(tensors) + shape_lens = set(list(map(lambda t: len(t.shape), tensors))) + assert len(shape_lens) == 1, "tensors must all have the same number of dimensions" + shape_len = list(shape_lens)[0] + dim = (dim + shape_len) if dim < 0 else dim + dims = list(zip(*map(lambda t: list(t.shape), tensors))) + expandable_dims = [(i, val) for i, val in enumerate(dims) if i != dim] + assert all( + [*map(lambda t: len(set(t[1])) <= 2, expandable_dims)] + ), "invalid dimensions for broadcastable concatentation" + max_dims = list(map(lambda t: (t[0], max(t[1])), expandable_dims)) + expanded_dims = list(map(lambda t: (t[0], (t[1],) * num_tensors), max_dims)) + expanded_dims.insert(dim, (dim, dims[dim])) + expandable_shapes = list(zip(*map(lambda t: t[1], expanded_dims))) + tensors = list(map(lambda t: t[0].expand(*t[1]), zip(tensors, expandable_shapes))) + return torch.cat(tensors, dim=dim) + + +def rotate_half(x): + x = rearrange(x, "... (d r) -> ... d r", r=2) + x1, x2 = x.unbind(dim=-1) + x = torch.stack((-x2, x1), dim=-1) + return rearrange(x, "... d r -> ... (d r)") + + +class VisionRotaryEmbedding(nn.Module): + def __init__( + self, + dim, + pt_seq_len, + ft_seq_len=None, + custom_freqs=None, + freqs_for="lang", + theta=10000, + max_freq=10, + num_freqs=1, + ): + super().__init__() + if custom_freqs: + freqs = custom_freqs + elif freqs_for == "lang": + freqs = 1.0 / ( + theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim) + ) + elif freqs_for == "pixel": + freqs = torch.linspace(1.0, max_freq / 2, dim // 2) * pi + elif freqs_for == "constant": + freqs = torch.ones(num_freqs).float() + else: + raise ValueError(f"unknown modality {freqs_for}") + + if ft_seq_len is None: + ft_seq_len = pt_seq_len + t = torch.arange(ft_seq_len) / ft_seq_len * pt_seq_len + + freqs_h = torch.einsum("..., f -> ... f", t, freqs) + freqs_h = repeat(freqs_h, "... n -> ... (n r)", r=2) + + freqs_w = torch.einsum("..., f -> ... f", t, freqs) + freqs_w = repeat(freqs_w, "... n -> ... (n r)", r=2) + + freqs = broadcat((freqs_h[:, None, :], freqs_w[None, :, :]), dim=-1) + + self.register_buffer("freqs_cos", freqs.cos()) + self.register_buffer("freqs_sin", freqs.sin()) + + print("======== shape of rope freq", self.freqs_cos.shape, "========") + + def forward(self, t, start_index=0): + rot_dim = self.freqs_cos.shape[-1] + end_index = start_index + rot_dim + assert ( + rot_dim <= t.shape[-1] + ), f"feature dimension {t.shape[-1]} is not of sufficient size to rotate in all the positions {rot_dim}" + t_left, t, t_right = ( + t[..., :start_index], + t[..., start_index:end_index], + t[..., end_index:], + ) + t = (t * self.freqs_cos) + (rotate_half(t) * self.freqs_sin) + return torch.cat((t_left, t, t_right), dim=-1) + + +class VisionRotaryEmbeddingFast(nn.Module): + def __init__( + self, + dim, + pt_seq_len, + ft_seq_len=None, + custom_freqs=None, + freqs_for="lang", + theta=10000, + max_freq=10, + num_freqs=1, + ): + super().__init__() + if custom_freqs: + freqs = custom_freqs + elif freqs_for == "lang": + freqs = 1.0 / ( + theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim) + ) + elif freqs_for == "pixel": + freqs = torch.linspace(1.0, max_freq / 2, dim // 2) * pi + elif freqs_for == "constant": + freqs = torch.ones(num_freqs).float() + else: + raise ValueError(f"unknown modality {freqs_for}") + + if ft_seq_len is None: + ft_seq_len = pt_seq_len + t = torch.arange(ft_seq_len) / ft_seq_len * pt_seq_len + + freqs = torch.einsum("..., f -> ... f", t, freqs) + freqs = repeat(freqs, "... n -> ... (n r)", r=2) + freqs = broadcat((freqs[:, None, :], freqs[None, :, :]), dim=-1) + + freqs_cos = freqs.cos().view(-1, freqs.shape[-1]) + freqs_sin = freqs.sin().view(-1, freqs.shape[-1]) + + self.register_buffer("freqs_cos", freqs_cos) + self.register_buffer("freqs_sin", freqs_sin) + + def forward(self, t): + return t * self.freqs_cos + rotate_half(t) * self.freqs_sin diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/layers/upsample.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/layers/upsample.py new file mode 100644 index 0000000000000000000000000000000000000000..786647474e2a5b00e231aae4d371b68d675c4dcf --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/layers/upsample.py @@ -0,0 +1,223 @@ +""" +Author: Luigi Piccinelli +Licensed under the CC-BY NC 4.0 license (http://creativecommons.org/licenses/by-nc/4.0/) +""" + +import torch +import torch.nn as nn +from einops import rearrange + +from .convnext import CvnxtBlock + + +class ConvUpsample(nn.Module): + def __init__( + self, + hidden_dim, + num_layers: int = 2, + expansion: int = 4, + layer_scale: float = 1.0, + kernel_size: int = 7, + **kwargs, + ): + super().__init__() + self.convs = nn.ModuleList([]) + for _ in range(num_layers): + self.convs.append( + CvnxtBlock( + hidden_dim, + kernel_size=kernel_size, + expansion=expansion, + layer_scale=layer_scale, + ) + ) + self.up = nn.Sequential( + nn.Conv2d(hidden_dim, hidden_dim // 2, kernel_size=1, padding=0), + nn.UpsamplingBilinear2d(scale_factor=2), + nn.Conv2d(hidden_dim // 2, hidden_dim // 2, kernel_size=3, padding=1), + ) + + def forward(self, x: torch.Tensor): + for conv in self.convs: + x = conv(x) + x = self.up(x) + x = rearrange(x, "b c h w -> b (h w) c") + return x + + +class ConvUpsampleShuffle(nn.Module): + def __init__( + self, + hidden_dim, + num_layers: int = 2, + expansion: int = 4, + layer_scale: float = 1.0, + kernel_size: int = 7, + **kwargs, + ): + super().__init__() + self.convs = nn.ModuleList([]) + for _ in range(num_layers): + self.convs.append( + CvnxtBlock( + hidden_dim, + kernel_size=kernel_size, + expansion=expansion, + layer_scale=layer_scale, + ) + ) + self.up = nn.Sequential( + nn.PixelShuffle(2), + nn.Conv2d(hidden_dim // 4, hidden_dim // 2, kernel_size=3, padding=1), + ) + + def forward(self, x: torch.Tensor): + for conv in self.convs: + x = conv(x) + x = self.up(x) + x = rearrange(x, "b c h w -> b (h w) c") + return x + + +class ConvUpsampleShuffleResidual(nn.Module): + def __init__( + self, + hidden_dim, + num_layers: int = 2, + expansion: int = 4, + layer_scale: float = 1.0, + kernel_size: int = 7, + padding_mode: str = "zeros", + **kwargs, + ): + super().__init__() + self.convs = nn.ModuleList([]) + for _ in range(num_layers): + self.convs.append( + CvnxtBlock( + hidden_dim, + kernel_size=kernel_size, + expansion=expansion, + layer_scale=layer_scale, + padding_mode=padding_mode, + ) + ) + self.up = nn.Sequential( + nn.PixelShuffle(2), + nn.Conv2d( + hidden_dim // 4, + hidden_dim // 4, + kernel_size=7, + padding=3, + padding_mode=padding_mode, + groups=hidden_dim // 4, + ), + nn.ReLU(), + nn.Conv2d( + hidden_dim // 4, + hidden_dim // 2, + kernel_size=3, + padding=1, + padding_mode=padding_mode, + ), + ) + self.residual = nn.Sequential( + nn.Conv2d(hidden_dim, hidden_dim // 2, kernel_size=1, padding=0), + nn.UpsamplingBilinear2d(scale_factor=2), + ) + + def forward(self, x: torch.Tensor): + for conv in self.convs: + x = conv(x) + x = self.up(x) + self.residual(x) + x = rearrange(x, "b c h w -> b (h w) c") + return x + + +class ResidualConvUnit(nn.Module): + def __init__( + self, + dim, + kernel_size: int = 3, + padding_mode: str = "zeros", + dilation: int = 1, + layer_scale: float = 1.0, + use_norm: bool = False, + ): + super().__init__() + self.conv1 = nn.Conv2d( + dim, + dim, + kernel_size=kernel_size, + padding=dilation * (kernel_size - 1) // 2, + dilation=dilation, + padding_mode=padding_mode, + ) + self.conv2 = nn.Conv2d( + dim, + dim, + kernel_size=kernel_size, + padding=dilation * (kernel_size - 1) // 2, + dilation=dilation, + padding_mode=padding_mode, + ) + self.activation = nn.LeakyReLU() + self.gamma = ( + nn.Parameter(layer_scale * torch.ones(1, dim, 1, 1)) + if layer_scale > 0.0 + else 1.0 + ) + self.norm1 = nn.GroupNorm(dim // 16, dim) if use_norm else nn.Identity() + self.norm2 = nn.GroupNorm(dim // 16, dim) if use_norm else nn.Identity() + + def forward(self, x): + out = self.activation(x) + out = self.conv1(out) + out = self.norm1(out) + out = self.activation(out) + out = self.conv2(out) + out = self.norm2(out) + return self.gamma * out + x + + +class ResUpsampleBil(nn.Module): + def __init__( + self, + hidden_dim, + output_dim: int = None, + num_layers: int = 2, + kernel_size: int = 3, + layer_scale: float = 1.0, + padding_mode: str = "zeros", + use_norm: bool = False, + **kwargs, + ): + super().__init__() + output_dim = output_dim if output_dim is not None else hidden_dim // 2 + self.convs = nn.ModuleList([]) + for _ in range(num_layers): + self.convs.append( + ResidualConvUnit( + hidden_dim, + kernel_size=kernel_size, + layer_scale=layer_scale, + padding_mode=padding_mode, + use_norm=use_norm, + ) + ) + self.up = nn.Sequential( + nn.Conv2d( + hidden_dim, + output_dim, + kernel_size=1, + padding=0, + padding_mode=padding_mode, + ), + nn.Upsample(scale_factor=2, mode="bilinear", align_corners=False), + ) + + def forward(self, x: torch.Tensor): + for conv in self.convs: + x = conv(x) + x = self.up(x) + return x diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/__init__.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..01e1784651cf2bbc77fcb298991c166ce68e4b55 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/__init__.py @@ -0,0 +1,8 @@ +from .unidepthv1 import UniDepthV1 +from .unidepthv2 import UniDepthV2, UniDepthV2old + +__all__ = [ + "UniDepthV1", + "UniDepthV2old", + "UniDepthV2", +] diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/backbones/__init__.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/backbones/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d443b3faa2d658af6ae95d6600650c3c876ec605 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/backbones/__init__.py @@ -0,0 +1,9 @@ +from .convnext import ConvNeXt +from .convnext2 import ConvNeXtV2 +from .dinov2 import _make_dinov2_model + +__all__ = [ + "ConvNeXt", + "ConvNeXtV2", + "_make_dinov2_model", +] diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/backbones/convnext.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/backbones/convnext.py new file mode 100644 index 0000000000000000000000000000000000000000..11b89a94ac66de221671f078ee785eb92f727040 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/backbones/convnext.py @@ -0,0 +1,580 @@ +from collections import OrderedDict +from functools import partial +from typing import Callable, Optional, Sequence, Tuple, Union + +import torch +import torch.nn as nn +from timm.layers import (AvgPool2dSame, DropPath, GlobalResponseNormMlp, + LayerNorm, LayerNorm2d, Mlp, create_conv2d, + get_act_layer, make_divisible, to_ntuple, + trunc_normal_) +from torch.utils.checkpoint import checkpoint + + +def get_num_layer_for_convnext(var_name): + """ + Divide [3, 3, 27, 3] layers into 12 groups; each group is three + consecutive blocks, including possible neighboring downsample layers; + adapted from https://github.com/microsoft/unilm/blob/master/beit/optim_factory.py + """ + if var_name.startswith("downsample_layers"): + stage_id = int(var_name.split(".")[1]) + if stage_id == 0: + layer_id = 0 + elif stage_id == 1 or stage_id == 2: + layer_id = stage_id + 1 + elif stage_id == 3: + layer_id = 12 + + elif var_name.startswith("stages"): + stage_id = int(var_name.split(".")[1]) + block_id = int(var_name.split(".")[3]) + if stage_id == 0 or stage_id == 1: + layer_id = stage_id + 1 + elif stage_id == 2: + layer_id = 3 + block_id // 3 + elif stage_id == 3: + layer_id = 12 + + elif var_name.startswith("stem"): + return 0 + else: + layer_id = 12 + return layer_id + 1 + + +def get_parameter_groups(model, lr, wd=1e-5, ld=0.9, skip_list=None): + parameter_group_names = {} + parameter_group_vars = {} + skip = set() + if skip_list is not None: + skip = skip_list + if hasattr(model, "no_weight_decay"): + skip.update(model.no_weight_decay()) + num_layers = 12 + layer_scale = list(ld ** (num_layers + 1 - i) for i in range(num_layers + 2)) + for name, param in model.named_parameters(): + if not param.requires_grad: + continue # frozen weights + if len(param.shape) == 1 or name.endswith(".bias") or name in skip: + group_name = "no_decay" + this_wd = 0.0 + else: + group_name = "decay" + this_wd = wd + + layer_id = get_num_layer_for_convnext(name) + group_name = "layer_%d_%s" % (layer_id, group_name) + + if group_name not in parameter_group_names: + scale = layer_scale[layer_id] + cur_lr = lr * scale + + parameter_group_names[group_name] = { + "weight_decay": this_wd, + "weight_decay_init": this_wd, + "weight_decay_base": this_wd, + "params": [], + "lr_init": cur_lr, + "lr_base": lr, + "lr": cur_lr, + } + parameter_group_vars[group_name] = { + "weight_decay": this_wd, + "weight_decay_init": this_wd, + "weight_decay_base": this_wd, + "params": [], + "lr_init": cur_lr, + "lr_base": lr, + "lr": cur_lr, + } + if this_wd == 0.0: + parameter_group_names[group_name]["weight_decay_final"] = 0.0 + parameter_group_vars[group_name]["weight_decay_final"] = 0.0 + parameter_group_vars[group_name]["params"].append(param) + parameter_group_names[group_name]["params"].append(name) + # from unidepth.utils import is_main_process + # import json + # if is_main_process(): + # print("Param groups = %s" % json.dumps(parameter_group_names, indent=2)) + return list(parameter_group_vars.values()), [ + v["lr"] for k, v in parameter_group_vars.items() + ] + + +class Downsample(nn.Module): + def __init__(self, in_chs, out_chs, stride=1, dilation=1): + super().__init__() + avg_stride = stride if dilation == 1 else 1 + if stride > 1 or dilation > 1: + avg_pool_fn = ( + AvgPool2dSame if avg_stride == 1 and dilation > 1 else nn.AvgPool2d + ) + self.pool = avg_pool_fn( + 2, avg_stride, ceil_mode=True, count_include_pad=False + ) + else: + self.pool = nn.Identity() + + if in_chs != out_chs: + self.conv = create_conv2d(in_chs, out_chs, 1, stride=1) + else: + self.conv = nn.Identity() + + def forward(self, x): + x = self.pool(x) + x = self.conv(x) + return x + + +class ConvNeXtBlock(nn.Module): + """ConvNeXt Block + There are two equivalent implementations: + (1) DwConv -> LayerNorm (channels_first) -> 1x1 Conv -> GELU -> 1x1 Conv; all in (N, C, H, W) + (2) DwConv -> Permute to (N, H, W, C); LayerNorm (channels_last) -> Linear -> GELU -> Linear; Permute back + + Unlike the official impl, this one allows choice of 1 or 2, 1x1 conv can be faster with appropriate + choice of LayerNorm impl, however as model size increases the tradeoffs appear to change and nn.Linear + is a better choice. This was observed with PyTorch 1.10 on 3090 GPU, it could change over time & w/ different HW. + """ + + def __init__( + self, + in_chs: int, + out_chs: Optional[int] = None, + kernel_size: int = 7, + stride: int = 1, + dilation: Union[int, Tuple[int, int]] = (1, 1), + mlp_ratio: float = 4, + conv_mlp: bool = False, + conv_bias: bool = True, + use_grn: bool = False, + ls_init_value: Optional[float] = 1e-6, + act_layer: Union[str, Callable] = "gelu", + norm_layer: Optional[Callable] = None, + drop_path: float = 0.0, + ): + """ + + Args: + in_chs: Block input channels. + out_chs: Block output channels (same as in_chs if None). + kernel_size: Depthwise convolution kernel size. + stride: Stride of depthwise convolution. + dilation: Tuple specifying input and output dilation of block. + mlp_ratio: MLP expansion ratio. + conv_mlp: Use 1x1 convolutions for MLP and a NCHW compatible norm layer if True. + conv_bias: Apply bias for all convolution (linear) layers. + use_grn: Use GlobalResponseNorm in MLP (from ConvNeXt-V2) + ls_init_value: Layer-scale init values, layer-scale applied if not None. + act_layer: Activation layer. + norm_layer: Normalization layer (defaults to LN if not specified). + drop_path: Stochastic depth probability. + """ + super().__init__() + out_chs = out_chs or in_chs + dilation = to_ntuple(2)(dilation) + act_layer = get_act_layer(act_layer) + if not norm_layer: + norm_layer = LayerNorm2d if conv_mlp else LayerNorm + mlp_layer = partial( + GlobalResponseNormMlp if use_grn else Mlp, use_conv=conv_mlp + ) + self.use_conv_mlp = conv_mlp + self.conv_dw = create_conv2d( + in_chs, + out_chs, + kernel_size=kernel_size, + stride=stride, + dilation=dilation[0], + depthwise=True, + bias=conv_bias, + ) + self.norm = norm_layer(out_chs) + self.mlp = mlp_layer(out_chs, int(mlp_ratio * out_chs), act_layer=act_layer) + self.gamma = ( + nn.Parameter(ls_init_value * torch.ones(out_chs)) + if ls_init_value is not None + else None + ) + if in_chs != out_chs or stride != 1 or dilation[0] != dilation[1]: + self.shortcut = Downsample( + in_chs, out_chs, stride=stride, dilation=dilation[0] + ) + else: + self.shortcut = nn.Identity() + self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity() + + def forward(self, x): + shortcut = x + x = self.conv_dw(x.contiguous()) + if self.use_conv_mlp: + x = self.norm(x) + x = self.mlp(x) + else: + x = x.permute(0, 2, 3, 1).contiguous() + x = self.norm(x) + x = self.mlp(x) + x = x.permute(0, 3, 1, 2).contiguous() + if self.gamma is not None: + x = x.mul(self.gamma.reshape(1, -1, 1, 1)) + + x = self.drop_path(x) + self.shortcut(shortcut) + return x.contiguous() + + +class ConvNeXtStage(nn.Module): + def __init__( + self, + in_chs, + out_chs, + kernel_size=7, + stride=2, + depth=2, + dilation=(1, 1), + drop_path_rates=None, + ls_init_value=1.0, + conv_mlp=False, + conv_bias=True, + use_grn=False, + act_layer="gelu", + norm_layer=None, + norm_layer_cl=None, + ): + super().__init__() + self.grad_checkpointing = False + + if in_chs != out_chs or stride > 1 or dilation[0] != dilation[1]: + ds_ks = 2 if stride > 1 or dilation[0] != dilation[1] else 1 + pad = ( + "same" if dilation[1] > 1 else 0 + ) # same padding needed if dilation used + self.downsample = nn.Sequential( + norm_layer(in_chs), + create_conv2d( + in_chs, + out_chs, + kernel_size=ds_ks, + stride=stride, + dilation=dilation[0], + padding=pad, + bias=conv_bias, + ), + ) + in_chs = out_chs + else: + self.downsample = nn.Identity() + + drop_path_rates = drop_path_rates or [0.0] * depth + stage_blocks = [] + for i in range(depth): + stage_blocks.append( + ConvNeXtBlock( + in_chs=in_chs, + out_chs=out_chs, + kernel_size=kernel_size, + dilation=dilation[1], + drop_path=drop_path_rates[i], + ls_init_value=ls_init_value, + conv_mlp=conv_mlp, + conv_bias=conv_bias, + use_grn=use_grn, + act_layer=act_layer, + norm_layer=norm_layer if conv_mlp else norm_layer_cl, + ) + ) + in_chs = out_chs + self.blocks = nn.ModuleList(stage_blocks) + + def forward(self, x): + xs = [] + x = self.downsample(x) + for block in self.blocks: + if self.grad_checkpointing: + x = checkpoint(block, x) + else: + x = block(x) + xs.append(x) + return xs + + +class ConvNeXt(nn.Module): + def __init__( + self, + in_chans: int = 3, + output_stride: int = 32, + depths: Tuple[int, ...] = (3, 3, 9, 3), + dims: Tuple[int, ...] = (96, 192, 384, 768), + kernel_sizes: Union[int, Tuple[int, ...]] = 7, + ls_init_value: Optional[float] = 1e-6, + stem_type: str = "patch", + patch_size: int = 4, + conv_mlp: bool = False, + conv_bias: bool = True, + use_grn: bool = False, + act_layer: Union[str, Callable] = "gelu", + norm_layer: Optional[Union[str, Callable]] = None, + norm_eps: Optional[float] = None, + drop_path_rate: float = 0.0, + output_idx=[], + use_checkpoint=False, + ): + """ + Args: + in_chans: Number of input image channels. + num_classes: Number of classes for classification head. + global_pool: Global pooling type. + output_stride: Output stride of network, one of (8, 16, 32). + depths: Number of blocks at each stage. + dims: Feature dimension at each stage. + kernel_sizes: Depthwise convolution kernel-sizes for each stage. + ls_init_value: Init value for Layer Scale, disabled if None. + stem_type: Type of stem. + patch_size: Stem patch size for patch stem. + head_init_scale: Init scaling value for classifier weights and biases. + head_norm_first: Apply normalization before global pool + head. + head_hidden_size: Size of MLP hidden layer in head if not None and head_norm_first == False. + conv_mlp: Use 1x1 conv in MLP, improves speed for small networks w/ chan last. + conv_bias: Use bias layers w/ all convolutions. + use_grn: Use Global Response Norm (ConvNeXt-V2) in MLP. + act_layer: Activation layer type. + norm_layer: Normalization layer type. + drop_rate: Head pre-classifier dropout rate. + drop_path_rate: Stochastic depth drop rate. + """ + super().__init__() + self.num_layers = len(depths) + self.depths = output_idx + self.embed_dims = [ + int(dim) for i, dim in enumerate(dims) for _ in range(depths[i]) + ] + self.embed_dim = dims[0] + + assert output_stride in (8, 16, 32) + kernel_sizes = to_ntuple(4)(kernel_sizes) + if norm_layer is None: + norm_layer = LayerNorm2d + norm_layer_cl = norm_layer if conv_mlp else LayerNorm + if norm_eps is not None: + norm_layer = partial(norm_layer, eps=norm_eps) + norm_layer_cl = partial(norm_layer_cl, eps=norm_eps) + else: + assert ( + conv_mlp + ), "If a norm_layer is specified, conv MLP must be used so all norm expect rank-4, channels-first input" + norm_layer_cl = norm_layer + if norm_eps is not None: + norm_layer_cl = partial(norm_layer_cl, eps=norm_eps) + + self.feature_info = [] + + assert stem_type in ("patch", "overlap", "overlap_tiered") + if stem_type == "patch": + # NOTE: this stem is a minimal form of ViT PatchEmbed, as used in SwinTransformer w/ patch_size = 4 + self.stem = nn.Sequential( + nn.Conv2d( + in_chans, + dims[0], + kernel_size=patch_size, + stride=patch_size, + bias=conv_bias, + ), + norm_layer(dims[0]), + ) + stem_stride = patch_size + else: + mid_chs = make_divisible(dims[0] // 2) if "tiered" in stem_type else dims[0] + self.stem = nn.Sequential( + nn.Conv2d( + in_chans, + mid_chs, + kernel_size=3, + stride=2, + padding=1, + bias=conv_bias, + ), + nn.Conv2d( + mid_chs, dims[0], kernel_size=3, stride=2, padding=1, bias=conv_bias + ), + norm_layer(dims[0]), + ) + stem_stride = 4 + + self.stages = nn.Sequential() + dp_rates = [ + x.tolist() + for x in torch.linspace(0, drop_path_rate, sum(depths)).split(depths) + ] + stages = [] + prev_chs = dims[0] + curr_stride = stem_stride + dilation = 1 + # 4 feature resolution stages, each consisting of multiple residual blocks + for i in range(4): + stride = 2 if curr_stride == 2 or i > 0 else 1 + if curr_stride >= output_stride and stride > 1: + dilation *= stride + stride = 1 + curr_stride *= stride + first_dilation = 1 if dilation in (1, 2) else 2 + out_chs = dims[i] + stages.append( + ConvNeXtStage( + prev_chs, + out_chs, + kernel_size=kernel_sizes[i], + stride=stride, + dilation=(first_dilation, dilation), + depth=depths[i], + drop_path_rates=dp_rates[i], + ls_init_value=ls_init_value, + conv_mlp=conv_mlp, + conv_bias=conv_bias, + use_grn=use_grn, + act_layer=act_layer, + norm_layer=norm_layer, + norm_layer_cl=norm_layer_cl, + ) + ) + prev_chs = out_chs + # NOTE feature_info use currently assumes stage 0 == stride 1, rest are stride 2 + self.feature_info += [ + dict(num_chs=prev_chs, reduction=curr_stride, module=f"stages.{i}") + ] + self.stages = nn.ModuleList(stages) + self.mask_token = nn.Parameter(torch.zeros(1, self.embed_dim, 1, 1)) + self.num_features = prev_chs + self.apply(self._init_weights) + self.set_grad_checkpointing(use_checkpoint) + + def _init_weights(self, module): + if isinstance(module, nn.Conv2d): + trunc_normal_(module.weight, std=0.02) + if module.bias is not None: + nn.init.zeros_(module.bias) + elif isinstance(module, nn.Linear): + trunc_normal_(module.weight, std=0.02) + nn.init.zeros_(module.bias) + + def forward(self, x, masks=None): + outs = [] + x = self.stem(x) + if masks is not None: + masks = torch.nn.functional.interpolate( + masks.float(), size=x.shape[-2:], mode="nearest" + ) + x = torch.where(masks.bool(), self.mask_token.to(x.dtype), x).contiguous() + for stage in self.stages: + xs = stage(x) + outs.extend([x.permute(0, 2, 3, 1).contiguous() for x in xs]) + x = xs[-1] + return outs, [x.mean(dim=(1, 2)).unsqueeze(1).contiguous() for x in outs] + + @torch.jit.ignore + def group_matcher(self, coarse=False): + return dict( + stem=r"^stem", + blocks=( + r"^stages\.(\d+)" + if coarse + else [ + (r"^stages\.(\d+)\.downsample", (0,)), # blocks + (r"^stages\.(\d+)\.blocks\.(\d+)", None), + (r"^norm_pre", (99999,)), + ] + ), + ) + + @torch.jit.ignore + def set_grad_checkpointing(self, enable=True): + for s in self.stages: + s.grad_checkpointing = enable + + def freeze(self) -> None: + for module in self.modules(): + module.eval() + for parameters in self.parameters(): + parameters.requires_grad = False + + def get_params(self, lr, wd, ld, *args, **kwargs): + encoder_p, encoder_lr = get_parameter_groups(self, lr, wd, ld) + return encoder_p, encoder_lr + + def no_weight_decay(self): + return {"mask_token"} + + @classmethod + def build(cls, config): + obj = globals()[config["model"]["encoder"]["name"]](config) + return obj + + +def checkpoint_filter_fn(state_dict, model): + """Remap FB checkpoints -> timm""" + if "head.norm.weight" in state_dict or "norm_pre.weight" in state_dict: + return state_dict # non-FB checkpoint + if "model" in state_dict: + state_dict = state_dict["model"] + + out_dict = {} + if "visual.trunk.stem.0.weight" in state_dict: + out_dict = { + k.replace("visual.trunk.", ""): v + for k, v in state_dict.items() + if k.startswith("visual.trunk.") + } + if "visual.head.proj.weight" in state_dict: + out_dict["head.fc.weight"] = state_dict["visual.head.proj.weight"] + out_dict["head.fc.bias"] = torch.zeros( + state_dict["visual.head.proj.weight"].shape[0] + ) + elif "visual.head.mlp.fc1.weight" in state_dict: + out_dict["head.pre_logits.fc.weight"] = state_dict[ + "visual.head.mlp.fc1.weight" + ] + out_dict["head.pre_logits.fc.bias"] = state_dict["visual.head.mlp.fc1.bias"] + out_dict["head.fc.weight"] = state_dict["visual.head.mlp.fc2.weight"] + out_dict["head.fc.bias"] = torch.zeros( + state_dict["visual.head.mlp.fc2.weight"].shape[0] + ) + return out_dict + + import re + + for k, v in state_dict.items(): + k = k.replace("downsample_layers.0.", "stem.") + k = re.sub(r"stages.([0-9]+).([0-9]+)", r"stages.\1.blocks.\2", k) + k = re.sub( + r"downsample_layers.([0-9]+).([0-9]+)", r"stages.\1.downsample.\2", k + ) + k = k.replace("dwconv", "conv_dw") + k = k.replace("pwconv", "mlp.fc") + if "grn" in k: + k = k.replace("grn.beta", "mlp.grn.bias") + k = k.replace("grn.gamma", "mlp.grn.weight") + v = v.reshape(v.shape[-1]) + k = k.replace("head.", "head.fc.") + if k.startswith("norm."): + k = k.replace("norm", "head.norm") + if v.ndim == 2 and "head" not in k: + model_shape = model.state_dict()[k].shape + v = v.reshape(model_shape) + out_dict[k] = v + + return out_dict + + +HF_URL = { + "convnext_xxlarge_pt": ( + "laion/CLIP-convnext_xxlarge-laion2B-s34B-b82K-augreg-soup", + "open_clip_pytorch_model.bin", + ), + "convnext_large_pt": ( + "laion/CLIP-convnext_large_d_320.laion2B-s29B-b131K-ft-soup", + "open_clip_pytorch_model.bin", + ), + "convnext_large": ( + "timm/convnext_large_mlp.clip_laion2b_soup_ft_in12k_in1k_384", + "pytorch_model.bin", + ), +} diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/backbones/convnext2.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/backbones/convnext2.py new file mode 100644 index 0000000000000000000000000000000000000000..74d5bbf12bf586552ef35e2e82d59e47b9c9cc42 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/backbones/convnext2.py @@ -0,0 +1,288 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F +from timm.models.layers import DropPath, trunc_normal_ + + +def get_num_layer_for_convnext_single(var_name, depths): + """ + Each layer is assigned distinctive layer ids + """ + if var_name.startswith("downsample_layers"): + stage_id = int(var_name.split(".")[1]) + layer_id = sum(depths[:stage_id]) + 1 + return layer_id + + elif var_name.startswith("stages"): + stage_id = int(var_name.split(".")[1]) + block_id = int(var_name.split(".")[2]) + layer_id = sum(depths[:stage_id]) + block_id + 1 + return layer_id + + else: + return sum(depths) + 1 + + +def get_num_layer_for_convnext(var_name): + """ + Divide [3, 3, 27, 3] layers into 12 groups; each group is three + consecutive blocks, including possible neighboring downsample layers; + adapted from https://github.com/microsoft/unilm/blob/master/beit/optim_factory.py + """ + num_max_layer = 12 + if var_name.startswith("downsample_layers"): + stage_id = int(var_name.split(".")[1]) + if stage_id == 0: + layer_id = 0 + elif stage_id == 1 or stage_id == 2: + layer_id = stage_id + 1 + elif stage_id == 3: + layer_id = 12 + return layer_id + + elif var_name.startswith("stages"): + stage_id = int(var_name.split(".")[1]) + block_id = int(var_name.split(".")[2]) + if stage_id == 0 or stage_id == 1: + layer_id = stage_id + 1 + elif stage_id == 2: + layer_id = 3 + block_id // 3 + elif stage_id == 3: + layer_id = 12 + return layer_id + else: + return num_max_layer + 1 + + +def get_parameter_groups(model, lr, wd=1e-5, ld=0.9, skip_list=()): + parameter_group_names = {} + parameter_group_vars = {} + skip = {} + if skip_list is not None: + skip = skip_list + elif hasattr(model, "no_weight_decay"): + skip = model.no_weight_decay() + num_layers = 12 # sum(model.depths) + layer_scale = list(ld ** (num_layers + 1 - i) for i in range(num_layers + 2)) + for name, param in model.named_parameters(): + if not param.requires_grad: + continue # frozen weights + if ( + len(param.shape) == 1 + or name.endswith(".bias") + or name in skip + or name.endswith(".gamma") + or name.endswith(".beta") + ): + group_name = "no_decay" + this_weight_decay = 0.0 + else: + group_name = "decay" + this_weight_decay = wd + + # layer_id = get_num_layer_for_convnext_single(name, model.depths) + layer_id = get_num_layer_for_convnext(name) + group_name = "layer_%d_%s" % (layer_id, group_name) + + if group_name not in parameter_group_names: + scale = layer_scale[layer_id] + cur_lr = lr * scale + + parameter_group_names[group_name] = { + "weight_decay": this_weight_decay, + "params": [], + "lr_scale": scale, + "lr": cur_lr, + } + parameter_group_vars[group_name] = { + "weight_decay": this_weight_decay, + "params": [], + "lr_scale": scale, + "lr": cur_lr, + } + parameter_group_vars[group_name]["params"].append(param) + parameter_group_names[group_name]["params"].append(name) + # if is_main_process(): + # print("Param groups = %s" % json.dumps(parameter_group_names, indent=2)) + return list(parameter_group_vars.values()), [ + v["lr"] for k, v in parameter_group_vars.items() + ] + + +class LayerNorm(nn.Module): + """LayerNorm that supports two data formats: channels_last (default) or channels_first. + The ordering of the dimensions in the inputs. channels_last corresponds to inputs with + shape (batch_size, height, width, channels) while channels_first corresponds to inputs + with shape (batch_size, channels, height, width). + """ + + def __init__(self, normalized_shape, eps=1e-6, data_format="channels_last"): + super().__init__() + self.weight = nn.Parameter(torch.ones(normalized_shape)) + self.bias = nn.Parameter(torch.zeros(normalized_shape)) + self.eps = eps + self.data_format = data_format + if self.data_format not in ["channels_last", "channels_first"]: + raise NotImplementedError + self.normalized_shape = (normalized_shape,) + + def forward(self, x): + if self.data_format == "channels_last": + return F.layer_norm( + x, self.normalized_shape, self.weight, self.bias, self.eps + ) + elif self.data_format == "channels_first": + u = x.mean(1, keepdim=True) + s = (x - u).pow(2).mean(1, keepdim=True) + x = (x - u) / torch.sqrt(s + self.eps) + x = self.weight[:, None, None] * x + self.bias[:, None, None] + return x + + +class GRN(nn.Module): + """GRN (Global Response Normalization) layer""" + + def __init__(self, dim): + super().__init__() + self.gamma = nn.Parameter(torch.zeros(1, 1, 1, dim)) + self.beta = nn.Parameter(torch.zeros(1, 1, 1, dim)) + + def forward(self, x): + Gx = torch.norm(x, p=2, dim=(1, 2), keepdim=True) + Nx = Gx / (Gx.mean(dim=-1, keepdim=True) + 1e-6) + return self.gamma * (x * Nx) + self.beta + x + + +class Block(nn.Module): + """ConvNeXtV2 Block. + + Args: + dim (int): Number of input channels. + drop_path (float): Stochastic depth rate. Default: 0.0 + """ + + def __init__(self, dim, drop_path=0.0, mult=4, use_checkpoint=False): + super().__init__() + self.dwconv = nn.Conv2d( + dim, dim, kernel_size=7, padding=3, groups=dim + ) # depthwise conv + self.norm = LayerNorm(dim, eps=1e-6) + self.pwconv1 = nn.Linear( + dim, mult * dim + ) # pointwise/1x1 convs, implemented with linear layers + self.act = nn.GELU() + self.grn = GRN(mult * dim) + self.pwconv2 = nn.Linear(mult * dim, dim) + self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity() + self.use_checkpoint = use_checkpoint + + def forward(self, x): + input = x + x = self.dwconv(x) + x = x.permute(0, 2, 3, 1) # (N, C, H, W) -> (N, H, W, C) + x = self.norm(x) + x = self.pwconv1(x) + x = self.act(x) + x = self.grn(x) + x = self.pwconv2(x) + x = x.permute(0, 3, 1, 2) # (N, H, W, C) -> (N, C, H, W) + + x = input + self.drop_path(x) + return x + + +class ConvNeXtV2(nn.Module): + """ConvNeXt V2 + + Args: + in_chans (int): Number of input image channels. Default: 3 + num_classes (int): Number of classes for classification head. Default: 1000 + depths (tuple(int)): Number of blocks at each stage. Default: [3, 3, 9, 3] + dims (int): Feature dimension at each stage. Default: [96, 192, 384, 768] + drop_path_rate (float): Stochastic depth rate. Default: 0. + head_init_scale (float): Init scaling value for classifier weights and biases. Default: 1. + """ + + def __init__( + self, + in_chans=3, + depths=[3, 3, 9, 3], + dims=96, + drop_path_rate=0.0, + output_idx=[], + use_checkpoint=False, + ): + super().__init__() + self.num_layers = len(depths) + self.depths = output_idx + self.embed_dims = [ + int(dim) for i, dim in enumerate(dims) for _ in range(depths[i]) + ] + self.embed_dim = dims[0] + + self.downsample_layers = ( + nn.ModuleList() + ) # stem and 3 intermediate downsampling conv layers + stem = nn.Sequential( + nn.Conv2d(in_chans, dims[0], kernel_size=4, stride=4), + LayerNorm(dims[0], eps=1e-6, data_format="channels_first"), + ) + self.downsample_layers.append(stem) + for i in range(3): + downsample_layer = nn.Sequential( + LayerNorm(dims[i], eps=1e-6, data_format="channels_first"), + nn.Conv2d(dims[i], dims[i + 1], kernel_size=2, stride=2), + ) + self.downsample_layers.append(downsample_layer) + + self.stages = ( + nn.ModuleList() + ) # 4 feature resolution stages, each consisting of multiple residual blocks + self.out_norms = nn.ModuleList() + dp_rates = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] + cur = 0 + for i in range(4): + stage = nn.ModuleList( + [ + Block( + dim=dims[i], + drop_path=dp_rates[cur + j], + use_checkpoint=use_checkpoint, + ) + for j in range(depths[i]) + ] + ) + self.stages.append(stage) + cur += depths[i] + + self.apply(self._init_weights) + + def _init_weights(self, m): + if isinstance(m, (nn.Conv2d, nn.Linear)): + trunc_normal_(m.weight, std=0.02) + nn.init.constant_(m.bias, 0) + + def forward(self, x): + outs = [] + for i in range(4): + x = self.downsample_layers[i](x) + for stage in self.stages[i]: + x = stage(x) + outs.append(x.permute(0, 2, 3, 1)) + cls_tokens = [x.mean(dim=(1, 2)).unsqueeze(1).contiguous() for x in outs] + return outs, cls_tokens + + def get_params(self, lr, wd, ld, *args, **kwargs): + encoder_p, encoder_lr = get_parameter_groups(self, lr, wd, ld) + return encoder_p, encoder_lr + + def freeze(self) -> None: + for module in self.modules(): + module.eval() + for parameters in self.parameters(): + parameters.requires_grad = False + + @classmethod + def build(cls, config): + obj = globals()[config["model"]["encoder"]["name"]](config) + return obj diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/backbones/dinov2.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/backbones/dinov2.py new file mode 100644 index 0000000000000000000000000000000000000000..d394ebbb80b54ba9ee6cf779d91d89209dd23191 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/backbones/dinov2.py @@ -0,0 +1,486 @@ +import contextlib +import logging +import math +from functools import partial +from typing import Callable, Sequence + +import torch +import torch.nn as nn +from torch.nn.init import trunc_normal_ + +from .metadinov2 import Attention, MemEffAttention, Mlp +from .metadinov2 import NestedTensorBlock as Block +from .metadinov2 import PatchEmbed, SwiGLUFFNFused + +_DINOV2_BASE_URL = "https://dl.fbaipublicfiles.com/dinov2" +logger = logging.getLogger("dinov2") + + +def named_apply( + fn: Callable, module: nn.Module, name="", depth_first=True, include_root=False +) -> nn.Module: + if not depth_first and include_root: + fn(module=module, name=name) + for child_name, child_module in module.named_children(): + child_name = ".".join((name, child_name)) if name else child_name + named_apply( + fn=fn, + module=child_module, + name=child_name, + depth_first=depth_first, + include_root=True, + ) + if depth_first and include_root: + fn(module=module, name=name) + return module + + +def get_parameter_groups(model, lr, wd=1e-5, ld=0.9, skip_list=()): + parameter_group_names = {} + parameter_group_vars = {} + skip = {} + if skip_list is not None: + skip = skip_list + elif hasattr(model, "no_weight_decay"): + skip = model.no_weight_decay() + + num_layers = model.n_blocks + layer_scale = list(ld ** (num_layers - i) for i in range(num_layers)) + + for name, param in model.named_parameters(): + if not param.requires_grad: + continue + + if len(param.shape) == 1: # norm + group_name = "no_decay" + this_wd = 0.0 + # layer scale, bias beta? + elif ( + name in skip + or name.endswith(".gamma") + or name.endswith(".beta") + or name.endswith(".bias") + ): + group_name = "no_decay" + this_wd = 0.0 + elif "cls_token" in name or "pos_embed" in name or "mask_token" in name: + group_name = "no_decay" + this_wd = 0.0 + else: + group_name = "decay" + this_wd = wd + + if name.startswith("blocks"): + layer_id = int(name.split(".")[1]) + elif name.startswith("patch_embed"): + layer_id = 0 + else: + layer_id = 0 + + group_name = f"layer_{layer_id}_{group_name}" + + if group_name not in parameter_group_names: + scale = layer_scale[layer_id] + cur_lr = lr * scale + + parameter_group_names[group_name] = { + "weight_decay": this_wd, + "params": [], + "lr_init": cur_lr, + "lr_base": lr, + "lr": cur_lr, + } + parameter_group_vars[group_name] = { + "weight_decay": this_wd, + "params": [], + "lr_init": cur_lr, + "lr_base": lr, + "lr": cur_lr, + } + parameter_group_vars[group_name]["params"].append(param) + parameter_group_names[group_name]["params"].append(name) + + return list(parameter_group_vars.values()), [ + v["lr"] for k, v in parameter_group_vars.items() + ] + + +class BlockChunk(nn.ModuleList): + def forward(self, x): + for b in self: + x = b(x) + return x + + +class DinoVisionTransformer(nn.Module): + def __init__( + self, + img_size=224, + patch_size=16, + in_chans=3, + embed_dim=768, + depth=12, + num_heads=12, + mlp_ratio=4.0, + qkv_bias=True, + ffn_bias=True, + proj_bias=True, + drop_path_rate=0.0, + drop_path_uniform=False, + init_values=None, # for layerscale: None or 0 => no layerscale + embed_layer=PatchEmbed, + act_layer=nn.GELU, + block_fn=Block, + ffn_layer="mlp", + block_chunks=1, + output_idx=[5, 12, 18, 24], + checkpoint: bool = False, + num_register_tokens=0, + interpolate_antialias=False, + interpolate_offset=0.0, + use_norm=False, + frozen_stages=0, + ): + """ + Args: + img_size (int, tuple): input image size + patch_size (int, tuple): patch size + in_chans (int): number of input channels + embed_dim (int): embedding dimension + depth (int): depth of transformer + num_heads (int): number of attention heads + mlp_ratio (int): ratio of mlp hidden dim to embedding dim + qkv_bias (bool): enable bias for qkv if True + proj_bias (bool): enable bias for proj in attn if True + ffn_bias (bool): enable bias for ffn if True + drop_path_rate (float): stochastic depth rate + drop_path_uniform (bool): apply uniform drop rate across blocks + weight_init (str): weight init scheme + init_values (float): layer-scale init values + embed_layer (nn.Module): patch embedding layer + act_layer (nn.Module): MLP activation layer + block_fn (nn.Module): transformer block class + ffn_layer (str): "mlp", "swiglu", "swiglufused" or "identity" + block_chunks: (int) split block sequence into block_chunks units for FSDP wrap + """ + super().__init__() + norm_layer = partial(nn.LayerNorm, eps=1e-6) + + self.num_features = self.embed_dim = ( + embed_dim # num_features for consistency with other models + ) + self.frozen_stages = frozen_stages + self.embed_dims = [embed_dim] * output_idx[-1] + self.num_tokens = 1 + self.n_blocks = depth + self.num_heads = num_heads + self.patch_size = patch_size + self.depths = output_idx + self.checkpoint = checkpoint + self.num_register_tokens = num_register_tokens + self.interpolate_antialias = interpolate_antialias + self.interpolate_offset = interpolate_offset + + self.patch_embed = embed_layer( + img_size=img_size, + patch_size=patch_size, + in_chans=in_chans, + embed_dim=embed_dim, + ) + num_patches = self.patch_embed.num_patches + + self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) + self.pos_embed = nn.Parameter( + torch.zeros(1, num_patches + self.num_tokens, embed_dim) + ) + assert num_register_tokens >= 0 + self.register_tokens = nn.Parameter( + torch.zeros(1, max(1, num_register_tokens), embed_dim) + ) + + if drop_path_uniform is True: + dpr = [drop_path_rate] * depth + else: + dpr = [ + x.item() for x in torch.linspace(0, drop_path_rate, depth) + ] # stochastic depth decay rule + + if ffn_layer == "mlp": + logger.info("using MLP layer as FFN") + ffn_layer = Mlp + elif ffn_layer == "swiglufused" or ffn_layer == "swiglu": + logger.info("using SwiGLU layer as FFN") + ffn_layer = SwiGLUFFNFused + elif ffn_layer == "identity": + logger.info("using Identity layer as FFN") + + def f(*args, **kwargs): + return nn.Identity() + + ffn_layer = f + else: + raise NotImplementedError + + blocks_list = [ + block_fn( + dim=embed_dim, + num_heads=num_heads, + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + proj_bias=proj_bias, + ffn_bias=ffn_bias, + drop_path=dpr[i], + norm_layer=norm_layer, + act_layer=act_layer, + ffn_layer=ffn_layer, + init_values=init_values, + ) + for i in range(depth) + ] + if block_chunks > 0: + self.chunked_blocks = True + chunked_blocks = [] + chunksize = depth // block_chunks + for i in range(0, depth, chunksize): + # this is to keep the block index consistent if we chunk the block list + chunked_blocks.append( + [nn.Identity()] * i + blocks_list[i : i + chunksize] + ) + self.blocks = nn.ModuleList([BlockChunk(p) for p in chunked_blocks]) + else: + self.chunked_blocks = False + self.blocks = nn.ModuleList(blocks_list) + + self.norm = nn.LayerNorm(embed_dim) + self.use_norm = use_norm + self.head = nn.Identity() + self.mask_token = nn.Parameter(torch.zeros(1, embed_dim)) + self.init_weights() + + def init_weights(self): + trunc_normal_(self.pos_embed, std=0.02) + nn.init.normal_(self.cls_token, std=1e-6) + if self.num_register_tokens: + nn.init.normal_(self.register_tokens, std=1e-6) + named_apply(init_weights_vit_timm, self) + + def interpolate_pos_encoding(self, x, w, h): + previous_dtype = x.dtype + npatch = x.shape[1] - 1 + N = self.pos_embed.shape[1] - 1 + if npatch == N and w == h: + return self.pos_embed + pos_embed = self.pos_embed.float() + class_pos_embed = pos_embed[:, 0] + patch_pos_embed = pos_embed[:, 1:] + dim = x.shape[-1] + w0 = w // self.patch_size + h0 = h // self.patch_size + + M = int(math.sqrt(N)) # Recover the number of patches in each dimension + assert N == M * M + kwargs = {} + if self.interpolate_offset: + # Historical kludge: add a small number to avoid floating point error in the interpolation, see https://github.com/facebookresearch/dino/issues/8 + # Note: still needed for backward-compatibility, the underlying operators are using both output size and scale factors + sx = float(w0 + self.interpolate_offset) / M + sy = float(h0 + self.interpolate_offset) / M + kwargs["scale_factor"] = (sx, sy) + else: + # Simply specify an output size instead of a scale factor + kwargs["size"] = (w0, h0) + + patch_pos_embed = nn.functional.interpolate( + patch_pos_embed.reshape(1, M, M, dim).permute(0, 3, 1, 2), + mode="bicubic", + antialias=self.interpolate_antialias, + **kwargs, + ) + assert (w0, h0) == patch_pos_embed.shape[-2:] + + patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim) + return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1).to( + previous_dtype + ) + + def prepare_tokens_with_masks(self, x, masks=None): + B, nc, w, h = x.shape + with torch.no_grad() if self.frozen_stages > -1 else contextlib.nullcontext(): + x = self.patch_embed(x) + if masks is not None: + masks = masks.bool().view(B, -1, 1) + x = torch.where(masks, self.mask_token.to(x.dtype).unsqueeze(0), x) + + x = torch.cat((self.cls_token.expand(x.shape[0], -1, -1), x), dim=1) + x = x + self.interpolate_pos_encoding(x, w, h) + + if self.num_register_tokens: + x = torch.cat( + (x[:, :1], self.register_tokens.expand(x.shape[0], -1, -1), x[:, 1:]), + dim=1, + ) + return x + + def forward(self, x, masks=None): + shapes = [val // self.patch_size for val in x.shape[-2:]] + batch_size = x.shape[0] + x = self.prepare_tokens_with_masks(x, masks) + outputs = [] + for i, blk in enumerate(self.blocks): + with ( + torch.no_grad() if i < self.frozen_stages else contextlib.nullcontext() + ): + x = blk(x) + outputs.append(x) + + if self.use_norm: + with ( + torch.no_grad() + if self.frozen_stages >= len(self.blocks) + else contextlib.nullcontext() + ): + outputs = [self.norm(out) for out in outputs] + class_tokens = [out[:, :1] for out in outputs] + outputs = [out[:, self.num_register_tokens + 1 :] for out in outputs] + outputs = [out.reshape(batch_size, *shapes, -1) for out in outputs] + + return (outputs, class_tokens) + + def get_params(self, lr, wd, ld, *args, **kwargs): + encoder_p, encoder_lr = get_parameter_groups(self, lr, wd, ld) + return encoder_p, encoder_lr + + def freeze(self) -> None: + for module in self.modules(): + module.eval() + for parameters in self.parameters(): + parameters.requires_grad = False + + def train(self, mode=True): + super().train(mode) + if self.frozen_stages > -1: + for p in self.patch_embed.parameters(): + p.requires_grad = False + + for i, blk in enumerate(self.blocks): + if i < self.frozen_stages: + blk.eval() + for p in blk.parameters(): + p.requires_grad = False + + for p in self.norm.parameters(): + p.requires_grad = self.frozen_stages <= len(self.blocks) and self.use_norm + + self.cls_token.requires_grad = self.frozen_stages < 1 + self.pos_embed.requires_grad = self.frozen_stages < 1 + self.mask_token.requires_grad = False + self.register_tokens.requires_grad = False + + +def init_weights_vit_timm(module: nn.Module, name: str = ""): + """ViT weight initialization, original timm impl (for reproducibility)""" + if isinstance(module, nn.Linear): + trunc_normal_(module.weight, std=0.02) + if module.bias is not None: + nn.init.zeros_(module.bias) + + +def vit_small(patch_size=16, num_register_tokens=0, export=False, **kwargs): + model = DinoVisionTransformer( + patch_size=patch_size, + embed_dim=384, + depth=12, + num_heads=6, + mlp_ratio=4, + num_register_tokens=num_register_tokens, + block_fn=partial(Block, attn_class=Attention if export else MemEffAttention), + **kwargs, + ) + return model + + +def vit_base(patch_size=16, num_register_tokens=0, export=False, **kwargs): + model = DinoVisionTransformer( + patch_size=patch_size, + embed_dim=768, + depth=12, + num_heads=12, + mlp_ratio=4, + num_register_tokens=num_register_tokens, + block_fn=partial(Block, attn_class=Attention if export else MemEffAttention), + **kwargs, + ) + return model + + +def vit_large(patch_size=16, num_register_tokens=0, export=False, **kwargs): + model = DinoVisionTransformer( + patch_size=patch_size, + embed_dim=1024, + depth=24, + num_heads=16, + mlp_ratio=4, + num_register_tokens=num_register_tokens, + block_fn=partial(Block, attn_class=Attention if export else MemEffAttention), + **kwargs, + ) + return model + + +def _make_dinov2_model_name(arch_name: str, patch_size: int) -> str: + compact_arch_name = arch_name.replace("_", "")[:4] + return f"dinov2_{compact_arch_name}{patch_size}" + + +def _make_dinov2_model( + *, + arch_name: str = "vit_large", + img_size: int = 518, + patch_size: int = 14, + init_values: float = 1.0, + ffn_layer: str = "mlp", + block_chunks: int = 0, + pretrained: str = "", + output_idx: Sequence[int] = [], + num_register_tokens: int = 0, + drop_path_rate: float = 0.0, + use_norm: bool = False, + export: bool = False, + interpolate_offset: float = 0.0, + frozen_stages: int = 0, + **kwargs, +): + model_name = _make_dinov2_model_name(arch_name, patch_size) + vit_kwargs = dict( + img_size=img_size, + patch_size=patch_size, + init_values=init_values, + ffn_layer=ffn_layer, + block_chunks=block_chunks, + output_idx=output_idx, + drop_path_rate=drop_path_rate, + num_register_tokens=num_register_tokens, + use_norm=use_norm, + export=export, + interpolate_offset=interpolate_offset, + frozen_stages=frozen_stages, + ) + vit_kwargs.update(**kwargs) + model = eval(arch_name)(**vit_kwargs) + if pretrained == "": + url = _DINOV2_BASE_URL + f"/{model_name}/{model_name}" + if num_register_tokens > 0: + url += "_reg4" + url += "_pretrain.pth" + state_dict = torch.hub.load_state_dict_from_url( + url, map_location="cpu", progress=False + ) + info = model.load_state_dict(state_dict, strict=False) + print(info) + elif pretrained is not None: + state_dict = torch.load(pretrained, map_location="cpu") + info = model.load_state_dict(state_dict, strict=False) + print(f"loading from {pretrained} with:", info) + else: + print("Not loading pretrained weights for backbone") + return model diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/backbones/metadinov2/__init__.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/backbones/metadinov2/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e9efd71a64023875330cc1c42a87452597dd9ae3 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/backbones/metadinov2/__init__.py @@ -0,0 +1,12 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +from .attention import Attention, MemEffAttention +from .block import NestedTensorBlock +from .dino_head import DINOHead +from .mlp import Mlp +from .patch_embed import PatchEmbed +from .swiglu_ffn import SwiGLUFFN, SwiGLUFFNFused diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/backbones/metadinov2/attention.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/backbones/metadinov2/attention.py new file mode 100644 index 0000000000000000000000000000000000000000..4707b37047736154abb4297ee08aa4f634ac4a53 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/backbones/metadinov2/attention.py @@ -0,0 +1,82 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +# References: +# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py +# https://github.com/rwightman/pytorch-image-models/tree/master/timm/models/vision_transformer.py + +import logging + +import torch +import torch.nn as nn +import torch.nn.functional as F + +logger = logging.getLogger("dinov2") + + +try: + from xformers.ops import fmha, memory_efficient_attention, unbind + + XFORMERS_AVAILABLE = True +except ImportError: + logger.warning("xFormers not available") + XFORMERS_AVAILABLE = False + +XFORMERS_AVAILABLE = XFORMERS_AVAILABLE and torch.cuda.is_available() + + +class Attention(nn.Module): + def __init__( + self, + dim: int, + num_heads: int = 8, + qkv_bias: bool = False, + proj_bias: bool = True, + attn_drop: float = 0.0, + proj_drop: float = 0.0, + ) -> None: + super().__init__() + self.num_heads = num_heads + head_dim = dim // num_heads + self.scale = head_dim**-0.5 + + self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) + self.attn_drop = nn.Dropout(attn_drop) + self.proj = nn.Linear(dim, dim, bias=proj_bias) + self.proj_drop = nn.Dropout(proj_drop) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + B, N, C = x.shape + qkv = ( + self.qkv(x) + .reshape(B, N, 3, self.num_heads, C // self.num_heads) + .permute(2, 0, 3, 1, 4) + ) + x = F.scaled_dot_product_attention(qkv[0], qkv[1], qkv[2]) + x = x.transpose(1, 2).reshape(B, N, C) + x = self.proj(x) + x = self.proj_drop(x) + return x + + +class MemEffAttention(Attention): + def forward(self, x: torch.Tensor, attn_bias=None) -> torch.Tensor: + # new pytorch have good attn efficient, no need for xformers + if not XFORMERS_AVAILABLE or x.device.type == "cpu": + assert attn_bias is None, "xFormers is required for nested tensors usage" + return super().forward(x) + + B, N, C = x.shape + qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads) + + q, k, v = unbind(qkv, 2) + + x = memory_efficient_attention(q, k, v, attn_bias=attn_bias) + x = x.reshape([B, N, C]) + + x = self.proj(x) + x = self.proj_drop(x) + return x diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/backbones/metadinov2/block.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/backbones/metadinov2/block.py new file mode 100644 index 0000000000000000000000000000000000000000..801f8f68785e36fb16dcb1a743302e90b70c0c94 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/backbones/metadinov2/block.py @@ -0,0 +1,282 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +# References: +# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py +# https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/patch_embed.py + +import logging +from typing import Any, Callable, Dict, List, Tuple + +import torch +import torch.nn as nn + +from .attention import Attention, MemEffAttention +from .drop_path import DropPath +from .layer_scale import LayerScale +from .mlp import Mlp + +logger = logging.getLogger("dinov2") + + +try: + from xformers.ops import fmha, index_select_cat, scaled_index_add + + XFORMERS_AVAILABLE = True +except ImportError: + logger.warning("xFormers not available") + XFORMERS_AVAILABLE = False + + +class Block(nn.Module): + def __init__( + self, + dim: int, + num_heads: int, + mlp_ratio: float = 4.0, + qkv_bias: bool = False, + proj_bias: bool = True, + ffn_bias: bool = True, + drop: float = 0.0, + attn_drop: float = 0.0, + init_values=None, + drop_path: float = 0.0, + act_layer: Callable[..., nn.Module] = nn.GELU, + norm_layer: Callable[..., nn.Module] = nn.LayerNorm, + attn_class: Callable[..., nn.Module] = Attention, + ffn_layer: Callable[..., nn.Module] = Mlp, + ) -> None: + super().__init__() + # print(f"biases: qkv: {qkv_bias}, proj: {proj_bias}, ffn: {ffn_bias}") + self.norm1 = norm_layer(dim) + self.attn = attn_class( + dim, + num_heads=num_heads, + qkv_bias=qkv_bias, + proj_bias=proj_bias, + attn_drop=attn_drop, + proj_drop=drop, + ) + self.ls1 = ( + LayerScale(dim, init_values=init_values) if init_values else nn.Identity() + ) + self.drop_path1 = DropPath(drop_path) if drop_path > 0.0 else nn.Identity() + + self.norm2 = norm_layer(dim) + mlp_hidden_dim = int(dim * mlp_ratio) + self.mlp = ffn_layer( + in_features=dim, + hidden_features=mlp_hidden_dim, + act_layer=act_layer, + drop=drop, + bias=ffn_bias, + ) + self.ls2 = ( + LayerScale(dim, init_values=init_values) if init_values else nn.Identity() + ) + self.drop_path2 = DropPath(drop_path) if drop_path > 0.0 else nn.Identity() + + self.sample_drop_ratio = drop_path + + def forward(self, x: torch.Tensor) -> torch.Tensor: + def attn_residual_func(x: torch.Tensor) -> torch.Tensor: + return self.ls1(self.attn(self.norm1(x))) + + def ffn_residual_func(x: torch.Tensor) -> torch.Tensor: + return self.ls2(self.mlp(self.norm2(x))) + + if self.training and self.sample_drop_ratio > 0.1: + # the overhead is compensated only for a drop path rate larger than 0.1 + x = drop_add_residual_stochastic_depth( + x, + residual_func=attn_residual_func, + sample_drop_ratio=self.sample_drop_ratio, + ) + x = drop_add_residual_stochastic_depth( + x, + residual_func=ffn_residual_func, + sample_drop_ratio=self.sample_drop_ratio, + ) + elif self.training and self.sample_drop_ratio > 0.0: + x = x + self.drop_path1(attn_residual_func(x)) + x = x + self.drop_path1(ffn_residual_func(x)) # FIXME: drop_path2 + else: + x = x + attn_residual_func(x) + x = x + ffn_residual_func(x) + return x + + +def drop_add_residual_stochastic_depth( + x: torch.Tensor, + residual_func: Callable[[torch.Tensor], torch.Tensor], + sample_drop_ratio: float = 0.0, +) -> torch.Tensor: + # 1) extract subset using permutation + b, n, d = x.shape + sample_subset_size = max(int(b * (1 - sample_drop_ratio)), 1) + brange = (torch.randperm(b, device=x.device))[:sample_subset_size] + x_subset = x[brange] + + # 2) apply residual_func to get residual + residual = residual_func(x_subset) + + x_flat = x.flatten(1) + residual = residual.flatten(1) + + residual_scale_factor = b / sample_subset_size + + # 3) add the residual + x_plus_residual = torch.index_add( + x_flat, 0, brange, residual.to(dtype=x.dtype), alpha=residual_scale_factor + ) + return x_plus_residual.view_as(x) + + +def get_branges_scales(x, sample_drop_ratio=0.0): + b, n, d = x.shape + sample_subset_size = max(int(b * (1 - sample_drop_ratio)), 1) + brange = (torch.randperm(b, device=x.device))[:sample_subset_size] + residual_scale_factor = b / sample_subset_size + return brange, residual_scale_factor + + +def add_residual(x, brange, residual, residual_scale_factor, scaling_vector=None): + if scaling_vector is None: + x_flat = x.flatten(1) + residual = residual.flatten(1) + x_plus_residual = torch.index_add( + x_flat, 0, brange, residual.to(dtype=x.dtype), alpha=residual_scale_factor + ) + else: + x_plus_residual = scaled_index_add( + x, + brange, + residual.to(dtype=x.dtype), + scaling=scaling_vector, + alpha=residual_scale_factor, + ) + return x_plus_residual + + +attn_bias_cache: Dict[Tuple, Any] = {} + + +def get_attn_bias_and_cat(x_list, branges=None): + """ + this will perform the index select, cat the tensors, and provide the attn_bias from cache + """ + batch_sizes = ( + [b.shape[0] for b in branges] + if branges is not None + else [x.shape[0] for x in x_list] + ) + all_shapes = tuple((b, x.shape[1]) for b, x in zip(batch_sizes, x_list)) + if all_shapes not in attn_bias_cache.keys(): + seqlens = [] + for b, x in zip(batch_sizes, x_list): + for _ in range(b): + seqlens.append(x.shape[1]) + attn_bias = fmha.BlockDiagonalMask.from_seqlens(seqlens) + attn_bias._batch_sizes = batch_sizes + attn_bias_cache[all_shapes] = attn_bias + + if branges is not None: + cat_tensors = index_select_cat([x.flatten(1) for x in x_list], branges).view( + 1, -1, x_list[0].shape[-1] + ) + else: + tensors_bs1 = tuple(x.reshape([1, -1, *x.shape[2:]]) for x in x_list) + cat_tensors = torch.cat(tensors_bs1, dim=1) + + return attn_bias_cache[all_shapes], cat_tensors + + +def drop_add_residual_stochastic_depth_list( + x_list: List[torch.Tensor], + residual_func: Callable[[torch.Tensor, Any], torch.Tensor], + sample_drop_ratio: float = 0.0, + scaling_vector=None, +) -> torch.Tensor: + # 1) generate random set of indices for dropping samples in the batch + branges_scales = [ + get_branges_scales(x, sample_drop_ratio=sample_drop_ratio) for x in x_list + ] + branges = [s[0] for s in branges_scales] + residual_scale_factors = [s[1] for s in branges_scales] + + # 2) get attention bias and index+concat the tensors + attn_bias, x_cat = get_attn_bias_and_cat(x_list, branges) + + # 3) apply residual_func to get residual, and split the result + residual_list = attn_bias.split(residual_func(x_cat, attn_bias=attn_bias)) # type: ignore + + outputs = [] + for x, brange, residual, residual_scale_factor in zip( + x_list, branges, residual_list, residual_scale_factors + ): + outputs.append( + add_residual( + x, brange, residual, residual_scale_factor, scaling_vector + ).view_as(x) + ) + return outputs + + +class NestedTensorBlock(Block): + def forward_nested(self, x_list: List[torch.Tensor]) -> List[torch.Tensor]: + """ + x_list contains a list of tensors to nest together and run + """ + assert isinstance(self.attn, MemEffAttention) + + if self.training and self.sample_drop_ratio > 0.0: + + def attn_residual_func(x: torch.Tensor, attn_bias=None) -> torch.Tensor: + return self.attn(self.norm1(x), attn_bias=attn_bias) + + def ffn_residual_func(x: torch.Tensor, attn_bias=None) -> torch.Tensor: + return self.mlp(self.norm2(x)) + + x_list = drop_add_residual_stochastic_depth_list( + x_list, + residual_func=attn_residual_func, + sample_drop_ratio=self.sample_drop_ratio, + scaling_vector=( + self.ls1.gamma if isinstance(self.ls1, LayerScale) else None + ), + ) + x_list = drop_add_residual_stochastic_depth_list( + x_list, + residual_func=ffn_residual_func, + sample_drop_ratio=self.sample_drop_ratio, + scaling_vector=( + self.ls2.gamma if isinstance(self.ls1, LayerScale) else None + ), + ) + return x_list + else: + + def attn_residual_func(x: torch.Tensor, attn_bias=None) -> torch.Tensor: + return self.ls1(self.attn(self.norm1(x), attn_bias=attn_bias)) + + def ffn_residual_func(x: torch.Tensor, attn_bias=None) -> torch.Tensor: + return self.ls2(self.mlp(self.norm2(x))) + + attn_bias, x = get_attn_bias_and_cat(x_list) + x = x + attn_residual_func(x, attn_bias=attn_bias) + x = x + ffn_residual_func(x) + return attn_bias.split(x) + + def forward(self, x_or_x_list): + if isinstance(x_or_x_list, torch.Tensor): + return super(NestedTensorBlock, self).forward(x_or_x_list) + elif isinstance(x_or_x_list, list): + assert ( + XFORMERS_AVAILABLE + ), "Please install xFormers for nested tensors usage" + return self.forward_nested(x_or_x_list) + else: + raise AssertionError diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/backbones/metadinov2/dino_head.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/backbones/metadinov2/dino_head.py new file mode 100644 index 0000000000000000000000000000000000000000..1147dd3a3c046aee8d427b42b1055f38a218275b --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/backbones/metadinov2/dino_head.py @@ -0,0 +1,68 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import torch +import torch.nn as nn +from torch.nn.init import trunc_normal_ +from torch.nn.utils import weight_norm + + +class DINOHead(nn.Module): + def __init__( + self, + in_dim, + out_dim, + use_bn=False, + nlayers=3, + hidden_dim=2048, + bottleneck_dim=256, + mlp_bias=True, + ): + super().__init__() + nlayers = max(nlayers, 1) + self.mlp = _build_mlp( + nlayers, + in_dim, + bottleneck_dim, + hidden_dim=hidden_dim, + use_bn=use_bn, + bias=mlp_bias, + ) + self.apply(self._init_weights) + self.last_layer = weight_norm(nn.Linear(bottleneck_dim, out_dim, bias=False)) + self.last_layer.weight_g.data.fill_(1) + + def _init_weights(self, m): + if isinstance(m, nn.Linear): + trunc_normal_(m.weight, std=0.02) + if isinstance(m, nn.Linear) and m.bias is not None: + nn.init.constant_(m.bias, 0) + + def forward(self, x): + x = self.mlp(x) + eps = 1e-6 if x.dtype == torch.float16 else 1e-12 + x = nn.functional.normalize(x, dim=-1, p=2, eps=eps) + x = self.last_layer(x) + return x + + +def _build_mlp( + nlayers, in_dim, bottleneck_dim, hidden_dim=None, use_bn=False, bias=True +): + if nlayers == 1: + return nn.Linear(in_dim, bottleneck_dim, bias=bias) + else: + layers = [nn.Linear(in_dim, hidden_dim, bias=bias)] + if use_bn: + layers.append(nn.BatchNorm1d(hidden_dim)) + layers.append(nn.GELU()) + for _ in range(nlayers - 2): + layers.append(nn.Linear(hidden_dim, hidden_dim, bias=bias)) + if use_bn: + layers.append(nn.BatchNorm1d(hidden_dim)) + layers.append(nn.GELU()) + layers.append(nn.Linear(hidden_dim, bottleneck_dim, bias=bias)) + return nn.Sequential(*layers) diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/backbones/metadinov2/drop_path.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/backbones/metadinov2/drop_path.py new file mode 100644 index 0000000000000000000000000000000000000000..35b1a620d06ba862ea05297d271d8c2c625b5f93 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/backbones/metadinov2/drop_path.py @@ -0,0 +1,37 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +# References: +# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py +# https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/drop.py + + +import torch.nn as nn + + +def drop_path(x, drop_prob: float = 0.0, training: bool = False): + if drop_prob == 0.0 or not training: + return x + keep_prob = 1 - drop_prob + shape = (x.shape[0],) + (1,) * ( + x.ndim - 1 + ) # work with diff dim tensors, not just 2D ConvNets + random_tensor = x.new_empty(shape).bernoulli_(keep_prob) + if keep_prob > 0.0: + random_tensor.div_(keep_prob) + output = x * random_tensor + return output + + +class DropPath(nn.Module): + """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).""" + + def __init__(self, drop_prob=None): + super(DropPath, self).__init__() + self.drop_prob = drop_prob + + def forward(self, x): + return drop_path(x, self.drop_prob, self.training) diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/backbones/metadinov2/layer_scale.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/backbones/metadinov2/layer_scale.py new file mode 100644 index 0000000000000000000000000000000000000000..40d18b5427183534d5516652b076f9883a609fc6 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/backbones/metadinov2/layer_scale.py @@ -0,0 +1,28 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +# Modified from: https://github.com/huggingface/pytorch-image-models/blob/main/timm/models/vision_transformer.py#L103-L110 + +from typing import Union + +import torch +import torch.nn as nn +from torch import Tensor + + +class LayerScale(nn.Module): + def __init__( + self, + dim: int, + init_values: Union[float, Tensor] = 1e-5, + inplace: bool = False, + ) -> None: + super().__init__() + self.inplace = inplace + self.gamma = nn.Parameter(init_values * torch.ones(dim)) + + def forward(self, x: Tensor) -> Tensor: + return x.mul_(self.gamma) if self.inplace else x * self.gamma diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/backbones/metadinov2/mlp.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/backbones/metadinov2/mlp.py new file mode 100644 index 0000000000000000000000000000000000000000..5e4b315f972f9a9f54aef1e4ef4e81b52976f018 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/backbones/metadinov2/mlp.py @@ -0,0 +1,41 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +# References: +# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py +# https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/mlp.py + + +from typing import Callable, Optional + +from torch import Tensor, nn + + +class Mlp(nn.Module): + def __init__( + self, + in_features: int, + hidden_features: Optional[int] = None, + out_features: Optional[int] = None, + act_layer: Callable[..., nn.Module] = nn.GELU, + drop: float = 0.0, + bias: bool = True, + ) -> None: + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features + self.fc1 = nn.Linear(in_features, hidden_features, bias=bias) + self.act = act_layer() + self.fc2 = nn.Linear(hidden_features, out_features, bias=bias) + self.drop = nn.Dropout(drop) + + def forward(self, x: Tensor) -> Tensor: + x = self.fc1(x) + x = self.act(x) + x = self.drop(x) + x = self.fc2(x) + x = self.drop(x) + return x diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/backbones/metadinov2/patch_embed.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/backbones/metadinov2/patch_embed.py new file mode 100644 index 0000000000000000000000000000000000000000..e5a56c02609e67922eb8f859588ef274e5298b55 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/backbones/metadinov2/patch_embed.py @@ -0,0 +1,101 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +# References: +# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py +# https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/patch_embed.py + +from typing import Callable, Optional, Tuple, Union + +import torch.nn as nn +from torch import Tensor + + +def make_2tuple(x): + if isinstance(x, tuple): + assert len(x) == 2 + return x + + assert isinstance(x, int) + return (x, x) + + +class PatchEmbed(nn.Module): + """ + 2D image to patch embedding: (B,C,H,W) -> (B,N,D) + + Args: + img_size: Image size. + patch_size: Patch token size. + in_chans: Number of input image channels. + embed_dim: Number of linear projection output channels. + norm_layer: Normalization layer. + """ + + def __init__( + self, + img_size: Union[int, Tuple[int, int]] = 224, + patch_size: Union[int, Tuple[int, int]] = 16, + in_chans: int = 3, + embed_dim: int = 768, + norm_layer: Optional[Callable] = None, + flatten_embedding: bool = True, + ) -> None: + super().__init__() + + image_HW = make_2tuple(img_size) + patch_HW = make_2tuple(patch_size) + patch_grid_size = ( + image_HW[0] // patch_HW[0], + image_HW[1] // patch_HW[1], + ) + + self.img_size = image_HW + self.patch_size = patch_HW + self.patches_resolution = patch_grid_size + self.num_patches = patch_grid_size[0] * patch_grid_size[1] + + self.in_chans = in_chans + self.embed_dim = embed_dim + + self.flatten_embedding = flatten_embedding + + self.proj = nn.Conv2d( + in_chans, embed_dim, kernel_size=patch_HW, stride=patch_HW + ) + self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity() + + def forward(self, x: Tensor) -> Tensor: + _, _, H, W = x.shape + patch_H, patch_W = self.patch_size + + assert ( + H % patch_H == 0 + ), f"Input image height {H} is not a multiple of patch height {patch_H}" + assert ( + W % patch_W == 0 + ), f"Input image width {W} is not a multiple of patch width: {patch_W}" + + x = self.proj(x) # B C H W + H, W = x.size(2), x.size(3) + x = x.flatten(2).transpose(1, 2) # B HW C + x = self.norm(x) + if not self.flatten_embedding: + x = x.reshape(-1, H, W, self.embed_dim) # B H W C + return x + + def flops(self) -> float: + Ho, Wo = self.patches_resolution + flops = ( + Ho + * Wo + * self.embed_dim + * self.in_chans + * (self.patch_size[0] * self.patch_size[1]) + ) + if self.norm is not None: + flops += Ho * Wo * self.embed_dim + return flops diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/backbones/metadinov2/swiglu_ffn.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/backbones/metadinov2/swiglu_ffn.py new file mode 100644 index 0000000000000000000000000000000000000000..e82999e9b09b41cd6aba9edbc4c05d51ab663a1e --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/backbones/metadinov2/swiglu_ffn.py @@ -0,0 +1,63 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +from typing import Callable, Optional + +import torch.nn.functional as F +from torch import Tensor, nn + + +class SwiGLUFFN(nn.Module): + def __init__( + self, + in_features: int, + hidden_features: Optional[int] = None, + out_features: Optional[int] = None, + act_layer: Callable[..., nn.Module] = None, + drop: float = 0.0, + bias: bool = True, + ) -> None: + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features + self.w12 = nn.Linear(in_features, 2 * hidden_features, bias=bias) + self.w3 = nn.Linear(hidden_features, out_features, bias=bias) + + def forward(self, x: Tensor) -> Tensor: + x12 = self.w12(x) + x1, x2 = x12.chunk(2, dim=-1) + hidden = F.silu(x1) * x2 + return self.w3(hidden) + + +try: + from xformers.ops import SwiGLU + + XFORMERS_AVAILABLE = True +except ImportError: + SwiGLU = SwiGLUFFN + XFORMERS_AVAILABLE = False + + +class SwiGLUFFNFused(SwiGLU): + def __init__( + self, + in_features: int, + hidden_features: Optional[int] = None, + out_features: Optional[int] = None, + act_layer: Callable[..., nn.Module] = None, + drop: float = 0.0, + bias: bool = True, + ) -> None: + out_features = out_features or in_features + hidden_features = hidden_features or in_features + hidden_features = (int(hidden_features * 2 / 3) + 7) // 8 * 8 + super().__init__( + in_features=in_features, + hidden_features=hidden_features, + out_features=out_features, + bias=bias, + ) diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/encoder.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..319e21c5600251f1b3c2da0c3df628b90f357b11 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/encoder.py @@ -0,0 +1,193 @@ +import torch +import torch.nn as nn + +from unidepth.models.backbones import ConvNeXt, ConvNeXtV2, _make_dinov2_model + + +class ModelWrap(nn.Module): + def __init__(self, model) -> None: + super().__init__() + self.backbone = model + + def forward(self, x, *args, **kwargs): + features = [] + for layer in self.backbone.features: + x = layer(x) + features.append(x) + return features + + +def convnextv2_base(config, **kwargs): + model = ConvNeXtV2( + depths=[3, 3, 27, 3], + dims=[128, 256, 512, 1024], + output_idx=config.get("output_idx", [3, 6, 33, 36]), + use_checkpoint=config.get("use_checkpoint", False), + **kwargs, + ) + url = "https://dl.fbaipublicfiles.com/convnext/convnextv2/im22k/convnextv2_base_22k_384_ema.pt" + state_dict = torch.hub.load_state_dict_from_url( + url, map_location="cpu", progress=False + )["model"] + info = model.load_state_dict(state_dict, strict=False) + print(info) + return model + + +def convnextv2_large(config, **kwargs): + model = ConvNeXtV2( + depths=[3, 3, 27, 3], + dims=[192, 384, 768, 1536], + output_idx=config.get("output_idx", [3, 6, 33, 36]), + use_checkpoint=config.get("use_checkpoint", False), + **kwargs, + ) + url = "https://dl.fbaipublicfiles.com/convnext/convnextv2/im22k/convnextv2_large_22k_384_ema.pt" + state_dict = torch.hub.load_state_dict_from_url( + url, map_location="cpu", progress=False + )["model"] + info = model.load_state_dict(state_dict, strict=False) + print(info) + return model + + +def convnextv2_large_mae(config, **kwargs): + model = ConvNeXtV2( + depths=[3, 3, 27, 3], + dims=[192, 384, 768, 1536], + output_idx=config.get("output_idx", [3, 6, 33, 36]), + use_checkpoint=config.get("use_checkpoint", False), + **kwargs, + ) + url = "https://dl.fbaipublicfiles.com/convnext/convnextv2/pt_only/convnextv2_large_1k_224_fcmae.pt" + state_dict = torch.hub.load_state_dict_from_url( + url, map_location="cpu", progress=False + )["model"] + info = model.load_state_dict(state_dict, strict=False) + print(info) + return model + + +def convnextv2_huge(config, **kwargs): + model = ConvNeXtV2( + depths=[3, 3, 27, 3], + dims=[352, 704, 1408, 2816], + output_idx=config.get("output_idx", [3, 6, 33, 36]), + use_checkpoint=config.get("use_checkpoint", False), + **kwargs, + ) + url = "https://dl.fbaipublicfiles.com/convnext/convnextv2/im22k/convnextv2_huge_22k_512_ema.pt" + state_dict = torch.hub.load_state_dict_from_url( + url, map_location="cpu", progress=False + )["model"] + info = model.load_state_dict(state_dict, strict=False) + print(info) + return model + + +def convnextv2_huge_mae(config, **kwargs): + model = ConvNeXtV2( + depths=[3, 3, 27, 3], + dims=[352, 704, 1408, 2816], + output_idx=config.get("output_idx", [3, 6, 33, 36]), + use_checkpoint=config.get("use_checkpoint", False), + **kwargs, + ) + url = "https://dl.fbaipublicfiles.com/convnext/convnextv2/pt_only/convnextv2_huge_1k_224_fcmae.pt" + state_dict = torch.hub.load_state_dict_from_url( + url, map_location="cpu", progress=False + )["model"] + info = model.load_state_dict(state_dict, strict=False) + print(info) + return model + + +def convnext_large_pt(config, **kwargs): + model = ConvNeXt( + depths=[3, 3, 27, 3], + dims=[192, 384, 768, 1536], + output_idx=config.get("output_idx", [3, 6, 33, 36]), + use_checkpoint=config.get("use_checkpoint", False), + **kwargs, + ) + from huggingface_hub import hf_hub_download + from huggingface_hub.utils import disable_progress_bars + + from unidepth.models.backbones.convnext import HF_URL, checkpoint_filter_fn + + disable_progress_bars() + repo_id, filename = HF_URL["convnext_large_pt"] + state_dict = torch.load(hf_hub_download(repo_id=repo_id, filename=filename)) + state_dict = checkpoint_filter_fn(state_dict, model) + info = model.load_state_dict(state_dict, strict=False) + print(info) + return model + + +def convnext_large(config, **kwargs): + model = ConvNeXt( + depths=[3, 3, 27, 3], + dims=[192, 384, 768, 1536], + output_idx=config.get("output_idx", [3, 6, 33, 36]), + use_checkpoint=config.get("use_checkpoint", False), + drop_path_rate=config.get("drop_path", 0.0), + **kwargs, + ) + return model + + +def dinov2_vits14(config, pretrained: bool = True, **kwargs): + """ + DINOv2 ViT-S/14 model (optionally) pretrained on the LVD-142M dataset. + """ + vit = _make_dinov2_model( + arch_name="vit_small", + pretrained=config["pretrained"], + output_idx=config.get("output_idx", [3, 6, 9, 12]), + checkpoint=config.get("use_checkpoint", False), + drop_path_rate=config.get("drop_path", 0.0), + num_register_tokens=config.get("num_register_tokens", 0), + use_norm=config.get("use_norm", False), + export=config.get("export", False), + interpolate_offset=config.get("interpolate_offset", 0.0), + **kwargs, + ) + return vit + + +def dinov2_vitb14(config, pretrained: bool = True, **kwargs): + """ + DINOv2 ViT-B/14 model (optionally) pretrained on the LVD-142M dataset. + """ + vit = _make_dinov2_model( + arch_name="vit_base", + pretrained=config["pretrained"], + output_idx=config.get("output_idx", [3, 6, 9, 12]), + checkpoint=config.get("use_checkpoint", False), + drop_path_rate=config.get("drop_path", 0.0), + num_register_tokens=config.get("num_register_tokens", 0), + use_norm=config.get("use_norm", False), + export=config.get("export", False), + interpolate_offset=config.get("interpolate_offset", 0.0), + **kwargs, + ) + return vit + + +def dinov2_vitl14(config, pretrained: str = "", **kwargs): + """ + DINOv2 ViT-L/14 model (optionally) pretrained on the LVD-142M dataset. + """ + vit = _make_dinov2_model( + arch_name="vit_large", + pretrained=config["pretrained"], + output_idx=config.get("output_idx", [5, 12, 18, 24]), + checkpoint=config.get("use_checkpoint", False), + drop_path_rate=config.get("drop_path", 0.0), + num_register_tokens=config.get("num_register_tokens", 0), + use_norm=config.get("use_norm", False), + export=config.get("export", False), + interpolate_offset=config.get("interpolate_offset", 0.0), + **kwargs, + ) + return vit diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/unidepthv1/__init__.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/unidepthv1/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1781bda94cdc13b0c0c805e7cde0872defc20cd3 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/unidepthv1/__init__.py @@ -0,0 +1,5 @@ +from .unidepthv1 import UniDepthV1 + +__all__ = [ + "UniDepthV1", +] diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/unidepthv1/decoder.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/unidepthv1/decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..bdfb363669577d92b5433111133fa4c2933f7f1f --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/unidepthv1/decoder.py @@ -0,0 +1,533 @@ +""" +Author: Luigi Piccinelli +Licensed under the CC-BY NC 4.0 license (http://creativecommons.org/licenses/by-nc/4.0/) +""" + +from typing import List, Tuple + +import torch +import torch.nn as nn +import torch.nn.functional as F +from einops import rearrange +from timm.models.layers import trunc_normal_ + +from unidepth.layers import (MLP, AttentionBlock, ConvUpsample, NystromBlock, + PositionEmbeddingSine) +from unidepth.utils.geometric import flat_interpolate, generate_rays +from unidepth.utils.misc import max_stack +from unidepth.utils.sht import rsh_cart_8 + + +class ListAdapter(nn.Module): + def __init__(self, input_dims: List[int], hidden_dim: int): + super().__init__() + self.input_adapters = nn.ModuleList([]) + self.num_chunks = len(input_dims) + for input_dim in input_dims: + self.input_adapters.append( + nn.Sequential( + nn.LayerNorm(input_dim), nn.Linear(input_dim, hidden_dim), nn.GELU() + ) + ) + + def forward(self, x: torch.Tensor, splits: torch.Tensor) -> torch.Tensor: + xs = torch.split(x, splits.int().tolist(), dim=-1) + xs = [adapter(x) for x, adapter in zip(xs, self.input_adapters)] + return torch.cat(xs, dim=-1) + + +class CameraHead(nn.Module): + def __init__( + self, + input_dim: int, + hidden_dim: int, + num_heads: int = 8, + expansion: int = 4, + depth: int = 4, + dropout: float = 0.0, + layer_scale: float = 1.0, + **kwargs, + ): + super().__init__() + + self.aggregate = AttentionBlock( + hidden_dim, + num_heads=1, + expansion=expansion, + dropout=dropout, + layer_scale=layer_scale, + ) + self.latents_pos = nn.Parameter( + torch.randn(1, 4, hidden_dim), requires_grad=True + ) + self.layers = nn.ModuleList([]) + self.in_features = MLP(hidden_dim, expansion=2, dropout=dropout) + for _ in range(depth): + blk = AttentionBlock( + hidden_dim, + num_heads=num_heads, + expansion=expansion, + dropout=dropout, + layer_scale=layer_scale, + ) + self.layers.append(blk) + self.out = MLP(hidden_dim, expansion=2, dropout=0.0, output_dim=1) + self.cls_project = nn.Sequential( + nn.LayerNorm(input_dim), + nn.Linear(input_dim, hidden_dim // 2), + nn.GELU(), + nn.Linear(hidden_dim // 2, hidden_dim), + ) + + def forward(self, features, cls_tokens, pos_embed) -> torch.Tensor: + features = features.unbind(dim=-1) + cls_tokens = self.cls_project(cls_tokens) + features_stack = torch.cat(features, dim=1) + features_stack = features_stack + pos_embed + latents_pos = self.latents_pos.expand(cls_tokens.shape[0], -1, -1) + features_stack = self.in_features(features_stack) + features = torch.cat((features_stack, cls_tokens), dim=1) + cls_tokens = self.aggregate(cls_tokens, context=features, pos_embed=latents_pos) + for i, layer in enumerate(self.layers): + cls_tokens = layer(cls_tokens, pos_embed=latents_pos) + + # project + x = self.out(cls_tokens).squeeze(-1) + camera_intrinsics = torch.zeros( + x.shape[0], 3, 3, device=x.device, requires_grad=False + ) + camera_intrinsics[:, 0, 0] = x[:, 0].exp() + camera_intrinsics[:, 1, 1] = x[:, 1].exp() + camera_intrinsics[:, 0, 2] = x[:, 2].sigmoid() + camera_intrinsics[:, 1, 2] = x[:, 3].sigmoid() + camera_intrinsics[:, 2, 2] = 1.0 + return camera_intrinsics + + def set_shapes(self, shapes: Tuple[int, int]): + self.shapes = shapes + + +class DepthHead(nn.Module): + def __init__( + self, + hidden_dim: int, + num_heads: int = 8, + expansion: int = 4, + depths: int | list[int] = 4, + camera_dim: int = 256, + num_resolutions: int = 4, + dropout: float = 0.0, + layer_scale: float = 1.0, + **kwargs, + ) -> None: + super().__init__() + if isinstance(depths, int): + depths = [depths] * 3 + assert len(depths) == 3 + + self.project_rays16 = MLP( + camera_dim, expansion=expansion, dropout=dropout, output_dim=hidden_dim + ) + self.project_rays8 = MLP( + camera_dim, expansion=expansion, dropout=dropout, output_dim=hidden_dim // 2 + ) + self.project_rays4 = MLP( + camera_dim, expansion=expansion, dropout=dropout, output_dim=hidden_dim // 4 + ) + self.to_latents = MLP(hidden_dim, expansion=2, dropout=dropout) + + self.features_channel_cat = nn.Linear(hidden_dim * num_resolutions, hidden_dim) + + self.up8 = ConvUpsample( + hidden_dim, expansion=expansion, layer_scale=layer_scale + ) + self.up4 = ConvUpsample( + hidden_dim // 2, expansion=expansion, layer_scale=layer_scale + ) + self.up2 = ConvUpsample( + hidden_dim // 4, expansion=expansion, layer_scale=layer_scale + ) + + self.layers_16 = nn.ModuleList([]) + self.layers_8 = nn.ModuleList([]) + self.layers_4 = nn.ModuleList([]) + self.aggregate_16 = AttentionBlock( + hidden_dim, + num_heads=1, + expansion=expansion, + dropout=dropout, + layer_scale=layer_scale, + context_dim=hidden_dim, + ) + self.prompt_camera = AttentionBlock( + hidden_dim, + num_heads=1, + expansion=expansion, + dropout=dropout, + layer_scale=layer_scale, + context_dim=hidden_dim, + ) + for i, (blk_lst, depth) in enumerate( + zip([self.layers_16, self.layers_8, self.layers_4], depths) + ): + attn_cls = AttentionBlock if i == 0 else NystromBlock + for _ in range(depth): + blk_lst.append( + attn_cls( + hidden_dim // (2**i), + num_heads=num_heads // (2**i), + expansion=expansion, + dropout=dropout, + layer_scale=layer_scale, + ) + ) + + self.out2 = nn.Conv2d(hidden_dim // 8, 1, 3, padding=1) + self.out4 = nn.Conv2d(hidden_dim // 4, 1, 3, padding=1) + self.out8 = nn.Conv2d(hidden_dim // 2, 1, 3, padding=1) + + def set_original_shapes(self, shapes: Tuple[int, int]): + self.original_shapes = shapes + + def set_shapes(self, shapes: Tuple[int, int]): + self.shapes = shapes + + def forward( + self, features: torch.Tensor, rays_hr: torch.Tensor, pos_embed, level_embed + ) -> torch.Tensor: + features = features.unbind(dim=-1) + shapes = self.shapes + rays_hr = rays_hr.detach() + + # camera_embedding + rays_embedding_16 = F.normalize( + flat_interpolate(rays_hr, old=self.original_shapes, new=shapes), dim=-1 + ) + rays_embedding_8 = F.normalize( + flat_interpolate( + rays_hr, old=self.original_shapes, new=[x * 2 for x in shapes] + ), + dim=-1, + ) + rays_embedding_4 = F.normalize( + flat_interpolate( + rays_hr, old=self.original_shapes, new=[x * 4 for x in shapes] + ), + dim=-1, + ) + rays_embedding_16 = self.project_rays16(rsh_cart_8(rays_embedding_16)) + rays_embedding_8 = self.project_rays8(rsh_cart_8(rays_embedding_8)) + rays_embedding_4 = self.project_rays4(rsh_cart_8(rays_embedding_4)) + features_tokens = torch.cat(features, dim=1) + features_tokens_pos = pos_embed + level_embed + + # Generate latents with init as pooled features + features_channels = torch.cat(features, dim=-1) + features_16 = self.features_channel_cat(features_channels) + latents_16 = self.to_latents( + flat_interpolate(features_16, old=self.shapes, new=shapes, antialias=False) + ) + + # Aggregate features: F -> D + latents_16 = self.aggregate_16( + latents_16, context=features_tokens, pos_embed_context=features_tokens_pos + ) + + # Aggregate camera: D- > D|E + latents_16 = self.prompt_camera(latents_16, context=rays_embedding_16) + + # Block 16 - Out 8 + for layer in self.layers_16: + latents_16 = layer(latents_16, pos_embed=rays_embedding_16) + latents_8 = self.up8( + rearrange( + latents_16 + rays_embedding_16, + "b (h w) c -> b c h w", + h=shapes[0], + w=shapes[1], + ).contiguous() + ) + out8 = self.out8( + rearrange( + latents_8, "b (h w) c -> b c h w", h=shapes[0] * 2, w=shapes[1] * 2 + ) + ) + + # Block 8 - Out 4 + for layer in self.layers_8: + latents_8 = layer(latents_8, pos_embed=rays_embedding_8) + latents_4 = self.up4( + rearrange( + latents_8 + rays_embedding_8, + "b (h w) c -> b c h w", + h=shapes[0] * 2, + w=shapes[1] * 2, + ).contiguous() + ) + out4 = self.out4( + rearrange( + latents_4, "b (h w) c -> b c h w", h=shapes[0] * 4, w=shapes[1] * 4 + ) + ) + + # Block 4 - Out 2 + for layer in self.layers_4: + latents_4 = layer(latents_4, pos_embed=rays_embedding_4) + latents_2 = self.up2( + rearrange( + latents_4 + rays_embedding_4, + "b (h w) c -> b c h w", + h=shapes[0] * 4, + w=shapes[1] * 4, + ).contiguous() + ) + out2 = self.out2( + rearrange( + latents_2, "b (h w) c -> b c h w", h=shapes[0] * 8, w=shapes[1] * 8 + ) + ) + + # Depth features + proj_latents_16 = rearrange( + latents_16, "b (h w) c -> b c h w", h=shapes[0], w=shapes[1] + ).contiguous() + + # MS Outputs + out2 = out2.clamp(-10.0, 10.0).exp() + out4 = out4.clamp(-10.0, 10.0).exp() + out8 = out8.clamp(-10.0, 10.0).exp() + + return out8, out4, out2, proj_latents_16 + + +class Decoder(nn.Module): + def __init__( + self, + config, + *args, + **kwargs, + ): + super().__init__() + self.build(config) + self.apply(self._init_weights) + self.test_fixed_camera = False + self.skip_camera = False + + def _init_weights(self, m): + if isinstance(m, nn.Linear): + trunc_normal_(m.weight, std=0.02) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.Conv2d): + trunc_normal_(m.weight, std=0.02) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.LayerNorm): + nn.init.constant_(m.bias, 0) + nn.init.constant_(m.weight, 1.0) + + def get_adapted_features(self, features_flat, splits): + features_flat_cat = torch.cat(features_flat, dim=-1) + features_projected = self.input_adapter( + features_flat_cat, splits + ) # list [b hw c] shapes + features = torch.chunk(features_projected, len(splits), dim=-1) + return features + + def run_camera(self, cls_tokens, features, pos_embed, original_shapes, rays): + # get cls tokens projections + cls_tokens_splits = torch.tensor( + [x.shape[-1] for x in cls_tokens], + device=features.device, + requires_grad=False, + dtype=features.dtype, + ) + cls_tokens = torch.cat(cls_tokens, dim=-1) + cls_tokens = self.token_adapter(cls_tokens, cls_tokens_splits) + cls_tokens = torch.cat( + torch.chunk(cls_tokens, len(cls_tokens_splits), dim=-1), dim=1 + ) + + # camera layer + intrinsics = self.camera_layer( + features=features, cls_tokens=cls_tokens, pos_embed=pos_embed + ) + intrinsics[:, 0, 0] = max(original_shapes) / 2 * intrinsics[:, 0, 0] + intrinsics[:, 1, 1] = max(original_shapes) / 2 * intrinsics[:, 1, 1] + intrinsics[:, 0, 2] = intrinsics[:, 0, 2] * original_shapes[1] + intrinsics[:, 1, 2] = intrinsics[:, 1, 2] * original_shapes[0] + if not self.test_fixed_camera: + rays, _ = generate_rays(intrinsics, original_shapes, noisy=False) + + return intrinsics, rays + + def forward(self, inputs, image_metas) -> torch.Tensor: + B, _, H, W = inputs["image"].shape + device = inputs["image"].device + + # make stride happy? + original_encoder_outputs = [x.contiguous() for x in inputs["encoder_outputs"]] + cls_tokens = [x.contiguous() for x in inputs["cls_tokens"]] + + # collect features and tokens + original_encoder_outputs = [ + max_stack(original_encoder_outputs[i:j]) + for i, j in self.slices_encoder_range + ] + # detach tokens for camera + cls_tokens = [ + cls_tokens[-i - 1].detach() for i in range(len(self.slices_encoder_range)) + ] + + # get features in b n d format + # level shapes, the shape per level, for swin like [[128, 128], [64, 64],...], for vit [[32,32]] -> mult times resolutions + resolutions = [ + tuple(sorted([x.shape[1], x.shape[2]])) for x in original_encoder_outputs + ] + level_shapes = sorted(list(set(resolutions)))[::-1] + + if len(level_shapes) == 1: + level_shapes = level_shapes * self.num_resolutions + input_shapes = [ + level_shapes[i] + for i, (start, end) in enumerate(self.slices_encoder) + for _ in range(end - start) + ] + common_shape = level_shapes[-2] + + # input shapes repeat shapes for each level, times the amount of the layers: + features_flat = [ + flat_interpolate( + rearrange(x, "b h w c -> b (h w) c"), old=input_shape, new=common_shape + ) + for x, input_shape in zip(original_encoder_outputs, input_shapes) + ] + features_splits = torch.tensor( + [x.shape[-1] for x in features_flat], + device=device, + requires_grad=False, + dtype=torch.float32, + ) + + # input adapter, then do mean of features in same blocks + features = self.get_adapted_features(features_flat, features_splits) + features = torch.stack(features, dim=-1) + + # positional embeddings, spatial and level + level_embed = torch.cat( + [ + self.level_embed_layer(self.level_embeds)[i : i + 1] + .unsqueeze(0) + .repeat(B, common_shape[0] * common_shape[1], 1) + for i in range(self.num_resolutions) + ], + dim=1, + ) + pos_embed = self.pos_embed( + torch.zeros( + B, + 1, + common_shape[0], + common_shape[1], + device=device, + requires_grad=False, + ) + ) + pos_embed = rearrange(pos_embed, "b c h w -> b (h w) c").repeat( + 1, self.num_resolutions, 1 + ) + + self.camera_layer.set_shapes(common_shape) + intrinsics, rays = ( + self.run_camera( + cls_tokens, + features=features, + pos_embed=pos_embed + level_embed, + original_shapes=(H, W), + rays=inputs.get("rays", None), + ) + if not self.skip_camera + else (inputs["K"], inputs["rays"]) + ) + + # run bulk of the model + self.depth_layer.set_shapes(common_shape) + self.depth_layer.set_original_shapes((H, W)) + out8, out4, out2, depth_features = self.depth_layer( + features=features, + rays_hr=rays, + pos_embed=pos_embed, + level_embed=level_embed, + ) + + return intrinsics, [out8, out4, out2], depth_features + + @torch.jit.ignore + def no_weight_decay_keywords(self): + return {"latents_pos", "level_embeds"} + + def build(self, config): + depth = config["model"]["pixel_decoder"]["depths"] + input_dims = config["model"]["pixel_encoder"]["embed_dims"] + hidden_dim = config["model"]["pixel_decoder"]["hidden_dim"] + num_heads = config["model"]["num_heads"] + expansion = config["model"]["expansion"] + dropout = config["model"]["pixel_decoder"]["dropout"] + depths_encoder = config["model"]["pixel_encoder"]["depths"] + layer_scale = 1.0 + + self.depth = depth + self.dim = hidden_dim + self.downsample = 4 + self.num_heads = num_heads + self.num_resolutions = len(depths_encoder) + self.depths_encoder = depths_encoder + + self.slices_encoder_single = list( + zip([d - 1 for d in self.depths_encoder], self.depths_encoder) + ) + self.slices_encoder_range = list( + zip([0, *self.depths_encoder[:-1]], self.depths_encoder) + ) + cls_token_input_dims = [input_dims[-i - 1] for i in range(len(depths_encoder))] + + input_dims = [input_dims[d - 1] for d in depths_encoder] + self.slices_encoder = self.slices_encoder_single + + # adapt from encoder features, just project + self.input_adapter = ListAdapter(input_dims, hidden_dim) + self.token_adapter = ListAdapter(cls_token_input_dims, hidden_dim) + + # camera layer + self.camera_layer = CameraHead( + input_dim=hidden_dim, + hidden_dim=hidden_dim, + num_heads=num_heads, + expansion=expansion, + depth=2, + dropout=dropout, + layer_scale=layer_scale, + ) + + self.depth_layer = DepthHead( + hidden_dim=hidden_dim, + num_heads=num_heads, + expansion=expansion, + depths=depth, + dropout=dropout, + camera_dim=81, + num_resolutions=self.num_resolutions, + layer_scale=layer_scale, + ) + + # transformer part + self.pos_embed = PositionEmbeddingSine(hidden_dim // 2, normalize=True) + self.level_embeds = nn.Parameter( + torch.randn(len(input_dims), hidden_dim), requires_grad=True + ) + self.level_embed_layer = nn.Sequential( + nn.Linear(hidden_dim, hidden_dim), + nn.GELU(), + nn.Linear(hidden_dim, hidden_dim), + nn.LayerNorm(hidden_dim), + ) diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/unidepthv1/unidepthv1.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/unidepthv1/unidepthv1.py new file mode 100644 index 0000000000000000000000000000000000000000..9372faa2e607883f31d28dee10869253b7268591 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/unidepthv1/unidepthv1.py @@ -0,0 +1,450 @@ +""" +Author: Luigi Piccinelli +Licensed under the CC-BY NC 4.0 license (http://creativecommons.org/licenses/by-nc/4.0/) +""" + +import importlib +from copy import deepcopy +from math import ceil + +import torch +import torch.nn as nn +import torch.nn.functional as F +import torchvision.transforms.functional as TF +from einops import rearrange +from huggingface_hub import PyTorchModelHubMixin + +from unidepth.models.unidepthv1.decoder import Decoder +from unidepth.utils.constants import (IMAGENET_DATASET_MEAN, + IMAGENET_DATASET_STD) +from unidepth.utils.distributed import is_main_process +from unidepth.utils.geometric import (generate_rays, + spherical_zbuffer_to_euclidean) +from unidepth.utils.misc import (get_params, match_gt, match_intrinsics, + profile_method) + +VERBOSE = False + + +# inference helpers +def _paddings(image_shape, network_shape): + cur_h, cur_w = image_shape + h, w = network_shape + pad_top, pad_bottom = (h - cur_h) // 2, h - cur_h - (h - cur_h) // 2 + pad_left, pad_right = (w - cur_w) // 2, w - cur_w - (w - cur_w) // 2 + return pad_left, pad_right, pad_top, pad_bottom + + +def _shapes(image_shape, network_shape): + h, w = image_shape + input_ratio = w / h + output_ratio = network_shape[1] / network_shape[0] + if output_ratio > input_ratio: + ratio = network_shape[0] / h + elif output_ratio <= input_ratio: + ratio = network_shape[1] / w + return (ceil(h * ratio - 0.5), ceil(w * ratio - 0.5)), ratio + + +def _preprocess(rgbs, intrinsics, shapes, pads, ratio, output_shapes): + (pad_left, pad_right, pad_top, pad_bottom) = pads + rgbs = F.interpolate( + rgbs, size=shapes, mode="bilinear", align_corners=False, antialias=True + ) + rgbs = F.pad(rgbs, (pad_left, pad_right, pad_top, pad_bottom), mode="constant") + if intrinsics is not None: + intrinsics = intrinsics.clone() + intrinsics[:, 0, 0] = intrinsics[:, 0, 0] * ratio + intrinsics[:, 1, 1] = intrinsics[:, 1, 1] * ratio + intrinsics[:, 0, 2] = intrinsics[:, 0, 2] * ratio + pad_left + intrinsics[:, 1, 2] = intrinsics[:, 1, 2] * ratio + pad_top + return rgbs, intrinsics + return rgbs, None + + +def _postprocess(predictions, intrinsics, shapes, pads, ratio, original_shapes): + (pad_left, pad_right, pad_top, pad_bottom) = pads + # pred mean, trim paddings, and upsample to input dim + predictions = sum( + [ + F.interpolate( + x.clone(), + size=shapes, + mode="bilinear", + align_corners=False, + antialias=True, + ) + for x in predictions + ] + ) / len(predictions) + predictions = predictions[ + ..., pad_top : shapes[0] - pad_bottom, pad_left : shapes[1] - pad_right + ] + predictions = F.interpolate( + predictions, + size=original_shapes, + mode="bilinear", + align_corners=False, + antialias=True, + ) + intrinsics[:, 0, 0] = intrinsics[:, 0, 0] / ratio + intrinsics[:, 1, 1] = intrinsics[:, 1, 1] / ratio + intrinsics[:, 0, 2] = (intrinsics[:, 0, 2] - pad_left) / ratio + intrinsics[:, 1, 2] = (intrinsics[:, 1, 2] - pad_top) / ratio + return predictions, intrinsics + + +class UniDepthV1( + nn.Module, + PyTorchModelHubMixin, + library_name="UniDepth", + repo_url="https://github.com/lpiccinelli-eth/UniDepth", + tags=["monocular-metric-depth-estimation"], +): + def __init__( + self, + config, + eps: float = 1e-6, + **kwargs, + ): + super().__init__() + self.build(config) + self.build_losses(config) + self.eps = eps + + @profile_method(verbose=VERBOSE) + def forward_train(self, inputs, image_metas): + inputs, outputs = self.encode_decode(inputs, image_metas) + losses = self.compute_losses(outputs, inputs, image_metas) + return outputs, losses + + @profile_method(verbose=VERBOSE) + def forward_test(self, inputs, image_metas): + inputs, outputs = self.encode_decode(inputs, image_metas) + depth_gt = inputs["depth"] + test_outputs = {} + test_outputs["depth"] = match_gt( + outputs["depth"], depth_gt, padding1=inputs["paddings"], padding2=None + ) + test_outputs["points"] = match_gt( + outputs["points"], depth_gt, padding1=inputs["paddings"], padding2=None + ) + test_outputs["confidence"] = match_gt( + outputs["confidence"], depth_gt, padding1=inputs["paddings"], padding2=None + ) + test_outputs["rays"] = match_gt( + outputs["rays"], depth_gt, padding1=inputs["paddings"], padding2=None + ) + test_outputs["rays"] = outputs["rays"] / torch.norm( + outputs["rays"], dim=1, keepdim=True + ).clip(min=1e-5) + test_outputs["intrinsics"] = match_intrinsics( + outputs["intrinsics"], + inputs["image"], + depth_gt, + padding1=inputs["paddings"], + padding2=None, + ) + return test_outputs + + def forward(self, inputs, image_metas): + if self.training: + return self.forward_train(inputs, image_metas) + else: + return self.forward_test(inputs, image_metas) + + def encode_decode(self, inputs, image_metas): + rgbs = inputs["image"] + B, _, H, W = rgbs.shape + cameras = inputs["camera"] + + # shortcut eval should avoid errors + if len(image_metas) and "paddings" in image_metas[0]: + inputs["paddings"] = torch.tensor( + [image_meta["paddings"] for image_meta in image_metas], + device=self.device, + )[ + ..., [0, 2, 1, 3] + ] # lrtb + inputs["depth_paddings"] = torch.tensor( + [image_meta["depth_paddings"] for image_meta in image_metas], + device=self.device, + ) + if ( + self.training + ): # at inference we do not have image paddings on top of depth ones (we have not "crop" on gt in ContextCrop) + inputs["depth_paddings"] = inputs["depth_paddings"] + inputs["paddings"] + + # Get camera rays for supervision, all in unit sphere + if inputs.get("camera", None) is not None: + inputs["rays"] = rearrange( + inputs["camera"].get_rays(shapes=(B, H, W)), "b c h w -> b (h w) c" + ) + + # Encode + encoder_outputs, cls_tokens = self.pixel_encoder(rgbs) + if "dino" in self.pixel_encoder.__class__.__name__.lower(): + encoder_outputs = [ + (x + y.unsqueeze(1)).contiguous() + for x, y in zip(encoder_outputs, cls_tokens) + ] + inputs["encoder_outputs"] = encoder_outputs + inputs["cls_tokens"] = cls_tokens + + # Decode + pred_intrinsics, predictions, depth_features = self.pixel_decoder(inputs, {}) + predictions = sum( + [ + F.interpolate( + x.clone(), + size=(H, W), + mode="bilinear", + align_corners=False, + antialias=True, + ) + for x in predictions + ] + ) / len(predictions) + + # Final 3D points backprojection + pred_rays, pred_angles = generate_rays(pred_intrinsics, (H, W), noisy=False) + + # You may want to use inputs["angles"] if available? + pred_angles = rearrange(pred_angles, "b (h w) c -> b c h w", h=H, w=W) + + points_3d = torch.cat((pred_angles, predictions), dim=1) + points_3d = spherical_zbuffer_to_euclidean( + points_3d.permute(0, 2, 3, 1) + ).permute(0, 3, 1, 2) + + # Output data, use for loss computation + outputs = { + "angles": pred_angles, + "rays": pred_rays, + "intrinsics": pred_intrinsics, + "points": points_3d, + "depth": predictions[:, -1:], + "cond_features": depth_features, + } + self.pixel_decoder.test_fixed_camera = False + outputs["rays"] = rearrange(outputs["rays"], "b (h w) c -> b c h w", h=H, w=W) + if "rays" in inputs: + inputs["rays"] = rearrange(inputs["rays"], "b (h w) c -> b c h w", h=H, w=W) + return inputs, outputs + + def compute_losses(self, outputs, inputs, image_metas): + B, _, H, W = inputs["image"].shape + losses = {"opt": {}, "stat": {}} + if ( + not self.training + ): # only compute losses during training, avoid issues for mismatch size of pred and GT + return losses + losses_to_be_computed = list(self.losses.keys()) + + # depth loss + si = torch.tensor( + [x.get("si", False) for x in image_metas], device=self.device + ).reshape(B) + loss = self.losses["depth"] + depth_losses = loss( + outputs["depth"], + target=inputs["depth"], + mask=inputs["depth_mask"].clone(), + si=si, + ) + losses["opt"][loss.name] = loss.weight * depth_losses.mean() + losses_to_be_computed.remove("depth") + + # camera loss, here we apply to rays for simplicity + # in the original training was on angles + # however, we saw no difference (see supplementary) + loss = self.losses["camera"] + camera_losses = loss(outputs["rays"], target=inputs["rays"]) + losses["opt"][loss.name] = loss.weight * camera_losses.mean() + losses_to_be_computed.remove("camera") + + # invariance loss + flips = torch.tensor( + [x.get("flip", False) for x in image_metas], device=self.device + ).reshape(B) + loss = self.losses["invariance"] + invariance_losses = loss( + outputs["cond_features"], + intrinsics=inputs["camera"].K, + mask=inputs["depth_mask"], + flips=flips, + ) + losses["opt"][loss.name] = loss.weight * invariance_losses.mean() + losses_to_be_computed.remove("invariance") + + # remaining losses, we expect no more losses to be computed + assert ( + not losses_to_be_computed + ), f"Losses {losses_to_be_computed} not computed, revise `compute_loss` method" + + return losses + + @torch.no_grad() + def infer(self, rgbs: torch.Tensor, intrinsics=None, skip_camera=False): + if rgbs.ndim == 3: + rgbs = rgbs.unsqueeze(0) + if intrinsics is not None and intrinsics.ndim == 2: + intrinsics = intrinsics.unsqueeze(0) + B, _, H, W = rgbs.shape + + rgbs = rgbs.to(self.device) + if intrinsics is not None: + intrinsics = intrinsics.to(self.device) + + # process image and intrinsiscs (if any) to match network input (slow?) + if rgbs.max() > 5 or rgbs.dtype == torch.uint8: + rgbs = rgbs.to(torch.float32).div(255) + if rgbs.min() >= 0.0 and rgbs.max() <= 1.0: + rgbs = TF.normalize( + rgbs, + mean=IMAGENET_DATASET_MEAN, + std=IMAGENET_DATASET_STD, + ) + + (h, w), ratio = _shapes((H, W), self.image_shape) + pad_left, pad_right, pad_top, pad_bottom = _paddings((h, w), self.image_shape) + rgbs, gt_intrinsics = _preprocess( + rgbs, + intrinsics, + (h, w), + (pad_left, pad_right, pad_top, pad_bottom), + ratio, + self.image_shape, + ) + + # run encoder + encoder_outputs, cls_tokens = self.pixel_encoder(rgbs) + if "dino" in self.pixel_encoder.__class__.__name__.lower(): + encoder_outputs = [ + (x + y.unsqueeze(1)).contiguous() + for x, y in zip(encoder_outputs, cls_tokens) + ] + + # get data for decoder and adapt to given camera + inputs = {} + inputs["encoder_outputs"] = encoder_outputs + inputs["cls_tokens"] = cls_tokens + inputs["image"] = rgbs + if gt_intrinsics is not None: + rays, angles = generate_rays( + gt_intrinsics, self.image_shape, noisy=self.training + ) + inputs["rays"] = rays + inputs["angles"] = angles + inputs["K"] = gt_intrinsics + self.pixel_decoder.test_fixed_camera = True + self.pixel_decoder.skip_camera = skip_camera + + # decode all + pred_intrinsics, predictions, _ = self.pixel_decoder(inputs, {}) + + # undo the reshaping and get original image size (slow) + predictions, pred_intrinsics = _postprocess( + predictions, + pred_intrinsics, + self.image_shape, + (pad_left, pad_right, pad_top, pad_bottom), + ratio, + (H, W), + ) + + # final 3D points backprojection + intrinsics = gt_intrinsics if gt_intrinsics is not None else pred_intrinsics + angles = generate_rays(intrinsics, (H, W), noisy=False)[-1] + angles = rearrange(angles, "b (h w) c -> b c h w", h=H, w=W) + points_3d = torch.cat((angles, predictions), dim=1) + points_3d = spherical_zbuffer_to_euclidean( + points_3d.permute(0, 2, 3, 1) + ).permute(0, 3, 1, 2) + + # output data + outputs = { + "intrinsics": pred_intrinsics, + "points": points_3d, + "depth": predictions[:, -1:], + } + self.pixel_decoder.test_fixed_camera = False + self.pixel_decoder.skip_camera = False + return outputs + + def load_pretrained(self, model_file): + device = ( + torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") + ) + dict_model = torch.load(model_file, map_location=device) + + if "model" in dict_model: + dict_model = dict_model["model"] + new_state_dict = deepcopy( + {k.replace("module.", ""): v for k, v in dict_model.items()} + ) + + info = self.load_state_dict(new_state_dict, strict=False) + if is_main_process(): + print( + f"Loaded from {model_file} for {self.__class__.__name__} results in:", + info, + ) + + def get_params(self, config): + if hasattr(self.pixel_encoder, "get_params"): + encoder_p, encoder_lr = self.pixel_encoder.get_params( + config["model"]["pixel_encoder"]["lr"], + config["training"]["wd"], + config["training"]["ld"], + ) + else: + encoder_p, encoder_lr = get_params( + self.pixel_encoder, + config["model"]["pixel_encoder"]["lr"], + config["training"]["wd"], + ) + decoder_p, decoder_lr = get_params( + self.pixel_decoder, config["training"]["lr"], config["training"]["wd"] + ) + return [*encoder_p, *decoder_p] + + @property + def device(self): + return next(self.parameters()).device + + def build(self, config): + mod = importlib.import_module("unidepth.models.encoder") + pixel_encoder_factory = getattr(mod, config["model"]["pixel_encoder"]["name"]) + pixel_encoder_config = { + **config["training"], + **config["data"], + **config["model"]["pixel_encoder"], + "interpolate_offset": 0.1, + } + pixel_encoder = pixel_encoder_factory(pixel_encoder_config) + + config["model"]["pixel_encoder"]["patch_size"] = ( + 14 if "dino" in config["model"]["pixel_encoder"]["name"] else 16 + ) + pixel_encoder_embed_dims = ( + pixel_encoder.embed_dims + if hasattr(pixel_encoder, "embed_dims") + else [getattr(pixel_encoder, "embed_dim") * 2**i for i in range(4)] + ) + config["model"]["pixel_encoder"]["embed_dim"] = getattr( + pixel_encoder, "embed_dim" + ) + config["model"]["pixel_encoder"]["embed_dims"] = pixel_encoder_embed_dims + config["model"]["pixel_encoder"]["depths"] = pixel_encoder.depths + + self.pixel_encoder = pixel_encoder + self.pixel_decoder = Decoder(config) + self.image_shape = config["data"]["image_shape"] + + def build_losses(self, config): + self.losses = {} + for loss_name, loss_config in config["training"].get("losses", {}).items(): + mod = importlib.import_module("unidepth.ops.losses") + loss_factory = getattr(mod, loss_config["name"]) + self.losses[loss_name] = loss_factory.build(loss_config) diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/unidepthv2/__init__.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/unidepthv2/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9849539148046b30c53bfac938e2b137839821a0 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/unidepthv2/__init__.py @@ -0,0 +1,7 @@ +from .unidepthv2 import UniDepthV2 +from .unidepthv2_old import UniDepthV2old + +__all__ = [ + "UniDepthV2", + "UniDepthV2old", +] diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/unidepthv2/decoder.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/unidepthv2/decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..f9f557e6d511765d873bff5a64c798f20bed2f4f --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/unidepthv2/decoder.py @@ -0,0 +1,524 @@ +""" +Author: Luigi Piccinelli +Licensed under the CC-BY NC 4.0 license (http://creativecommons.org/licenses/by-nc/4.0/) +""" + +import torch +import torch.nn as nn +import torch.nn.functional as F +from einops import rearrange +from timm.models.layers import trunc_normal_ + +from unidepth.layers import (MLP, AttentionBlock, AttentionLayer, + PositionEmbeddingSine, ResUpsampleBil) +from unidepth.utils.coordinate import coords_grid +from unidepth.utils.geometric import flat_interpolate +from unidepth.utils.positional_embedding import generate_fourier_features + + +def orthonormal_init(num_tokens, dims): + + pe = torch.randn(num_tokens, dims) + + # Apply Gram-Schmidt process to make the matrix orthonormal + for i in range(num_tokens): + for j in range(i): + # Subtract the projection of current row onto previous row + pe[i] -= torch.dot(pe[i], pe[j]) * pe[j] + + # Normalize the current row + pe[i] = F.normalize(pe[i], p=2, dim=0) + + return pe + + +class ListAdapter(nn.Module): + def __init__(self, input_dims: list[int], hidden_dim: int): + super().__init__() + self.input_adapters = nn.ModuleList([]) + self.num_chunks = len(input_dims) + for input_dim in input_dims: + self.input_adapters.append(nn.Linear(input_dim, hidden_dim)) + + def forward(self, xs: torch.Tensor) -> list[torch.Tensor]: + outs = [self.input_adapters[i](x) for i, x in enumerate(xs)] + return outs + + +class CameraHead(nn.Module): + def __init__( + self, + hidden_dim: int, + num_heads: int = 8, + expansion: int = 4, + dropout: float = 0.0, + layer_scale: float = 1.0, + **kwargs, + ): + super().__init__() + self.num_params = 4 + + self.aggregate1 = AttentionBlock( + hidden_dim, + num_heads=num_heads, + expansion=expansion, + dropout=dropout, + layer_scale=layer_scale, + use_bias=False, + ) + self.aggregate2 = AttentionBlock( + hidden_dim, + num_heads=num_heads, + expansion=expansion, + dropout=dropout, + layer_scale=layer_scale, + use_bias=False, + ) + self.latents_pos = nn.Parameter( + torch.randn(1, self.num_params, hidden_dim), requires_grad=True + ) + self.project = MLP( + hidden_dim, expansion=1, dropout=dropout, output_dim=hidden_dim + ) + self.out_pinhole = MLP(hidden_dim, expansion=1, dropout=dropout, output_dim=1) + + def fill_intrinsics(self, x): + fx, fy, cx, cy = x.unbind(dim=-1) + fx = torch.exp(fx) + fy = torch.exp(fy) + cx = torch.sigmoid(cx) + cy = torch.sigmoid(cy) + diagonal = (self.shapes[0] ** 2 + self.shapes[1] ** 2) ** 0.5 + correction_tensor = torch.tensor( + [0.7 * diagonal, 0.7 * diagonal, self.shapes[1], self.shapes[0]], + device=x.device, + dtype=x.dtype, + ) + intrinsics = torch.stack([fx, fy, cx, cy], dim=1) + intrinsics = correction_tensor.unsqueeze(0) * intrinsics + return intrinsics + + def forward(self, features, cls_tokens, pos_embed) -> torch.Tensor: + features = features.unbind(dim=-1) + tokens = self.project(cls_tokens) + + latents_pos = self.latents_pos.expand(cls_tokens.shape[0], -1, -1) + tokens = self.aggregate1(tokens, pos_embed=latents_pos) + tokens = self.aggregate2(tokens, pos_embed=latents_pos) + + x = self.out_pinhole(tokens.clone()).squeeze(-1) + camera_intrinsics = self.fill_intrinsics(x) + return camera_intrinsics + + def set_shapes(self, shapes: tuple[int, int]): + self.shapes = shapes + + +class DepthHead(nn.Module): + def __init__( + self, + hidden_dim: int, + num_heads: int = 8, + expansion: int = 4, + depths: int | list[int] = 4, + camera_dim: int = 256, + dropout: float = 0.0, + kernel_size: int = 7, + layer_scale: float = 1.0, + out_dim: int = 1, + use_norm=False, + num_prompt_blocks=1, + **kwargs, + ) -> None: + super().__init__() + + self.camera_dim = camera_dim + self.out_dim = out_dim + self.hidden_dim = hidden_dim + + self.ups = nn.ModuleList([]) + self.depth_mlp = nn.ModuleList([]) + self.process_features = nn.ModuleList([]) + self.project_features = nn.ModuleList([]) + self.prompt_camera = nn.ModuleList([]) + mult = 2 + self.to_latents = nn.Linear(hidden_dim, hidden_dim) + + for _ in range(4): + self.prompt_camera.append( + AttentionLayer( + num_blocks=num_prompt_blocks, + dim=hidden_dim, + num_heads=num_heads, + expansion=expansion, + dropout=dropout, + layer_scale=-1.0, + context_dim=hidden_dim, + use_bias=False, + ) + ) + + for i, depth in enumerate(depths): + current_dim = min(hidden_dim, mult * hidden_dim // int(2**i)) + next_dim = mult * hidden_dim // int(2 ** (i + 1)) + output_dim = max(next_dim, out_dim) + self.process_features.append( + nn.ConvTranspose2d( + hidden_dim, + current_dim, + kernel_size=max(1, 2 * i), + stride=max(1, 2 * i), + padding=0, + ) + ) + + self.ups.append( + ResUpsampleBil( + current_dim, + output_dim=output_dim, + expansion=expansion, + layer_scale=layer_scale, + kernel_size=kernel_size, + num_layers=depth, + use_norm=use_norm, + ) + ) + + depth_mlp = nn.Identity() + if i == len(depths) - 1: + depth_mlp = nn.Sequential( + nn.LayerNorm(next_dim), nn.Linear(next_dim, output_dim) + ) + + self.depth_mlp.append(depth_mlp) + + self.confidence_mlp = nn.Sequential( + nn.LayerNorm(next_dim), nn.Linear(next_dim, output_dim) + ) + + self.to_depth_lr = nn.Conv2d( + output_dim, + output_dim // 2, + kernel_size=3, + padding=1, + padding_mode="reflect", + ) + self.to_confidence_lr = nn.Conv2d( + output_dim, + output_dim // 2, + kernel_size=3, + padding=1, + padding_mode="reflect", + ) + self.to_depth_hr = nn.Sequential( + nn.Conv2d( + output_dim // 2, 32, kernel_size=3, padding=1, padding_mode="reflect" + ), + nn.LeakyReLU(), + nn.Conv2d(32, 1, kernel_size=1), + ) + self.to_confidence_hr = nn.Sequential( + nn.Conv2d( + output_dim // 2, 32, kernel_size=3, padding=1, padding_mode="reflect" + ), + nn.LeakyReLU(), + nn.Conv2d(32, 1, kernel_size=1), + ) + + def set_original_shapes(self, shapes: tuple[int, int]): + self.original_shapes = shapes + + def set_shapes(self, shapes: tuple[int, int]): + self.shapes = shapes + + def embed_rays(self, rays): + rays_embedding = flat_interpolate( + rays, old=self.original_shapes, new=self.shapes, antialias=True + ) + rays_embedding = rays_embedding / torch.norm( + rays_embedding, dim=-1, keepdim=True + ).clip(min=1e-4) + x, y, z = rays_embedding[..., 0], rays_embedding[..., 1], rays_embedding[..., 2] + polar = torch.acos(z) + x_clipped = x.abs().clip(min=1e-3) * (2 * (x >= 0).int() - 1) + azimuth = torch.atan2(y, x_clipped) + rays_embedding = torch.stack([polar, azimuth], dim=-1) + rays_embedding = generate_fourier_features( + rays_embedding, + dim=self.hidden_dim, + max_freq=max(self.shapes) // 2, + use_log=True, + cat_orig=False, + ) + return rays_embedding + + def condition(self, feat, rays_embeddings): + conditioned_features = [ + prompter(rearrange(feature, "b h w c -> b (h w) c"), rays_embeddings) + for prompter, feature in zip(self.prompt_camera, feat) + ] + return conditioned_features + + def process(self, features_list, rays_embeddings): + conditioned_features = self.condition(features_list, rays_embeddings) + init_latents = self.to_latents(conditioned_features[0]) + init_latents = rearrange( + init_latents, "b (h w) c -> b c h w", h=self.shapes[0], w=self.shapes[1] + ).contiguous() + conditioned_features = [ + rearrange( + x, "b (h w) c -> b c h w", h=self.shapes[0], w=self.shapes[1] + ).contiguous() + for x in conditioned_features + ] + latents = init_latents + + out_features = [] + for i, up in enumerate(self.ups): + latents = latents + self.process_features[i](conditioned_features[i + 1]) + latents = up(latents) + out_features.append(latents) + + return out_features, init_latents + + def depth_proj(self, out_features): + h_out, w_out = out_features[-1].shape[-2:] + # aggregate output and project to depth + for i, (layer, features) in enumerate(zip(self.depth_mlp, out_features)): + out_depth_features = layer(features.permute(0, 2, 3, 1)).permute(0, 3, 1, 2) + out_depth_features = F.interpolate( + out_depth_features, + size=(h_out, w_out), + mode="bilinear", + align_corners=True, + ) + if i == len(self.depth_mlp) - 1: + logdepth = out_depth_features + + logdepth = self.to_depth_lr(logdepth) + logdepth = F.interpolate( + logdepth, size=self.original_shapes, mode="bilinear", align_corners=True + ) + logdepth = self.to_depth_hr(logdepth) + return logdepth + + def confidence_proj(self, out_features): + highres_features = out_features[-1].permute(0, 2, 3, 1) + confidence = self.confidence_mlp(highres_features).permute(0, 3, 1, 2) + confidence = self.to_confidence_lr(confidence) + confidence = F.interpolate( + confidence, size=self.original_shapes, mode="bilinear", align_corners=True + ) + confidence = self.to_confidence_hr(confidence) + return confidence + + def decode(self, out_features): + logdepth = self.depth_proj(out_features) + confidence = self.confidence_proj(out_features) + return logdepth, confidence + + def forward( + self, + features: list[torch.Tensor], + rays_hr: torch.Tensor, + pos_embed, + level_embed, + ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + B = features[0].shape[0] + + rays_embeddings = self.embed_rays(rays_hr) + features, proj_latents_16 = self.process(features, rays_embeddings) + logdepth, logconf = self.decode(features) + + return logdepth, logconf, proj_latents_16 + + +class Decoder(nn.Module): + def __init__( + self, + config, + ): + super().__init__() + self.build(config) + self.apply(self._init_weights) + self.test_gt_camera = False + + def _init_weights(self, m): + if isinstance(m, nn.Linear): + trunc_normal_(m.weight, std=0.02) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.Conv2d): + trunc_normal_(m.weight, std=0.02) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.LayerNorm): + if m.bias is not None: + nn.init.constant_(m.bias, 0) + if m.weight is not None: + nn.init.constant_(m.weight, 1.0) + + def run_camera(self, cls_tokens, features, pos_embed, original_shapes, rays_gt): + H, W = original_shapes + + # camera layer + intrinsics = self.camera_layer( + features=features, cls_tokens=cls_tokens, pos_embed=pos_embed + ) + B, N = intrinsics.shape + device = intrinsics.device + dtype = intrinsics.dtype + + id_coords = coords_grid(B, H, W, device=features.device, homogeneous=True) + intrinsics_matrix_inverse = torch.eye(3, device=device, dtype=dtype).repeat( + B, 1, 1 + ) + intrinsics_matrix_inverse[:, 0, 0] = 1.0 / intrinsics[:, 0] + intrinsics_matrix_inverse[:, 1, 1] = 1.0 / intrinsics[:, 1] + intrinsics_matrix_inverse[:, 0, 2] = -intrinsics[:, 2] / intrinsics[:, 0] + intrinsics_matrix_inverse[:, 1, 2] = -intrinsics[:, 3] / intrinsics[:, 1] + + intrinsics_matrix = torch.eye(3, device=device, dtype=dtype).repeat(B, 1, 1) + intrinsics_matrix[:, 0, 0] = intrinsics[:, 0] + intrinsics_matrix[:, 1, 1] = intrinsics[:, 1] + intrinsics_matrix[:, 0, 2] = intrinsics[:, 2] + intrinsics_matrix[:, 1, 2] = intrinsics[:, 3] + + rays_pred = intrinsics_matrix_inverse @ id_coords.reshape(B, 3, -1) + rays_pred = rays_pred.reshape(B, 3, H, W) + rays_pred = rays_pred / torch.norm(rays_pred, dim=1, keepdim=True).clamp( + min=1e-5 + ) + + ### LEGACY CODE FOR TRAINING + # if self.training and rays_gt is not None: + # prob = -1.0 # 0.8 * (1 - tanh(self.steps / 100000)) + 0.2 + # where_use_gt_rays = torch.rand(B, 1, 1, device=device, dtype=dtype) < prob + # where_use_gt_rays = where_use_gt_rays.int() + # rays = rays_gt * where_use_gt_rays + rays_pred * (1 - where_use_gt_rays) + + rays = rays_pred if rays_gt is None else rays_gt + rays = rearrange(rays, "b c h w -> b (h w) c") + + return intrinsics_matrix, rays + + def forward( + self, + inputs: dict[str, torch.Tensor], + image_metas: list[dict[str, torch.Tensor]], + ) -> dict[str, torch.Tensor]: + B, C, H, W = inputs["image"].shape + device = inputs["image"].device + dtype = inputs["features"][0].dtype + + # get features in b n d format + common_shape = inputs["features"][0].shape[1:3] + + # input shapes repeat shapes for each level, times the amount of the layers: + features = self.input_adapter(inputs["features"]) + + # positional embeddings, spatial and level + level_embed = self.level_embeds.repeat( + B, common_shape[0] * common_shape[1], 1, 1 + ) + level_embed = rearrange(level_embed, "b n l d -> b (n l) d") + dummy_tensor = torch.zeros( + B, 1, common_shape[0], common_shape[1], device=device, requires_grad=False + ) + pos_embed = self.pos_embed(dummy_tensor) + pos_embed = rearrange(pos_embed, "b c h w -> b (h w) c").repeat( + 1, self.num_resolutions, 1 + ) + + # get cls tokens projections + camera_tokens = inputs["tokens"] + camera_tokens = self.camera_token_adapter(camera_tokens) + self.camera_layer.set_shapes((H, W)) + + intrinsics, rays = self.run_camera( + torch.cat(camera_tokens, dim=1), + features=torch.stack(features, dim=-1).detach(), + pos_embed=(pos_embed + level_embed).detach(), + original_shapes=(H, W), + rays_gt=inputs.get("rays", None), + ) + + # run bulk of the model + self.depth_layer.set_shapes(common_shape) + self.depth_layer.set_original_shapes((H, W)) + logdepth, logconfidence, depth_features = self.depth_layer( + features=features, + rays_hr=rays, + pos_embed=pos_embed, + level_embed=level_embed, + ) + + return { + "radius": torch.exp(logdepth.clip(min=-8.0, max=8.0) + 2.0), + "depth_features": depth_features, + "confidence": torch.exp(logconfidence.clip(min=-8.0, max=8.0)), + "intrinsics": intrinsics, + "rays": rays, + } + + @torch.jit.ignore + def no_weight_decay_keywords(self): + return {"latents_pos", "level_embeds"} + + def build(self, config): + input_dims = config["model"]["pixel_encoder"]["embed_dims"] + hidden_dim = config["model"]["pixel_decoder"]["hidden_dim"] + expansion = config["model"]["expansion"] + num_heads = config["model"]["num_heads"] + dropout = config["model"]["pixel_decoder"]["dropout"] + depths_encoder = config["model"]["pixel_encoder"]["depths"] + layer_scale = config["model"]["layer_scale"] + + depth = config["model"]["pixel_decoder"]["depths"] + self.downsample = 4 + depths_encoder = config["model"]["pixel_encoder"]["depths"] + + self.num_resolutions = len(depths_encoder) + self.test_fixed_camera = False + + out_dim = config["model"]["pixel_decoder"]["out_dim"] + kernel_size = config["model"]["pixel_decoder"].get("kernel_size", 7) + + self.slices_encoder = list(zip([d - 1 for d in depths_encoder], depths_encoder)) + input_dims = [input_dims[d - 1] for d in depths_encoder] + + # # adapt from encoder features, just project + camera_dims = input_dims + self.input_adapter = ListAdapter(input_dims, hidden_dim) + self.camera_token_adapter = ListAdapter(camera_dims, hidden_dim) + + # # camera layer + self.camera_layer = CameraHead( + hidden_dim=hidden_dim, + num_heads=num_heads, + expansion=expansion, + dropout=dropout, + layer_scale=layer_scale, + ) + + self.depth_layer = DepthHead( + hidden_dim=hidden_dim, + num_heads=num_heads, + expansion=expansion, + depths=depth, + dropout=dropout, + camera_dim=96, + num_resolutions=self.num_resolutions, + layer_scale=layer_scale, + out_dim=out_dim, + kernel_size=kernel_size, + num_prompt_blocks=1, + use_norm=False, + ) + self.pos_embed = PositionEmbeddingSine(hidden_dim // 2, normalize=True) + self.level_embeds = nn.Parameter( + orthonormal_init(len(input_dims), hidden_dim).reshape( + 1, 1, len(input_dims), hidden_dim + ), + requires_grad=False, + ) diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/unidepthv2/decoder_old.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/unidepthv2/decoder_old.py new file mode 100644 index 0000000000000000000000000000000000000000..45de9ce3f4674a1f9188d0179441fa58b4beab4a --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/unidepthv2/decoder_old.py @@ -0,0 +1,585 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F +from einops import rearrange +from timm.models.layers import trunc_normal_ + +from unidepth.layers import (MLP, AttentionBlock, ConvUpsampleShuffleResidual, + NystromBlock, PositionEmbeddingSine) +from unidepth.utils.geometric import flat_interpolate, generate_rays +from unidepth.utils.positional_embedding import generate_fourier_features + + +class ListAdapter(nn.Module): + def __init__(self, input_dims: list[int], hidden_dim: int): + super().__init__() + self.input_adapters = nn.ModuleList([]) + self.num_chunks = len(input_dims) + self.checkpoint = True + for input_dim in input_dims: + self.input_adapters.append( + nn.Sequential( + nn.LayerNorm(input_dim), nn.Linear(input_dim, hidden_dim), nn.GELU() + ) + ) + + def forward(self, x: torch.Tensor, splits: torch.Tensor) -> torch.Tensor: + xs = torch.split(x, splits.int().tolist(), dim=-1) + xs = [adapter(x) for x, adapter in zip(xs, self.input_adapters)] + return torch.cat(xs, dim=-1) + + +class CameraHead(nn.Module): + def __init__( + self, + hidden_dim: int, + num_heads: int = 8, + expansion: int = 4, + dropout: float = 0.0, + **kwargs, + ): + super().__init__() + self.aggregate1 = AttentionBlock( + hidden_dim, num_heads=1, expansion=expansion, dropout=dropout + ) + self.aggregate2 = AttentionBlock( + hidden_dim, num_heads=1, expansion=expansion, dropout=dropout + ) + self.latents_pos = nn.Parameter( + torch.randn(1, 4, hidden_dim), requires_grad=True + ) + self.in_features = MLP(hidden_dim, expansion=2, dropout=dropout) + self.project_cls = MLP(hidden_dim, dropout=dropout) + self.out = MLP(hidden_dim, expansion=2, dropout=0.0, output_dim=1) + + def fill_intrinsics(self, x): + camera_intrinsics = torch.zeros( + x.shape[0], 3, 3, device=x.device, requires_grad=False + ) + camera_intrinsics[:, 0, 0] = x[:, 0].exp() + camera_intrinsics[:, 1, 1] = x[:, 1].exp() + camera_intrinsics[:, 0, 2] = x[:, 2].sigmoid() + camera_intrinsics[:, 1, 2] = x[:, 3].sigmoid() + camera_intrinsics[:, 2, 2] = 1.0 + return camera_intrinsics + + def forward(self, features, cls_tokens, pos_embed) -> torch.Tensor: + features = features.unbind(dim=-1) + cls_tokens = self.project_cls(cls_tokens) + latents_pos = self.latents_pos.expand(cls_tokens.shape[0], -1, -1) + features = self.in_features(torch.cat(features, dim=1) + pos_embed) + features = torch.cat((features, cls_tokens), dim=1) + cls_tokens = self.aggregate1( + cls_tokens, context=features, pos_embed=latents_pos + ) + cls_tokens = self.aggregate2( + cls_tokens, context=features, pos_embed=latents_pos + ) + + # project to intrinsics + x = self.out(cls_tokens).squeeze(-1) + camera_intrinsics = self.fill_intrinsics(x) + + return camera_intrinsics + + def set_shapes(self, shapes: tuple[int, int]): + self.shapes = shapes + + +class GlobalHead(nn.Module): + def __init__( + self, + hidden_dim: int, + camera_dim: int, + expansion: int = 4, + dropout: float = 0.0, + **kwargs, + ): + super().__init__() + self.camera_dim = camera_dim + self.in_features = nn.Linear(hidden_dim, hidden_dim) + self.project_rays = nn.Linear(camera_dim + 3, hidden_dim) + self.aggregate1 = AttentionBlock( + hidden_dim, num_heads=1, expansion=expansion, dropout=dropout + ) + self.aggregate2 = AttentionBlock( + hidden_dim, num_heads=1, expansion=expansion, dropout=dropout + ) + self.project_cls = MLP(hidden_dim, dropout=dropout) + self.out = MLP(hidden_dim, expansion=2, dropout=0.0, output_dim=1) + + def embed_rays(self, rays, shapes): + rays_embedding = flat_interpolate(rays, old=self.original_shapes, new=shapes) + rays_embedding = F.normalize(rays_embedding, dim=-1) + rays_embedding = generate_fourier_features( + rays_embedding, + dim=self.camera_dim, + max_freq=max(shapes) // 2, + use_log=True, + cat_orig=True, + ) + return rays_embedding + + def set_original_shapes(self, shapes: tuple[int, int]): + self.original_shapes = shapes + + def set_shapes(self, shapes: tuple[int, int]): + self.shapes = shapes + + def get_scaleshift(self, x): + scale, shift = torch.chunk(x, 2, dim=1) + scale = scale.exp().reshape(-1, 1, 1, 1) + shift = shift.reshape(-1, 1, 1, 1) + return scale, shift + + def forward(self, features, cls_tokens, rays) -> torch.Tensor: + features = features.unbind(dim=-1) + cls_tokens = self.project_cls(cls_tokens) + rays_embedding = self.project_rays(self.embed_rays(rays, self.shapes)) + rays_embedding = rays_embedding.repeat(1, len(features), 1) + features = self.in_features(torch.cat(features, dim=1) + rays_embedding) + features = torch.cat((features, cls_tokens), dim=1) + cls_tokens = self.aggregate1(cls_tokens, context=features) + cls_tokens = self.aggregate2(cls_tokens, context=features) + x = self.out(cls_tokens).squeeze(-1) + scale, shift = self.get_scaleshift(x) + return scale, shift + + +class DepthHead(nn.Module): + def __init__( + self, + hidden_dim: int, + num_heads: int = 8, + expansion: int = 4, + depths: int | list[int] = 4, + checkpoint: bool = True, + camera_dim: int = 256, + num_resolutions: int = 4, + dropout: float = 0.0, + **kwargs, + ) -> None: + super().__init__() + self.checkpoint = checkpoint + self.camera_dim = camera_dim + self.skip_depth = False + + self.to_latents = MLP(hidden_dim, expansion=2, dropout=dropout) + self.features_channel_cat = nn.Linear(hidden_dim * num_resolutions, hidden_dim) + self.aggregate_16 = AttentionBlock( + hidden_dim, + num_heads=1, + expansion=expansion, + dropout=dropout, + context_dim=hidden_dim, + ) + self.prompt_camera = AttentionBlock( + hidden_dim, + num_heads=1, + expansion=expansion, + dropout=dropout, + context_dim=hidden_dim, + ) + + self.rays_layers = nn.ModuleList([]) + self.ups = nn.ModuleList([]) + self.process_layers = nn.ModuleList([]) + self.norms, self.out_layers = nn.ModuleList([]), nn.ModuleList([]) + self.depth_mlp, self.confidence_mlp = nn.ModuleList([]), nn.ModuleList([]) + for i, depth in enumerate(depths): + blk_lst = nn.ModuleList([]) + for _ in range(depth): + blk_lst.append( + NystromBlock( + hidden_dim // int(2**i), + num_heads=num_heads // int(2**i), + expansion=expansion, + dropout=dropout, + ) + ) + self.process_layers.append(blk_lst) + self.rays_layers.append(nn.Linear(camera_dim + 3, hidden_dim // int(2**i))) + self.ups.append( + ConvUpsampleShuffleResidual( + hidden_dim // int(2**i), + expansion=expansion, + kernel_size=7, + num_layers=2, + ) + ) + self.depth_mlp.append( + MLP( + input_dim=hidden_dim // int(2 ** (i + 1)), + output_dim=16, + expansion=1, + ) + ) + self.confidence_mlp.append( + MLP( + input_dim=hidden_dim // int(2 ** (i + 1)), + output_dim=16, + expansion=1, + ) + ) + self.to_depth = nn.Conv2d( + 16 * len(depths), 1, 7, padding=3, padding_mode="reflect" + ) + self.to_confidence = nn.Conv2d( + 16 * len(depths), 1, 7, padding=3, padding_mode="reflect" + ) + + def set_original_shapes(self, shapes: tuple[int, int]): + self.original_shapes = shapes + + def set_shapes(self, shapes: tuple[int, int]): + self.shapes = shapes + + def embed_rays(self, rays, shapes): + rays_embedding = flat_interpolate(rays, old=self.original_shapes, new=shapes) + rays_embedding = F.normalize(rays_embedding, dim=-1) + rays_embedding = generate_fourier_features( + rays_embedding, + dim=self.camera_dim, + max_freq=max(shapes) // 2, + use_log=True, + cat_orig=True, + ) + return rays_embedding + + def project_rays(self, rays, shapes): + embedded_rays = [] + for i, layer in enumerate(self.rays_layers): + embedded_rays.append( + layer(self.embed_rays(rays, [(2**i) * x for x in shapes])) + ) + return embedded_rays + + def decode_depth(self, latents_16, rays, shapes): + latents = latents_16 + out_features, depths, confidences = [], [], [] + for i, (up, layers, rays_embedding) in enumerate( + zip(self.ups, self.process_layers, rays) + ): + for layer in layers: + latents = layer(latents, pos_embed=rays_embedding) + latents = up( + rearrange( + latents + rays_embedding, + "b (h w) c -> b c h w", + h=shapes[0] * int(2**i), + w=shapes[1] * int(2**i), + ).contiguous() + ) + out = rearrange( + latents, + "b (h w) c -> b h w c", + h=shapes[0] * int(2 ** (1 + i)), + w=shapes[1] * int(2 ** (1 + i)), + ) + out_features.append(out) + + # aggregate output and project to depth + for i, (layer, features) in enumerate( + zip(self.depth_mlp[::-1], out_features[::-1]) + ): + out_depth_features = layer(features).permute(0, 3, 1, 2) + out_depth_features = F.interpolate( + out_depth_features, size=self.original_shapes, mode="bilinear" + ) + depths.append(out_depth_features) + logdepth = self.to_depth(torch.cat(depths, dim=1)) + + # aggregate output and project to confidences + for i, (layer, features) in enumerate( + zip(self.confidence_mlp[::-1], out_features[::-1]) + ): + out_conf_features = layer(features).permute(0, 3, 1, 2) + out_conf_features = F.interpolate( + out_conf_features, size=self.original_shapes, mode="bilinear" + ) + confidences.append(out_conf_features) + confidence = self.to_confidence(torch.cat(confidences, dim=1)) + + # apply sigmoid ot get conf in [0, 1] + confidence = torch.sigmoid(confidence) + + return logdepth, confidence + + def init_latents(self, features, shapes): + # Generate latents with init as pooled features + features_channels = torch.cat(features, dim=-1) + features_16 = self.features_channel_cat(features_channels) + latents_16 = features_16 + self.to_latents( + flat_interpolate(features_16, old=self.shapes, new=shapes, antialias=False) + ) + return latents_16 + + def forward( + self, features: torch.Tensor, rays_hr: torch.Tensor, pos_embed, level_embed + ) -> torch.Tensor: + B = features.shape[0] + features = features.unbind(dim=-1) + shapes = self.shapes + + # camera_embedding + rays_embeddings = self.project_rays(rays_hr, shapes) + + # Init latents + init_latents_16 = self.init_latents(features, shapes) + + # Aggregate features: F -> D + latents_16 = self.aggregate_16( + init_latents_16, + context=torch.cat(features, dim=1), + pos_embed_context=pos_embed + level_embed, + ) + + # Aggregate camera: D -> D|E + latents_16 = self.prompt_camera(latents_16, context=rays_embeddings[0]) + + # Decode depth + logdepth, confidence = self.decode_depth(latents_16, rays_embeddings, shapes) + + return logdepth, confidence, latents_16 + + +class Decoder(nn.Module): + def __init__( + self, + config, + ): + super().__init__() + self.build(config) + self.apply(self._init_weights) + + def _init_weights(self, m): + if isinstance(m, nn.Linear): + trunc_normal_(m.weight, std=0.02) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.Conv2d): + trunc_normal_(m.weight, std=0.02) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.LayerNorm): + if m.bias is not None: + nn.init.constant_(m.bias, 0) + if m.weight is not None: + nn.init.constant_(m.weight, 1.0) + + def get_adapted_features(self, features_flat, splits): + features_flat_cat = torch.cat(features_flat, dim=-1) + features_projected = self.input_adapter( + features_flat_cat, splits + ) # list [b hw c] shapes + features = torch.chunk(features_projected, splits.shape[0], dim=-1) + return features + + def run_camera(self, cls_tokens, features, pos_embed, original_shapes, rays_gt): + # get cls tokens projections + cls_tokens_splits = torch.tensor( + [x.shape[-1] for x in cls_tokens], + device=features.device, + requires_grad=False, + dtype=features.dtype, + ) + cls_tokens = torch.cat(cls_tokens, dim=-1) + cls_tokens = self.camera_token_adapter(cls_tokens, cls_tokens_splits) + cls_tokens = torch.cat( + torch.chunk(cls_tokens, cls_tokens_splits.shape[0], dim=-1), dim=1 + ) + + # camera layer + intrinsics = self.camera_layer( + features=features, cls_tokens=cls_tokens, pos_embed=pos_embed + ) + intrinsics[:, 0, 0] = max(original_shapes) / 2 * intrinsics[:, 0, 0] + intrinsics[:, 1, 1] = max(original_shapes) / 2 * intrinsics[:, 1, 1] + intrinsics[:, 0, 2] = intrinsics[:, 0, 2] * original_shapes[1] + intrinsics[:, 1, 2] = intrinsics[:, 1, 2] * original_shapes[0] + + rays = ( + rays_gt + if rays_gt is not None + else generate_rays(intrinsics, original_shapes)[0] + ) + return intrinsics, rays + + def run_global(self, cls_tokens, features, rays): + # get cls tokens projections + cls_tokens_splits = torch.tensor( + [x.shape[-1] for x in cls_tokens], + device=features.device, + requires_grad=False, + dtype=torch.float32, + ) + cls_tokens = torch.cat(cls_tokens, dim=-1) + cls_tokens = self.global_token_adapter(cls_tokens, cls_tokens_splits) + cls_tokens = torch.cat( + torch.chunk(cls_tokens, cls_tokens_splits.shape[0], dim=-1), dim=1 + ) + + scale, shift = self.global_layer( + features=features, rays=rays, cls_tokens=cls_tokens + ) + + return scale, shift + + def forward(self, inputs, image_metas) -> torch.Tensor: + B, C, H, W = inputs["image"].shape + device = inputs["image"].device + dtype = inputs["image"].dtype + + # get features in b n d format + # level shapes, the shape per level, for swin like [[128, 128], [64, 64],...], for vit [[32,32]] -> mult times resolutions + level_shapes = sorted( + list(set([tuple([x.shape[1], x.shape[2]]) for x in inputs["features"]])) + )[::-1] + if len(level_shapes) == 1: + level_shapes = level_shapes * self.num_resolutions + input_shapes = [ + level_shapes[i] + for i, (start, end) in enumerate(self.slices_encoder) + for _ in range(end - start) + ] + common_shape = level_shapes[-2] + + # input shapes repeat shapes for each level, times the amount of the layers: + features_flat = [ + flat_interpolate( + rearrange(x, "b h w c -> b (h w) c"), old=input_shape, new=common_shape + ) + for x, input_shape in zip(inputs["features"], input_shapes) + ] + features_splits = torch.tensor( + [x.shape[-1] for x in features_flat], + device=device, + requires_grad=False, + dtype=torch.float32, + ) + features = self.get_adapted_features(features_flat, features_splits) + features = torch.stack(features, dim=-1) + + # positional embeddings, spatial and level + level_embed = torch.cat( + [ + self.level_embed_layer(self.level_embeds)[i : i + 1] + .unsqueeze(0) + .repeat(B, common_shape[0] * common_shape[1], 1) + for i in range(self.num_resolutions) + ], + dim=1, + ) + dummy_tensor = torch.zeros( + B, 1, common_shape[0], common_shape[1], device=device, requires_grad=False + ) + pos_embed = self.pos_embed(dummy_tensor) + pos_embed = rearrange(pos_embed, "b c h w -> b (h w) c").repeat( + 1, self.num_resolutions, 1 + ) + + self.camera_layer.set_shapes(common_shape) + intrinsics, rays = self.run_camera( + inputs["camera_tokens"], + features=features, + pos_embed=pos_embed + level_embed, + original_shapes=(H, W), + rays_gt=inputs.get("rays"), + ) + + self.global_layer.set_shapes(common_shape) + self.global_layer.set_original_shapes((H, W)) + scale, shift = self.run_global( + inputs["global_tokens"], features=features, rays=rays + ) + + # run bulk of the model + self.depth_layer.set_shapes(common_shape) + self.depth_layer.set_original_shapes((H, W)) + logdepth, confidence, depth_features = self.depth_layer( + features=features, + rays_hr=rays, + pos_embed=pos_embed, + level_embed=level_embed, + ) + logdepth = logdepth.to(torch.float32, non_blocking=True) + + # norm in log space, why performs better? + shapes = [int(x) for x in logdepth.shape[-2:]] + depth_normalized = F.layer_norm(logdepth, shapes).exp() + + depth = ( + depth_normalized + shift + ) * scale # shift is scale invariant if we do (x + mu) * sigma + depth = F.softplus(depth, beta=10.0).to(dtype, non_blocking=True) + + outputs = { + "depth": depth, + "confidence": confidence, + "depth_features": depth_features, + "K": intrinsics, + } + return outputs + + @torch.jit.ignore + def no_weight_decay_keywords(self): + return {"latents_pos", "level_embeds"} + + def build(self, config): + input_dims = config["model"]["pixel_encoder"]["embed_dims"] + hidden_dim = config["model"]["pixel_decoder"]["hidden_dim"] + expansion = config["model"]["expansion"] + num_heads = config["model"]["num_heads"] + dropout = config["model"]["pixel_decoder"]["dropout"] + depths_encoder = config["model"]["pixel_encoder"]["depths"] + depth = config["model"]["pixel_decoder"]["depths"] + depths_encoder = config["model"]["pixel_encoder"]["depths"] + self.downsample = 4 + self.num_resolutions = len(depths_encoder) + + self.slices_encoder = list(zip([d - 1 for d in depths_encoder], depths_encoder)) + cls_token_input_dims = [input_dims[i] for i in [-1, -2, -3, -4]] + input_dims = [input_dims[d - 1] for d in depths_encoder] + + # # camera layer + self.camera_layer = CameraHead( + hidden_dim=hidden_dim, + num_heads=num_heads, + expansion=expansion, + dropout=dropout, + ) + + # # scale shift layer + self.global_layer = GlobalHead( + hidden_dim=hidden_dim, + camera_dim=96, + num_heads=num_heads, + expansion=expansion, + dropout=dropout, + ) + + # # adapt from encoder features, just project + self.input_adapter = ListAdapter(input_dims, hidden_dim) + self.camera_token_adapter = ListAdapter(cls_token_input_dims, hidden_dim) + self.global_token_adapter = ListAdapter(cls_token_input_dims[:2], hidden_dim) + + self.depth_layer = DepthHead( + hidden_dim=hidden_dim, + num_heads=num_heads, + expansion=expansion, + depths=depth, + dropout=dropout, + camera_dim=96, + num_resolutions=self.num_resolutions, + ) + + self.pos_embed = PositionEmbeddingSine(hidden_dim // 2, normalize=True) + self.level_embeds = nn.Parameter( + torch.randn(len(input_dims), hidden_dim), requires_grad=True + ) + self.level_embed_layer = nn.Sequential( + nn.Linear(hidden_dim, hidden_dim), + nn.GELU(), + nn.Linear(hidden_dim, hidden_dim), + nn.LayerNorm(hidden_dim), + ) diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/unidepthv2/export.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/unidepthv2/export.py new file mode 100644 index 0000000000000000000000000000000000000000..9792f4af927e970f76903f959572087e80c3fa28 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/unidepthv2/export.py @@ -0,0 +1,172 @@ +""" +Author: Luigi Piccinelli +Licensed under the CC-BY NC 4.0 license (http://creativecommons.org/licenses/by-nc/4.0/) +""" + +import argparse +import json +import os +from math import ceil + +import huggingface_hub +import torch.nn.functional as F +import torch.onnx + +from unidepth.models.unidepthv2 import UniDepthV2 + + +class UniDepthV2ONNX(UniDepthV2): + def __init__( + self, + config, + eps: float = 1e-6, + **kwargs, + ): + super().__init__(config, eps) + + def forward(self, rgbs): + B, _, H, W = rgbs.shape + features, tokens = self.pixel_encoder(rgbs) + + inputs = {} + inputs["image"] = rgbs + inputs["features"] = [ + self.stacking_fn(features[i:j]).contiguous() + for i, j in self.slices_encoder_range + ] + inputs["tokens"] = [ + self.stacking_fn(tokens[i:j]).contiguous() + for i, j in self.slices_encoder_range + ] + outputs = self.pixel_decoder(inputs, []) + outputs["rays"] = outputs["rays"].permute(0, 2, 1).reshape(B, 3, H, W) + pts_3d = outputs["rays"] * outputs["radius"] + + return pts_3d, outputs["confidence"], outputs["intrinsics"] + + +class UniDepthV2ONNXcam(UniDepthV2): + def __init__( + self, + config, + eps: float = 1e-6, + **kwargs, + ): + super().__init__(config, eps) + + def forward(self, rgbs, rays): + B, _, H, W = rgbs.shape + features, tokens = self.pixel_encoder(rgbs) + + inputs = {} + inputs["image"] = rgbs + inputs["rays"] = rays + inputs["features"] = [ + self.stacking_fn(features[i:j]).contiguous() + for i, j in self.slices_encoder_range + ] + inputs["tokens"] = [ + self.stacking_fn(tokens[i:j]).contiguous() + for i, j in self.slices_encoder_range + ] + outputs = self.pixel_decoder(inputs, []) + outputs["rays"] = outputs["rays"].permute(0, 2, 1).reshape(B, 3, H, W) + pts_3d = outputs["rays"] * outputs["radius"] + + return pts_3d, outputs["confidence"], outputs["intrinsics"] + + + +def export(model, path, shape=(462, 630), with_camera=False): + model.eval() + image = torch.rand(1, 3, *shape) + dynamic_axes_in = {"rgbs": {0: "batch"}} + inputs = [image] + if with_camera: + rays = torch.rand(1, 3, *shape) + inputs.append(rays) + dynamic_axes_in["rays"] = {0: "batch"} + + dynamic_axes_out = { + "pts_3d": {0: "batch"}, + "confidence": {0: "batch"}, + "intrinsics": {0: "batch"}, + } + torch.onnx.export( + model, + tuple(inputs), + path, + input_names=list(dynamic_axes_in.keys()), + output_names=list(dynamic_axes_out.keys()), + opset_version=14, + dynamic_axes={**dynamic_axes_in, **dynamic_axes_out}, + ) + print(f"Model exported to {path}") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Export UniDepthV2 model to ONNX") + parser.add_argument( + "--version", type=str, default="v2", choices=["v2"], help="UniDepth version" + ) + parser.add_argument( + "--backbone", + type=str, + default="vitl", + choices=["vits", "vitb", "vitl"], + help="Backbone model", + ) + parser.add_argument( + "--shape", + type=int, + nargs=2, + default=(462, 630), + help="Input shape. No dyamic shape supported!", + ) + parser.add_argument( + "--output-path", type=str, default="unidepthv2.onnx", help="Output ONNX file" + ) + parser.add_argument( + "--with-camera", + action="store_true", + help="Export model that expects GT camera as unprojected rays at inference", + ) + args = parser.parse_args() + + version = args.version + backbone = args.backbone + shape = args.shape + output_path = args.output_path + with_camera = args.with_camera + + # force shape to be multiple of 14 + shape_rounded = [14 * ceil(x // 14 - 0.5) for x in shape] + if list(shape) != list(shape_rounded): + print(f"Shape {shape} is not multiple of 14. Rounding to {shape_rounded}") + shape = shape_rounded + + # assumes command is from root of repo + with open(os.path.join("configs", f"config_{version}_{backbone}14.json")) as f: + config = json.load(f) + + # tell DINO not to use efficient attention: not exportable + config["training"]["export"] = True + + model = UniDepthV2ONNX(config) if not with_camera else UniDepthV2ONNXcam(config) + path = huggingface_hub.hf_hub_download( + repo_id=f"lpiccinelli/unidepth-{version}-{backbone}14", + filename=f"pytorch_model.bin", + repo_type="model", + ) + info = model.load_state_dict(torch.load(path), strict=False) + print(f"UniDepth_{version}_{backbone} is loaded with:") + print(f"\t missing keys: {info.missing_keys}") + print(f"\t additional keys: {info.unexpected_keys}") + + export( + model=model, + path=os.path.join(os.environ.get("TMPDIR", "."), output_path), + shape=shape, + with_camera=with_camera, + ) + diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/unidepthv2/unidepthv2.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/unidepthv2/unidepthv2.py new file mode 100644 index 0000000000000000000000000000000000000000..c2a94533e12e177e98532d687e87ee9b9349c39e --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/unidepthv2/unidepthv2.py @@ -0,0 +1,467 @@ +""" +Author: Luigi Piccinelli +Licensed under the CC-BY NC 4.0 license (http://creativecommons.org/licenses/by-nc/4.0/) +""" + +import importlib +from copy import deepcopy +from math import ceil +import warnings + +import torch +import torch.nn as nn +import torch.nn.functional as F +import torchvision.transforms.v2.functional as TF +from einops import rearrange +from huggingface_hub import PyTorchModelHubMixin + +from unidepth.models.unidepthv2.decoder import Decoder +from unidepth.utils.camera import BatchCamera, Camera, Pinhole +from unidepth.utils.constants import (IMAGENET_DATASET_MEAN, + IMAGENET_DATASET_STD) +from unidepth.utils.distributed import is_main_process +from unidepth.utils.misc import (first_stack, get_params, last_stack, match_gt, + match_intrinsics, max_stack, mean_stack, + softmax_stack) + +STACKING_FNS = { + "max": max_stack, + "mean": mean_stack, + "first": first_stack, + "last": last_stack, + "softmax": softmax_stack, +} + + +def get_paddings(original_shape, aspect_ratio_range): + # Original dimensions + H_ori, W_ori = original_shape + orig_aspect_ratio = W_ori / H_ori + + # Determine the closest aspect ratio within the range + min_ratio, max_ratio = aspect_ratio_range + target_aspect_ratio = min(max_ratio, max(min_ratio, orig_aspect_ratio)) + + if orig_aspect_ratio > target_aspect_ratio: # Too wide + W_new = W_ori + H_new = int(W_ori / target_aspect_ratio) + pad_top = (H_new - H_ori) // 2 + pad_bottom = H_new - H_ori - pad_top + pad_left, pad_right = 0, 0 + else: # Too tall + H_new = H_ori + W_new = int(H_ori * target_aspect_ratio) + pad_left = (W_new - W_ori) // 2 + pad_right = W_new - W_ori - pad_left + pad_top, pad_bottom = 0, 0 + + return (pad_left, pad_right, pad_top, pad_bottom), (H_new, W_new) + + +def get_resize_factor(original_shape, pixels_range, shape_multiplier=14): + # Original dimensions + H_ori, W_ori = original_shape + n_pixels_ori = W_ori * H_ori + + # Determine the closest number of pixels within the range + min_pixels, max_pixels = pixels_range + target_pixels = min(max_pixels, max(min_pixels, n_pixels_ori)) + + # Calculate the resize factor + resize_factor = (target_pixels / n_pixels_ori) ** 0.5 + new_width = int(W_ori * resize_factor) + new_height = int(H_ori * resize_factor) + new_height = ceil(new_height / shape_multiplier) * shape_multiplier + new_width = ceil(new_width / shape_multiplier) * shape_multiplier + + return resize_factor, (new_height, new_width) + + +def _postprocess(tensor, shapes, paddings, interpolation_mode="bilinear"): + # interpolate to original size + tensor = F.interpolate( + tensor, size=shapes, mode=interpolation_mode, align_corners=False + ) + + # remove paddings + pad1_l, pad1_r, pad1_t, pad1_b = paddings + tensor = tensor[..., pad1_t : shapes[0] - pad1_b, pad1_l : shapes[1] - pad1_r] + return tensor + + +def _postprocess_intrinsics(K, resize_factors, paddings): + batch_size = K.shape[0] + K_new = K.clone() + + for i in range(batch_size): + scale = resize_factors[i] + pad_l, _, pad_t, _ = paddings[i] + + K_new[i, 0, 0] /= scale # fx + K_new[i, 1, 1] /= scale # fy + K_new[i, 0, 2] /= scale # cx + K_new[i, 1, 2] /= scale # cy + + K_new[i, 0, 2] -= pad_l # cx + K_new[i, 1, 2] -= pad_t # cy + + return K_new + + +class UniDepthV2( + nn.Module, + PyTorchModelHubMixin, + library_name="UniDepth", + repo_url="https://github.com/lpiccinelli-eth/UniDepth", + tags=["monocular-metric-depth-estimation"], +): + def __init__( + self, + config, + eps: float = 1e-6, + **kwargs, + ): + super().__init__() + self.eps = eps + self.build(config) + self.build_losses(config) + + def forward_train(self, inputs, image_metas): + inputs, outputs = self.encode_decode(inputs, image_metas) + losses = self.compute_losses(outputs, inputs, image_metas) + return outputs, losses + + def forward_test(self, inputs, image_metas): + inputs, outputs = self.encode_decode(inputs, image_metas) + depth_gt = inputs["depth"] + test_outputs = {} + test_outputs["depth"] = match_gt( + outputs["depth"], depth_gt, padding1=inputs["paddings"], padding2=None + ) + test_outputs["points"] = match_gt( + outputs["points"], depth_gt, padding1=inputs["paddings"], padding2=None + ) + test_outputs["confidence"] = match_gt( + outputs["confidence"], depth_gt, padding1=inputs["paddings"], padding2=None + ) + test_outputs["rays"] = match_gt( + outputs["rays"], depth_gt, padding1=inputs["paddings"], padding2=None + ) + test_outputs["rays"] = outputs["rays"] / torch.norm( + outputs["rays"], dim=1, keepdim=True + ).clip(min=1e-5) + test_outputs["intrinsics"] = match_intrinsics( + outputs["intrinsics"], + inputs["image"], + depth_gt, + padding1=inputs["paddings"], + padding2=None, + ) + return test_outputs + + def forward(self, inputs, image_metas): + if self.training: + return self.forward_train(inputs, image_metas) + else: + return self.forward_test(inputs, image_metas) + + def compute_losses(self, outputs, inputs, image_metas): + B, _, H, W = inputs["image"].shape + losses = {"opt": {}, "stat": {}} + losses_to_be_computed = list(self.losses.keys()) + + # depth loss + si = torch.tensor( + [x.get("si", False) for x in image_metas], device=self.device + ).reshape(B) + loss = self.losses["depth"] + depth_losses = loss( + outputs["depth"], + target=inputs["depth"], + mask=inputs["depth_mask"].clone(), + si=si, + ) + losses["opt"][loss.name] = loss.weight * depth_losses.mean() + losses_to_be_computed.remove("depth") + + # camera loss, here we apply to rays for simplicity + # in the original training was on angles + # however, we saw no difference (see supplementary) + loss = self.losses["camera"] + camera_losses = loss(outputs["rays"], target=inputs["rays"]) + losses["opt"][loss.name] = loss.weight * camera_losses.mean() + losses_to_be_computed.remove("camera") + + # invariance loss on output depth + flips = torch.tensor( + [x.get("flip", False) for x in image_metas], device=self.device + ).reshape(B) + loss = self.losses["invariance"] + invariance_losses = loss( + outputs["depth"], + intrinsics=inputs["camera"].K, + mask=inputs["depth_mask"], + flips=flips, + downsample_ratio=1, + ) + losses["opt"][loss.name] = loss.weight * invariance_losses.mean() + losses_to_be_computed.remove("invariance") + + # edge guided ssi + loss = self.losses["ssi"] + ssi_losses = loss( + outputs["depth"], + target=inputs["depth"], + mask=inputs["depth_mask"].clone(), + image=inputs["image"], + validity_mask=inputs["validity_mask"], + ) + losses["opt"][loss.name] = loss.weight * ssi_losses.mean() + losses_to_be_computed.remove("ssi") + + # remaining losses, we expect no more losses to be computed + loss = self.losses["confidence"] + conf_losses = loss( + outputs["confidence"].log(), + target_gt=inputs["depth"], + target_pred=outputs["depth"], + mask=inputs["depth_mask"].clone(), + ) + losses["opt"][loss.name + "_conf"] = loss.weight * conf_losses.mean() + losses_to_be_computed.remove("confidence") + + assert ( + not losses_to_be_computed + ), f"Losses {losses_to_be_computed} not computed, revise `compute_loss` method" + + return losses + + @torch.no_grad() + @torch.autocast(device_type="cuda", enabled=True, dtype=torch.float16) + def infer( + self, + rgb: torch.Tensor, + camera: torch.Tensor | Camera | None = None, + normalize=True, + ): + ratio_bounds = self.shape_constraints["ratio_bounds"] + pixels_bounds = [ + self.shape_constraints["pixels_min"], + self.shape_constraints["pixels_max"], + ] + if hasattr(self, "resolution_level"): + assert ( + self.resolution_level >= 0 and self.resolution_level < 10 + ), "resolution_level should be in [0, 10)" + pixels_range = pixels_bounds[1] - pixels_bounds[0] + interval = pixels_range / 10 + new_lowbound = self.resolution_level * interval + pixels_bounds[0] + new_upbound = (self.resolution_level + 1) * interval + pixels_bounds[0] + pixels_bounds = (new_lowbound, new_upbound) + else: + warnings.warn("!! self.resolution_level not set, using default bounds !!") + + # houskeeping on cpu/cuda and batchify + if rgb.ndim == 3: + rgb = rgb.unsqueeze(0) + if camera is not None: + if isinstance(camera, torch.Tensor): + assert ( + camera.shape[-1] == 3 and camera.shape[-2] == 3 + ), "camera tensor should be of shape (..., 3, 3): assume pinhole" + camera = Pinhole(K=camera) + camera = BatchCamera.from_camera(camera) + camera = camera.to(self.device) + B, _, H, W = rgb.shape + + rgb = rgb.to(self.device) + if camera is not None: + camera = camera.to(self.device) + + # preprocess + paddings, (padded_H, padded_W) = get_paddings((H, W), ratio_bounds) + (pad_left, pad_right, pad_top, pad_bottom) = paddings + resize_factor, (new_H, new_W) = get_resize_factor( + (padded_H, padded_W), pixels_bounds + ) + # -> rgb preprocess (input std-ized and resized) + if normalize: + rgb = TF.normalize( + rgb.float() / 255.0, + mean=IMAGENET_DATASET_MEAN, + std=IMAGENET_DATASET_STD, + ) + rgb = F.pad(rgb, (pad_left, pad_right, pad_top, pad_bottom), value=0.0) + rgb = F.interpolate( + rgb, size=(new_H, new_W), mode="bilinear", align_corners=False + ) + # -> camera preprocess + if camera is not None: + camera = camera.crop( + left=-pad_left, top=-pad_top, right=-pad_right, bottom=-pad_bottom + ) + camera = camera.resize(resize_factor) + + # run model + _, model_outputs = self.encode_decode( + inputs={"image": rgb, "camera": camera}, image_metas=[] + ) + + # collect outputs + out = {} + out["confidence"] = _postprocess( + model_outputs["confidence"], + (padded_H, padded_W), + paddings=paddings, + interpolation_mode=self.interpolation_mode, + ) + points = _postprocess( + model_outputs["points"], + (padded_H, padded_W), + paddings=paddings, + interpolation_mode=self.interpolation_mode, + ) + rays = _postprocess( + model_outputs["rays"], + (padded_H, padded_W), + paddings=paddings, + interpolation_mode=self.interpolation_mode, + ) + out["intrinsics"] = _postprocess_intrinsics( + model_outputs["intrinsics"], [resize_factor] * B, [paddings] * B + ) + + out["radius"] = points.norm(dim=1, keepdim=True) + out["depth"] = points[:, -1:] + out["points"] = points + out["rays"] = rays / torch.norm(rays, dim=1, keepdim=True).clip(min=1e-5) + out["depth_features"] = model_outputs["depth_features"] + return out + + def encode_decode(self, inputs, image_metas=[]): + B, _, H, W = inputs["image"].shape + + # shortcut eval should avoid errors + if len(image_metas) and "paddings" in image_metas[0]: + inputs["paddings"] = torch.tensor( + [image_meta["paddings"] for image_meta in image_metas], + device=self.device, + )[ + ..., [0, 2, 1, 3] + ] # lrtb + inputs["depth_paddings"] = torch.tensor( + [image_meta["depth_paddings"] for image_meta in image_metas], + device=self.device, + ) + if ( + self.training + ): # at inference we do not have image paddings on top of depth ones (we have not "crop" on gt in ContextCrop) + inputs["depth_paddings"] = inputs["depth_paddings"] + inputs["paddings"] + + if inputs.get("camera", None) is not None: + inputs["rays"] = inputs["camera"].get_rays(shapes=(B, H, W)) + + features, tokens = self.pixel_encoder(inputs["image"]) + inputs["features"] = [ + self.stacking_fn(features[i:j]).contiguous() + for i, j in self.slices_encoder_range + ] + inputs["tokens"] = [ + self.stacking_fn(tokens[i:j]).contiguous() + for i, j in self.slices_encoder_range + ] + + outputs = self.pixel_decoder(inputs, image_metas) + outputs["rays"] = rearrange(outputs["rays"], "b (h w) c -> b c h w", h=H, w=W) + pts_3d = outputs["rays"] * outputs["radius"] + outputs.update({"points": pts_3d, "depth": pts_3d[:, -1:]}) + + return inputs, outputs + + def load_pretrained(self, model_file): + device = ( + torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") + ) + dict_model = torch.load(model_file, map_location=device, weights_only=False) + if "model" in dict_model: + dict_model = dict_model["model"] + dict_model = {k.replace("module.", ""): v for k, v in dict_model.items()} + info = self.load_state_dict(dict_model, strict=False) + if is_main_process(): + print( + f"Loaded from {model_file} for {self.__class__.__name__} results in:", + info, + ) + + def get_params(self, config): + if hasattr(self.pixel_encoder, "get_params"): + encoder_p, encoder_lr = self.pixel_encoder.get_params( + config["model"]["pixel_encoder"]["lr"], + config["training"]["wd"], + config["training"]["ld"], + ) + else: + encoder_p, encoder_lr = get_params( + self.pixel_encoder, + config["model"]["pixel_encoder"]["lr"], + config["training"]["wd"], + ) + decoder_p, decoder_lr = get_params( + self.pixel_decoder, config["training"]["lr"], config["training"]["wd"] + ) + return [*encoder_p, *decoder_p] + + @property + def device(self): + return next(self.parameters()).device + + def build(self, config): + mod = importlib.import_module("unidepth.models.encoder") + pixel_encoder_factory = getattr(mod, config["model"]["pixel_encoder"]["name"]) + pixel_encoder_config = { + **config["training"], + **config["model"]["pixel_encoder"], + **config["data"], + } + pixel_encoder = pixel_encoder_factory(pixel_encoder_config) + + config["model"]["pixel_encoder"]["patch_size"] = ( + 14 if "dino" in config["model"]["pixel_encoder"]["name"] else 16 + ) + pixel_encoder_embed_dims = ( + pixel_encoder.embed_dims + if hasattr(pixel_encoder, "embed_dims") + else [getattr(pixel_encoder, "embed_dim") * 2**i for i in range(4)] + ) + config["model"]["pixel_encoder"]["embed_dim"] = getattr( + pixel_encoder, "embed_dim" + ) + config["model"]["pixel_encoder"]["embed_dims"] = pixel_encoder_embed_dims + config["model"]["pixel_encoder"]["depths"] = pixel_encoder.depths + config["model"]["pixel_encoder"]["cls_token_embed_dims"] = getattr( + pixel_encoder, "cls_token_embed_dims", pixel_encoder_embed_dims + ) + + pixel_decoder = Decoder(config) + + self.pixel_encoder = pixel_encoder + self.pixel_decoder = pixel_decoder + + self.slices_encoder_range = list( + zip([0, *self.pixel_encoder.depths[:-1]], self.pixel_encoder.depths) + ) + + stacking_fn = config["model"]["pixel_encoder"]["stacking_fn"] + assert ( + stacking_fn in STACKING_FNS + ), f"Stacking function {stacking_fn} not found in {STACKING_FNS.keys()}" + self.stacking_fn = STACKING_FNS[stacking_fn] + self.shape_constraints = config["data"]["augmentations"]["shape_constraints"] + self.interpolation_mode = "bilinear" + + def build_losses(self, config): + self.losses = {} + for loss_name, loss_config in config["training"]["losses"].items(): + mod = importlib.import_module("unidepth.ops.losses") + loss_factory = getattr(mod, loss_config["name"]) + self.losses[loss_name] = loss_factory.build(loss_config) diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/unidepthv2/unidepthv2_old.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/unidepthv2/unidepthv2_old.py new file mode 100644 index 0000000000000000000000000000000000000000..b6933d2c418673222980790b9affab1930346b72 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/models/unidepthv2/unidepthv2_old.py @@ -0,0 +1,356 @@ +import importlib +import warnings +from copy import deepcopy +from math import ceil + +import torch +import torch.nn as nn +import torch.nn.functional as F +import torchvision.transforms.functional as TF +from einops import rearrange +from huggingface_hub import PyTorchModelHubMixin + +from unidepth.models.unidepthv2.decoder_old import Decoder +from unidepth.utils.constants import (IMAGENET_DATASET_MEAN, + IMAGENET_DATASET_STD) +from unidepth.utils.distributed import is_main_process +from unidepth.utils.geometric import (generate_rays, + spherical_zbuffer_to_euclidean) +from unidepth.utils.misc import (first_stack, last_stack, max_stack, + mean_stack, softmax_stack) + +STACKING_FNS = { + "max": max_stack, + "mean": mean_stack, + "first": first_stack, + "last": last_stack, + "softmax": softmax_stack, +} +RESOLUTION_LEVELS = 10 + + +# inference helpers +def _check_ratio(image_ratio, ratio_bounds): + ratio_bounds = sorted(ratio_bounds) + if ratio_bounds is not None and ( + image_ratio < ratio_bounds[0] or image_ratio > ratio_bounds[1] + ): + warnings.warn( + f"Input image ratio ({image_ratio:.3f}) is out of training " + f"distribution: {ratio_bounds}. This may lead to unexpected results. " + f"Consider resizing/padding the image to match the training distribution." + ) + + +def _check_resolution(shape_constraints, resolution_level): + if resolution_level is None: + warnings.warn( + "Resolution level is not set. Using max resolution. " + "You can tradeoff resolution for speed by setting a number in [0,10]. " + "This can be achieved by setting model's `resolution_level` attribute." + ) + resolution_level = RESOLUTION_LEVELS + pixel_bounds = sorted(shape_constraints["pixels_bounds_ori"]) + pixel_range = pixel_bounds[-1] - pixel_bounds[0] + clipped_resolution_level = min(max(resolution_level, 0), RESOLUTION_LEVELS) + if clipped_resolution_level != resolution_level: + warnings.warn( + f"Resolution level {resolution_level} is out of bounds ([0,{RESOLUTION_LEVELS}]). " + f"Clipping to {clipped_resolution_level}." + ) + shape_constraints["pixels_bounds"] = [ + pixel_bounds[0] + + ceil(pixel_range * clipped_resolution_level / RESOLUTION_LEVELS), + pixel_bounds[0] + + ceil(pixel_range * clipped_resolution_level / RESOLUTION_LEVELS), + ] + return shape_constraints + + +def _get_closes_num_pixels(image_shape, pixels_bounds): + h, w = image_shape + num_pixels = h * w + pixels_bounds = sorted(pixels_bounds) + num_pixels = max(min(num_pixels, pixels_bounds[1]), pixels_bounds[0]) + return num_pixels + + +def _shapes(image_shape, shape_constraints): + h, w = image_shape + image_ratio = w / h + _check_ratio(image_ratio, shape_constraints["ratio_bounds"]) + num_pixels = _get_closes_num_pixels( + (h / shape_constraints["patch_size"], w / shape_constraints["patch_size"]), + shape_constraints["pixels_bounds"], + ) + h = ceil((num_pixels / image_ratio) ** 0.5 - 0.5) + w = ceil(h * image_ratio - 0.5) + ratio = h / image_shape[0] * shape_constraints["patch_size"] + return ( + h * shape_constraints["patch_size"], + w * shape_constraints["patch_size"], + ), ratio + + +def _preprocess(rgbs, intrinsics, shapes, ratio): + rgbs = F.interpolate(rgbs, size=shapes, mode="bilinear", antialias=True) + if intrinsics is not None: + intrinsics = intrinsics.clone() + intrinsics[:, 0, 0] = intrinsics[:, 0, 0] * ratio + intrinsics[:, 1, 1] = intrinsics[:, 1, 1] * ratio + intrinsics[:, 0, 2] = intrinsics[:, 0, 2] * ratio + intrinsics[:, 1, 2] = intrinsics[:, 1, 2] * ratio + return rgbs, intrinsics + return rgbs, None + + +def _postprocess(outs, ratio, original_shapes, mode="nearest-exact"): + outs["depth"] = F.interpolate(outs["depth"], size=original_shapes, mode=mode) + outs["confidence"] = F.interpolate( + outs["confidence"], size=original_shapes, mode="bilinear", antialias=True + ) + outs["K"][:, 0, 0] = outs["K"][:, 0, 0] / ratio + outs["K"][:, 1, 1] = outs["K"][:, 1, 1] / ratio + outs["K"][:, 0, 2] = outs["K"][:, 0, 2] / ratio + outs["K"][:, 1, 2] = outs["K"][:, 1, 2] / ratio + return outs + + +class UniDepthV2old( + nn.Module, + PyTorchModelHubMixin, + library_name="UniDepth", + repo_url="https://github.com/lpiccinelli-eth/UniDepth", + tags=["monocular-metric-depth-estimation"], +): + def __init__( + self, + config, + **kwargs, + ): + super().__init__() + self.build(config) + + def forward(self, inputs, image_metas): + H, W = inputs["depth"].shape[-2:] + + if "K" in inputs: + rays, angles = generate_rays(inputs["K"], (H, W)) + inputs["rays"] = rays + inputs["angles"] = angles + + features, tokens = self.pixel_encoder(inputs[f"image"]) + + cls_tokens = [x.contiguous() for x in tokens] + features = [ + self.stacking_fn(features[i:j]).contiguous() + for i, j in self.slices_encoder_range + ] + tokens = [ + self.stacking_fn(tokens[i:j]).contiguous() + for i, j in self.slices_encoder_range + ] + global_tokens = [cls_tokens[i] for i in [-2, -1]] + camera_tokens = [cls_tokens[i] for i in [-3, -2, -1]] + [tokens[-2]] + + inputs["features"] = features + inputs["tokens"] = tokens + inputs["global_tokens"] = global_tokens + inputs["camera_tokens"] = camera_tokens + + outs = self.pixel_decoder(inputs, image_metas) + + angles = rearrange( + generate_rays(outs["K"], (H, W), noisy=False)[-1], + "b (h w) c -> b c h w", + h=H, + w=W, + ) + predictions = F.interpolate( + outs["depth"], + size=(H, W), + mode="bilinear", + align_corners=False, + antialias=True, + ) + confidence = F.interpolate( + outs["confidence"], + size=(H, W), + mode="bilinear", + align_corners=False, + antialias=True, + ) + predictions_3d = torch.cat((angles, predictions), dim=1) + predictions_3d = spherical_zbuffer_to_euclidean( + predictions_3d.permute(0, 2, 3, 1) + ).permute(0, 3, 1, 2) + + outputs = { + "K": outs["K"], + "depth": predictions, + "confidence": confidence, + "points": predictions_3d, + "depth_features": outs["depth_features"], + } + return outputs + + @torch.no_grad() + def infer(self, rgbs: torch.Tensor, intrinsics=None): + shape_constraints = self.shape_constraints + if rgbs.ndim == 3: + rgbs = rgbs.unsqueeze(0) + if intrinsics is not None and intrinsics.ndim == 2: + intrinsics = intrinsics.unsqueeze(0) + B, _, H, W = rgbs.shape + + rgbs = rgbs.to(self.device) + if intrinsics is not None: + intrinsics = intrinsics.to(self.device) + + # process image and intrinsiscs (if any) to match network input (slow?) + if rgbs.max() > 5 or rgbs.dtype == torch.uint8: + rgbs = rgbs.to(torch.float32).div(255) + if rgbs.min() >= 0.0 and rgbs.max() <= 1.0: + rgbs = TF.normalize( + rgbs, + mean=IMAGENET_DATASET_MEAN, + std=IMAGENET_DATASET_STD, + ) + + # check resolution constraints: tradeoff resolution and speed + shape_constraints = _check_resolution(shape_constraints, self.resolution_level) + + # get image shape + (h, w), ratio = _shapes((H, W), shape_constraints) + rgbs, gt_intrinsics = _preprocess( + rgbs, + intrinsics, + (h, w), + ratio, + ) + + # run encoder + features, tokens = self.pixel_encoder(rgbs) + + cls_tokens = [x.contiguous() for x in tokens] + features = [ + self.stacking_fn(features[i:j]).contiguous() + for i, j in self.slices_encoder_range + ] + tokens = [ + self.stacking_fn(tokens[i:j]).contiguous() + for i, j in self.slices_encoder_range + ] + global_tokens = [cls_tokens[i] for i in [-2, -1]] + camera_tokens = [cls_tokens[i] for i in [-3, -2, -1]] + [tokens[-2]] + + # get data fro decoder and adapt to given camera + inputs = {} + inputs["features"] = features + inputs["tokens"] = tokens + inputs["global_tokens"] = global_tokens + inputs["camera_tokens"] = camera_tokens + inputs["image"] = rgbs + if gt_intrinsics is not None: + rays, angles = generate_rays(gt_intrinsics, (h, w)) + inputs["rays"] = rays + inputs["angles"] = angles + inputs["K"] = gt_intrinsics + + outs = self.pixel_decoder(inputs, {}) + # undo the reshaping and get original image size (slow) + outs = _postprocess(outs, ratio, (H, W), mode=self.interpolation_mode) + pred_intrinsics = outs["K"] + depth = outs["depth"] + confidence = outs["confidence"] + + # final 3D points backprojection + intrinsics = intrinsics if intrinsics is not None else pred_intrinsics + angles = generate_rays(intrinsics, (H, W))[-1] + angles = rearrange(angles, "b (h w) c -> b c h w", h=H, w=W) + points_3d = torch.cat((angles, depth), dim=1) + points_3d = spherical_zbuffer_to_euclidean( + points_3d.permute(0, 2, 3, 1) + ).permute(0, 3, 1, 2) + + outputs = { + "intrinsics": pred_intrinsics, + "points": points_3d, + "depth": depth, + "confidence": confidence, + } + return outputs + + def load_pretrained(self, model_file): + device = ( + torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") + ) + dict_model = torch.load(model_file, map_location=device) + if "model" in dict_model: + dict_model = dict_model["model"] + dict_model = deepcopy( + {k.replace("module.", ""): v for k, v in dict_model.items()} + ) + + info = self.load_state_dict(dict_model, strict=False) + if is_main_process(): + print( + f"Loaded from {model_file} for {self.__class__.__name__} results in:", + info, + ) + + @property + def device(self): + return next(self.parameters()).device + + def build(self, config): + mod = importlib.import_module("unidepth.models.encoder") + pixel_encoder_factory = getattr(mod, config["model"]["pixel_encoder"]["name"]) + pixel_encoder_config = { + **config["training"], + **config["model"]["pixel_encoder"], + **config["data"], + } + pixel_encoder = pixel_encoder_factory(pixel_encoder_config) + + config["model"]["pixel_encoder"]["patch_size"] = ( + 14 if "dino" in config["model"]["pixel_encoder"]["name"] else 16 + ) + pixel_encoder_embed_dims = ( + pixel_encoder.embed_dims + if hasattr(pixel_encoder, "embed_dims") + else [getattr(pixel_encoder, "embed_dim") * 2**i for i in range(4)] + ) + config["model"]["pixel_encoder"]["embed_dim"] = getattr( + pixel_encoder, "embed_dim" + ) + config["model"]["pixel_encoder"]["embed_dims"] = pixel_encoder_embed_dims + config["model"]["pixel_encoder"]["depths"] = pixel_encoder.depths + + pixel_decoder = Decoder(config) + + self.pixel_encoder = pixel_encoder + self.pixel_decoder = pixel_decoder + stacking_fn = config["model"]["pixel_encoder"]["stacking_fn"] + assert ( + stacking_fn in STACKING_FNS + ), f"Stacking function {stacking_fn} not found in {STACKING_FNS.keys()}" + self.stacking_fn = STACKING_FNS[stacking_fn] + + self.slices_encoder_range = list( + zip([0, *pixel_encoder.depths[:-1]], pixel_encoder.depths) + ) + self.shape_constraints = config["data"]["shape_constraints"] + self.shape_constraints["pixels_bounds_ori"] = self.shape_constraints.get( + "pixels_bounds", [1400, 2400] + ) + self.interpolation_mode = "bilinear" + self.eps = 1e-6 + self.resolution_level = None + + def build_losses(self, config): + self.losses = {} + for loss_name, loss_config in config["training"]["losses"].items(): + mod = importlib.import_module("unidepth.ops.losses") + loss_factory = getattr(mod, loss_config["name"]) + self.losses[loss_name] = loss_factory.build(loss_config) diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/__init__.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3eea77c21068371d9fdf9b34e251468804a7a172 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/__init__.py @@ -0,0 +1,3 @@ +from .losses import (ARel, Confidence, Dummy, EdgeGuidedLocalSSI, LocalSSI, + Regression, SelfDistill, SILog, TeacherDistill) +from .scheduler import CosineScheduler, PlainCosineScheduler diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/extract_patches/__init__.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/extract_patches/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b9e1b4e15ce3fa896f0b08d4bcea88c80c2758bc --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/extract_patches/__init__.py @@ -0,0 +1,4 @@ +from .functions import ExtractPatchesFunction +from .modules import RandomPatchExtractor + +__all__ = ["ExtractPatchesFunction", "RandomPatchExtractor"] \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/extract_patches/compile.sh b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/extract_patches/compile.sh new file mode 100644 index 0000000000000000000000000000000000000000..f1acd97c3a8ef13e21157d475d1f3ca5a4565e21 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/extract_patches/compile.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash + +if [ -z "$TORCH_CUDA_ARCH_LIST" ]; then + export TORCH_CUDA_ARCH_LIST="7.5 8.0 8.6+PTX" +fi + +python setup.py build install diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/extract_patches/functions/__init__.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/extract_patches/functions/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d085c5a935e2c0fd8203f178f422f9d7c2feac42 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/extract_patches/functions/__init__.py @@ -0,0 +1,3 @@ +from .extract_patches import ExtractPatchesFunction + +__all__ = ["ExtractPatchesFunction"] diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/extract_patches/functions/extract_patches.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/extract_patches/functions/extract_patches.py new file mode 100644 index 0000000000000000000000000000000000000000..df594f09e69adeb0b5c272ce390190396261aeb8 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/extract_patches/functions/extract_patches.py @@ -0,0 +1,37 @@ +import RandomPatchExtraction +import torch +from torch.autograd import Function + + +class ExtractPatchesFunction(Function): + @staticmethod + def forward(ctx, input, centers, h, w): + # Save variables for backward pass. inputs for shapes + ctx.save_for_backward(input, centers) + + return RandomPatchExtraction.extract_patches_forward(input, centers, h, w) + + @staticmethod + def backward(ctx, grad_output): + input, centers = ctx.saved_tensors + + (grad_input,) = RandomPatchExtraction.extract_patches_backward( + grad_output, centers, input.shape[2], input.shape[3] + ) + # breakpoint() + + # Return gradients with respect to inputs only + return grad_input, None, None, None + + +# Test +if __name__ == "__main__": + B, C, H, W = 1, 1, 10, 10 + N = 2 + h, w = 3, 3 + input = torch.arange( + B * C * H * W, device="cuda", dtype=torch.float32, requires_grad=True + ).view(B, C, H, W) + centers = torch.tensor([[[4, 4], [6, 6]]], device="cuda", dtype=torch.int32) + output = ExtractPatchesFunction.apply(input, centers, h, w) + output.mean().backward() diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/extract_patches/modules/__init__.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/extract_patches/modules/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e2f24b805f6f13fb035ff90d62411ad04e51f586 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/extract_patches/modules/__init__.py @@ -0,0 +1,3 @@ +from .patch_extractor import RandomPatchExtractor + +__all__ = ["RandomPatchExtractor"] diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/extract_patches/modules/patch_extractor.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/extract_patches/modules/patch_extractor.py new file mode 100644 index 0000000000000000000000000000000000000000..82cbb41963dc034fd6a288195db971aa49453cf4 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/extract_patches/modules/patch_extractor.py @@ -0,0 +1,42 @@ +from __future__ import absolute_import, division, print_function + +import torch +import torch.nn.functional as F +from torch import nn + +from ..functions import ExtractPatchesFunction + + +class RandomPatchExtractor(nn.Module): + def __init__( + self, + ): + super().__init__() + + def forward( + self, tensor: torch.Tensor, centers: torch.Tensor, patch_size: tuple[int, int] + ): + device = tensor.device + dtype = tensor.dtype + patch_width, patch_height = patch_size + pad_width = patch_width // 2 + pad_height = patch_height // 2 + dtype = tensor.dtype + + # Pad input to avoid out-of-bounds + tensor_padded = F.pad( + tensor, + (pad_width, pad_width, pad_height, pad_height), + mode="constant", + value=0.0, + ) + + # Adjust edge coordinates to account for padding + centers_padded = centers + torch.tensor( + [pad_height, pad_width], dtype=dtype, device=device + ).reshape(1, 1, 2) + + output = ExtractPatchesFunction.apply( + tensor_padded.float(), centers_padded.int(), patch_height, patch_width + ) + return output.to(dtype) diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/extract_patches/setup.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/extract_patches/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..be2cc0d7dc0face0864f7c142e5da9ce18ac9b21 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/extract_patches/setup.py @@ -0,0 +1,61 @@ +import glob +import os + +import torch +from setuptools import find_packages, setup +from torch.utils.cpp_extension import CUDA_HOME, CppExtension, CUDAExtension + +requirements = ["torch", "torchvision"] + + +def get_extensions(): + this_dir = os.path.dirname(os.path.abspath(__file__)) + extensions_dir = os.path.join(this_dir, "src") + + main_file = glob.glob(os.path.join(extensions_dir, "*.cpp")) + source_cpu = glob.glob(os.path.join(extensions_dir, "cpu", "*.cpp")) + source_cuda = glob.glob(os.path.join(extensions_dir, "cuda", "*.cu")) + + sources = main_file + source_cpu + extension = CppExtension + extra_compile_args = {"cxx": ["-O2"]} + define_macros = [] + + if torch.cuda.is_available() and CUDA_HOME is not None: + extension = CUDAExtension + sources += source_cuda + define_macros += [("WITH_CUDA", None)] + extra_compile_args["nvcc"] = [ + "-O2", + ] + else: + raise NotImplementedError("Cuda is not available") + + sources = list(set([os.path.join(extensions_dir, s) for s in sources])) + include_dirs = [extensions_dir] + ext_modules = [ + extension( + "RandomPatchExtraction", + sources, + include_dirs=include_dirs, + define_macros=define_macros, + extra_compile_args=extra_compile_args, + ) + ] + + return ext_modules + + +setup( + name="RandomPatchExtraction", + version="0.1", + author="Luigi Piccinelli", + ext_modules=get_extensions(), + packages=find_packages( + exclude=( + "configs", + "tests", + ) + ), + cmdclass={"build_ext": torch.utils.cpp_extension.BuildExtension}, +) diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/extract_patches/src/cpu/extract_patches_cpu.cpp b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/extract_patches/src/cpu/extract_patches_cpu.cpp new file mode 100644 index 0000000000000000000000000000000000000000..68695547d2d2fbb6002b923cf7bafbe2e4580d37 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/extract_patches/src/cpu/extract_patches_cpu.cpp @@ -0,0 +1,22 @@ +#include + +#include +#include + +torch::Tensor extract_patches_cpu_forward( + const torch::Tensor &input, + const torch::Tensor ¢ers, + int h, + int w +) { + AT_ERROR("Not implement on cpu"); +} + +std::vector extract_patches_cpu_backward( + const torch::Tensor &grad_patches, + const torch::Tensor &coords, + int H, + int W +) { + AT_ERROR("Not implement on cpu"); +} diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/extract_patches/src/cpu/extract_patches_cpu.h b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/extract_patches/src/cpu/extract_patches_cpu.h new file mode 100644 index 0000000000000000000000000000000000000000..be96c1336680b1ed3bd44e0614337c06cac564d1 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/extract_patches/src/cpu/extract_patches_cpu.h @@ -0,0 +1,18 @@ +#pragma once +#include +#include + + +torch::Tensor extract_patches_cpu_forward( + const torch::Tensor &input, + const torch::Tensor ¢ers, + int h, + int w +); + +std::vector extract_patches_cpu_backward( + const torch::Tensor &grad_patches, + const torch::Tensor &coords, + int H, + int W +); diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/extract_patches/src/cuda/extract_patches_cuda.h b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/extract_patches/src/cuda/extract_patches_cuda.h new file mode 100644 index 0000000000000000000000000000000000000000..f628ece88d66ef2a48c46d221efe7b8f9dd59d87 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/extract_patches/src/cuda/extract_patches_cuda.h @@ -0,0 +1,25 @@ +#ifndef EXTRACT_PATCHES_CUDA_H +#define EXTRACT_PATCHES_CUDA_H + +#include +#include +#include +#include + +// Function prototypes for the CUDA functions +torch::Tensor extract_patches_cuda_forward( + const torch::Tensor &input, + const torch::Tensor ¢ers, + int h, + int w +); + +std::vector extract_patches_cuda_backward( + const torch::Tensor &grad_output, + const torch::Tensor ¢ers, + int H, + int W +); + + +#endif // EXTRACT_PATCHES_CUDA_H diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/extract_patches/src/cuda/extract_patches_kernel.cu b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/extract_patches/src/cuda/extract_patches_kernel.cu new file mode 100644 index 0000000000000000000000000000000000000000..88b2b91f4de5d5cc08c7a229cfe5e507db100046 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/extract_patches/src/cuda/extract_patches_kernel.cu @@ -0,0 +1,158 @@ +#include +#include + +#include "cuda/extract_patches_kernel.cuh" +#include "cuda/extract_patches_cuda.h" + + +// Need to templetize these two to get fp16 working, but problems in compilation... +torch::Tensor extract_patches_cuda_forward( + const torch::Tensor &input, + const torch::Tensor ¢ers, + int h, + int w +) { + + int B = input.size(0); + int C = input.size(1); + int H = input.size(2); + int W = input.size(3); + int N = centers.size(1); + + auto output = torch::zeros({B, C, N, h, w}, input.options()); + + const int threads = C; + const dim3 blocks(B, N); + + extract_patches_cuda_forward_kernel<<>>( + input.data_ptr(), + output.data_ptr(), + centers.data_ptr(), + B, C, H, W, + N, h, w); + + return {output}; +} + +std::vector extract_patches_cuda_backward( + const torch::Tensor &grad_output, + const torch::Tensor ¢ers, + int H, + int W +) { + + int B = grad_output.size(0); + int C = grad_output.size(1); + int N = centers.size(1); + int h = grad_output.size(3); + int w = grad_output.size(4); + + auto grad_input = torch::zeros({B, C, H, W}, grad_output.options()); + + const int threads = C; + const dim3 blocks(B, N); + + extract_patches_cuda_backward_kernel<<>>( + grad_output.data_ptr(), + grad_input.data_ptr(), + centers.data_ptr(), + B, C, H, W, + N, h, w); + + return {grad_input}; +} + +template +__global__ void extract_patches_cuda_forward_kernel( + const T* __restrict__ input, + T* __restrict__ output, + const int* __restrict__ centers, + int B, int C, int H, int W, + int N, int h, int w) { + + // Calculate thread indices + int batch_idx = blockIdx.x; + int patch_idx = blockIdx.y; + int channel_idx = threadIdx.x; + + // Extract center coordinates + int center_y = centers[(batch_idx * N + patch_idx) * 2]; + int center_x = centers[(batch_idx * N + patch_idx) * 2 + 1]; + + // Calculate half patch size + int half_h = h / 2; + int half_w = w / 2; + + // Extract patch + for (int i = 0; i < h; ++i) { + for (int j = 0; j < w; ++j) { + int y = center_y - half_h + i; + int x = center_x - half_w + j; + output[batch_idx * C * N * h * w + patch_idx * C * h * w + channel_idx * h * w + i * w + j] = + input[batch_idx * C * H * W + channel_idx * H * W + y * W + x]; + } + } +} + +template __global__ void extract_patches_cuda_forward_kernel( + const float* __restrict__ input, + float* __restrict__ output, + const int* __restrict__ centers, + int B, int C, int H, int W, + int N, int h, int w); + +template __global__ void extract_patches_cuda_forward_kernel<__half>( + const __half* __restrict__ input, + __half* __restrict__ output, + const int* __restrict__ centers, + int B, int C, int H, int W, + int N, int h, int w); + +template +__global__ void extract_patches_cuda_backward_kernel( + const T* __restrict__ grad_output, + T* __restrict__ grad_input, + const int* __restrict__ centers, + int B, int C, int H, int W, + int N, int h, int w) { + + // Calculate thread indices + int batch_idx = blockIdx.x; + int patch_idx = blockIdx.y; + int channel_idx = threadIdx.x; + + // Extract center coordinates + int center_y = centers[(batch_idx * N + patch_idx) * 2]; + int center_x = centers[(batch_idx * N + patch_idx) * 2 + 1]; + + // Calculate half patch size + int half_h = h / 2; + int half_w = w / 2; + + // Compute gradients with respect to input tensor using chain rule + for (int i = 0; i < h; ++i) { + for (int j = 0; j < w; ++j) { + int y = center_y - half_h + i; + int x = center_x - half_w + j; + + atomicAdd( + &grad_input[batch_idx * C * H * W + channel_idx * H * W + y * W + x], + grad_output[batch_idx * C * N * h * w + patch_idx * C * h * w + channel_idx * h * w + i * w + j] + ); + } + } +} + +template __global__ void extract_patches_cuda_backward_kernel( + const float* __restrict__ grad_output, + float* __restrict__ grad_input, + const int* __restrict__ centers, + int B, int C, int H, int W, + int N, int h, int w); + +template __global__ void extract_patches_cuda_backward_kernel<__half>( + const __half* __restrict__ grad_output, + __half* __restrict__ grad_input, + const int* __restrict__ centers, + int B, int C, int H, int W, + int N, int h, int w); \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/extract_patches/src/cuda/extract_patches_kernel.cuh b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/extract_patches/src/cuda/extract_patches_kernel.cuh new file mode 100644 index 0000000000000000000000000000000000000000..5386e8fb99312bf30ff792d632ab8b0da17e24aa --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/extract_patches/src/cuda/extract_patches_kernel.cuh @@ -0,0 +1,26 @@ +#ifndef EXTRACT_PATCHES_KERNEL_CUH +#define EXTRACT_PATCHES_KERNEL_CUH + +#include +#include +#include +#include +#include // should contain __half + +// Declare the forward CUDA kernel function +template __global__ void extract_patches_cuda_forward_kernel( + const T* __restrict__ input, + T* __restrict__ output, + const int* __restrict__ centers, + int B, int C, int H, int W, + int N, int h, int w); + +// Declare the backward CUDA kernel function +template __global__ void extract_patches_cuda_backward_kernel( + const T* __restrict__ grad_output, + T* __restrict__ grad_input, + const int* __restrict__ centers, + int B, int C, int H, int W, + int N, int h, int w); + +#endif // EXTRACT_PATCHES_KERNEL_CUH diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/extract_patches/src/extract_patches.cpp b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/extract_patches/src/extract_patches.cpp new file mode 100644 index 0000000000000000000000000000000000000000..67c1d22dcf98b8af4c694b6f5777aada525cd29f --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/extract_patches/src/extract_patches.cpp @@ -0,0 +1,7 @@ + +#include "extract_patches.h" + +PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { + m.def("extract_patches_forward", &extract_patches_forward, "Extract patches forward (CUDA)"); + m.def("extract_patches_backward", &extract_patches_backward, "Extract patches backward (CUDA)"); +} diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/extract_patches/src/extract_patches.h b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/extract_patches/src/extract_patches.h new file mode 100644 index 0000000000000000000000000000000000000000..09eb628ad8516d82e2d68c00e6fcb908ae7b083d --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/extract_patches/src/extract_patches.h @@ -0,0 +1,46 @@ +#pragma once + +#include "cpu/extract_patches_cpu.h" + +#ifdef WITH_CUDA +#include "cuda/extract_patches_cuda.h" +#endif + +#include + +#include +#include + +torch::Tensor extract_patches_forward( + const torch::Tensor &images, + const torch::Tensor &coords, + int patch_height, + int patch_width) +{ + if (images.type().is_cuda()) + { +#ifdef WITH_CUDA + return extract_patches_cuda_forward(images, coords, patch_height, patch_width); +#else + AT_ERROR("Not compiled with GPU support"); +#endif + } + AT_ERROR("Not implemented on the CPU"); +} + +std::vector extract_patches_backward( + const torch::Tensor &grad_patches, + const torch::Tensor &coords, + int H, + int W) +{ + if (grad_patches.type().is_cuda()) + { +#ifdef WITH_CUDA + return extract_patches_cuda_backward(grad_patches, coords, H, W); +#else + AT_ERROR("Not compiled with GPU support"); +#endif + } + AT_ERROR("Not implemented on the CPU"); +} \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/knn/__init__.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/knn/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ba469c8fcb582177fd183702a468d6e72d262a7f --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/knn/__init__.py @@ -0,0 +1,6 @@ +from .functions.knn import knn_gather, knn_points + +__all__ = [ + "knn_points", + "knn_gather", +] diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/knn/compile.sh b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/knn/compile.sh new file mode 100644 index 0000000000000000000000000000000000000000..348ef710b9efaba5cb24ae54cebbee0d4e4d737c --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/knn/compile.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash + +export TORCH_CUDA_ARCH_LIST="6.1 7.0 7.5 8.0 8.6 8.7 8.9 9.0+PTX" +# export FORCE_CUDA=1 #if you do not actually have cuda, workaround +python setup.py build install \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/knn/functions/__init__.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/knn/functions/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6a54211c5e208129ba33507b0011733cb4a31491 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/knn/functions/__init__.py @@ -0,0 +1,6 @@ +from .knn import knn_gather, knn_points + +__all__ = [ + "knn_points", + "knn_gather", +] diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/knn/functions/knn.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/knn/functions/knn.py new file mode 100644 index 0000000000000000000000000000000000000000..42c36344d42952f123290cb0bec10e39a6f2da3b --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/knn/functions/knn.py @@ -0,0 +1,249 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +# pyre-unsafe + +from collections import namedtuple +from typing import Union + +import torch +from KNN import knn_points_backward, knn_points_idx +from torch.autograd import Function +from torch.autograd.function import once_differentiable + +_KNN = namedtuple("KNN", "dists idx knn") + + +class _knn_points(Function): + """ + Torch autograd Function wrapper for KNN C++/CUDA implementations. + """ + + @staticmethod + # pyre-fixme[14]: `forward` overrides method defined in `Function` inconsistently. + def forward( + ctx, + p1, + p2, + lengths1, + lengths2, + K, + version, + norm: int = 2, + return_sorted: bool = True, + ): + """ + K-Nearest neighbors on point clouds. + + Args: + p1: Tensor of shape (N, P1, D) giving a batch of N point clouds, each + containing up to P1 points of dimension D. + p2: Tensor of shape (N, P2, D) giving a batch of N point clouds, each + containing up to P2 points of dimension D. + lengths1: LongTensor of shape (N,) of values in the range [0, P1], giving the + length of each pointcloud in p1. Or None to indicate that every cloud has + length P1. + lengths2: LongTensor of shape (N,) of values in the range [0, P2], giving the + length of each pointcloud in p2. Or None to indicate that every cloud has + length P2. + K: Integer giving the number of nearest neighbors to return. + version: Which KNN implementation to use in the backend. If version=-1, + the correct implementation is selected based on the shapes of the inputs. + norm: (int) indicating the norm. Only supports 1 (for L1) and 2 (for L2). + return_sorted: (bool) whether to return the nearest neighbors sorted in + ascending order of distance. + + Returns: + p1_dists: Tensor of shape (N, P1, K) giving the squared distances to + the nearest neighbors. This is padded with zeros both where a cloud in p2 + has fewer than K points and where a cloud in p1 has fewer than P1 points. + + p1_idx: LongTensor of shape (N, P1, K) giving the indices of the + K nearest neighbors from points in p1 to points in p2. + Concretely, if `p1_idx[n, i, k] = j` then `p2[n, j]` is the k-th nearest + neighbors to `p1[n, i]` in `p2[n]`. This is padded with zeros both where a cloud + in p2 has fewer than K points and where a cloud in p1 has fewer than P1 points. + """ + if not ((norm == 1) or (norm == 2)): + raise ValueError("Support for 1 or 2 norm.") + + idx, dists = knn_points_idx(p1, p2, lengths1, lengths2, norm, K, version) + + # sort KNN in ascending order if K > 1 + if K > 1 and return_sorted: + if lengths2.min() < K: + P1 = p1.shape[1] + mask = lengths2[:, None] <= torch.arange(K, device=dists.device)[None] + # mask has shape [N, K], true where dists irrelevant + mask = mask[:, None].expand(-1, P1, -1) + # mask has shape [N, P1, K], true where dists irrelevant + dists[mask] = float("inf") + dists, sort_idx = dists.sort(dim=2) + dists[mask] = 0 + else: + dists, sort_idx = dists.sort(dim=2) + idx = idx.gather(2, sort_idx) + + ctx.save_for_backward(p1, p2, lengths1, lengths2, idx) + ctx.mark_non_differentiable(idx) + ctx.norm = norm + return dists, idx + + @staticmethod + @once_differentiable + def backward(ctx, grad_dists, grad_idx): + p1, p2, lengths1, lengths2, idx = ctx.saved_tensors + norm = ctx.norm + # TODO(gkioxari) Change cast to floats once we add support for doubles. + if not (grad_dists.dtype == torch.float32): + grad_dists = grad_dists.float() + if not (p1.dtype == torch.float32): + p1 = p1.float() + if not (p2.dtype == torch.float32): + p2 = p2.float() + grad_p1, grad_p2 = knn_points_backward( + p1, p2, lengths1, lengths2, idx, norm, grad_dists + ) + return grad_p1, grad_p2, None, None, None, None, None, None + + +def knn_points( + p1: torch.Tensor, + p2: torch.Tensor, + lengths1: Union[torch.Tensor, None] = None, + lengths2: Union[torch.Tensor, None] = None, + norm: int = 2, + K: int = 1, + version: int = -1, + return_nn: bool = False, + return_sorted: bool = True, +) -> _KNN: + """ + K-Nearest neighbors on point clouds. + + Args: + p1: Tensor of shape (N, P1, D) giving a batch of N point clouds, each + containing up to P1 points of dimension D. + p2: Tensor of shape (N, P2, D) giving a batch of N point clouds, each + containing up to P2 points of dimension D. + lengths1: LongTensor of shape (N,) of values in the range [0, P1], giving the + length of each pointcloud in p1. Or None to indicate that every cloud has + length P1. + lengths2: LongTensor of shape (N,) of values in the range [0, P2], giving the + length of each pointcloud in p2. Or None to indicate that every cloud has + length P2. + norm: Integer indicating the norm of the distance. Supports only 1 for L1, 2 for L2. + K: Integer giving the number of nearest neighbors to return. + version: Which KNN implementation to use in the backend. If version=-1, + the correct implementation is selected based on the shapes of the inputs. + return_nn: If set to True returns the K nearest neighbors in p2 for each point in p1. + return_sorted: (bool) whether to return the nearest neighbors sorted in + ascending order of distance. + + Returns: + dists: Tensor of shape (N, P1, K) giving the squared distances to + the nearest neighbors. This is padded with zeros both where a cloud in p2 + has fewer than K points and where a cloud in p1 has fewer than P1 points. + + idx: LongTensor of shape (N, P1, K) giving the indices of the + K nearest neighbors from points in p1 to points in p2. + Concretely, if `p1_idx[n, i, k] = j` then `p2[n, j]` is the k-th nearest + neighbors to `p1[n, i]` in `p2[n]`. This is padded with zeros both where a cloud + in p2 has fewer than K points and where a cloud in p1 has fewer than P1 + points. + + nn: Tensor of shape (N, P1, K, D) giving the K nearest neighbors in p2 for + each point in p1. Concretely, `p2_nn[n, i, k]` gives the k-th nearest neighbor + for `p1[n, i]`. Returned if `return_nn` is True. + The nearest neighbors are collected using `knn_gather` + + .. code-block:: + + p2_nn = knn_gather(p2, p1_idx, lengths2) + + which is a helper function that allows indexing any tensor of shape (N, P2, U) with + the indices `p1_idx` returned by `knn_points`. The output is a tensor + of shape (N, P1, K, U). + + """ + if p1.shape[0] != p2.shape[0]: + raise ValueError("pts1 and pts2 must have the same batch dimension.") + if p1.shape[2] != p2.shape[2]: + raise ValueError("pts1 and pts2 must have the same point dimension.") + + p1 = p1.contiguous() + p2 = p2.contiguous() + + P1 = p1.shape[1] + P2 = p2.shape[1] + + if lengths1 is None: + lengths1 = torch.full((p1.shape[0],), P1, dtype=torch.int64, device=p1.device) + if lengths2 is None: + lengths2 = torch.full((p1.shape[0],), P2, dtype=torch.int64, device=p1.device) + + p1_dists, p1_idx = _knn_points.apply( + p1, p2, lengths1, lengths2, K, version, norm, return_sorted + ) + + p2_nn = None + if return_nn: + p2_nn = knn_gather(p2, p1_idx, lengths2) + + return _KNN(dists=p1_dists, idx=p1_idx, knn=p2_nn if return_nn else None) + + +def knn_gather( + x: torch.Tensor, idx: torch.Tensor, lengths: Union[torch.Tensor, None] = None +): + """ + A helper function for knn that allows indexing a tensor x with the indices `idx` + returned by `knn_points`. + + For example, if `dists, idx = knn_points(p, x, lengths_p, lengths, K)` + where p is a tensor of shape (N, L, D) and x a tensor of shape (N, M, D), + then one can compute the K nearest neighbors of p with `p_nn = knn_gather(x, idx, lengths)`. + It can also be applied for any tensor x of shape (N, M, U) where U != D. + + Args: + x: Tensor of shape (N, M, U) containing U-dimensional features to + be gathered. + idx: LongTensor of shape (N, L, K) giving the indices returned by `knn_points`. + lengths: LongTensor of shape (N,) of values in the range [0, M], giving the + length of each example in the batch in x. Or None to indicate that every + example has length M. + Returns: + x_out: Tensor of shape (N, L, K, U) resulting from gathering the elements of x + with idx, s.t. `x_out[n, l, k] = x[n, idx[n, l, k]]`. + If `k > lengths[n]` then `x_out[n, l, k]` is filled with 0.0. + """ + N, M, U = x.shape + _N, L, K = idx.shape + + if N != _N: + raise ValueError("x and idx must have same batch dimension.") + + if lengths is None: + lengths = torch.full((x.shape[0],), M, dtype=torch.int64, device=x.device) + + idx_expanded = idx[:, :, :, None].expand(-1, -1, -1, U) + # idx_expanded has shape [N, L, K, U] + + x_out = x[:, :, None].expand(-1, -1, K, -1).gather(1, idx_expanded) + # p2_nn has shape [N, L, K, U] + + needs_mask = lengths.min() < K + if needs_mask: + # mask has shape [N, K], true where idx is irrelevant because + # there is less number of points in p2 than K + mask = lengths[:, None] <= torch.arange(K, device=x.device)[None] + + # expand mask to shape [N, L, K, U] + mask = mask[:, None].expand(-1, L, -1) + mask = mask[:, :, :, None].expand(-1, -1, -1, U) + x_out[mask] = 0.0 + + return x_out diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/knn/setup.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/knn/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..6e7f7dd9953b7da22310cdb7d227acccf2749f36 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/knn/setup.py @@ -0,0 +1,61 @@ +import glob +import os + +import torch +from setuptools import find_packages, setup +from torch.utils.cpp_extension import CUDA_HOME, CppExtension, CUDAExtension + +requirements = ["torch", "torchvision"] + + +def get_extensions(): + this_dir = os.path.dirname(os.path.abspath(__file__)) + extensions_dir = os.path.join(this_dir, "src") + + main_file = glob.glob(os.path.join(extensions_dir, "*.cpp")) + source_cpu = glob.glob(os.path.join(extensions_dir, "*.cpp")) + source_cuda = glob.glob(os.path.join(extensions_dir, "*.cu")) + + sources = main_file + source_cpu + extension = CppExtension + extra_compile_args = {"cxx": ["-O3"]} + define_macros = [] + + if torch.cuda.is_available() and CUDA_HOME is not None: + extension = CUDAExtension + sources += source_cuda + define_macros += [("WITH_CUDA", None)] + extra_compile_args["nvcc"] = [ + "-O3", + ] + else: + raise NotImplementedError("Cuda is not available") + + sources = list(set([os.path.join(extensions_dir, s) for s in sources])) + include_dirs = [extensions_dir] + ext_modules = [ + extension( + "KNN", + sources, + include_dirs=include_dirs, + define_macros=define_macros, + extra_compile_args=extra_compile_args, + ) + ] + + return ext_modules + + +setup( + name="KNN", + version="0.1", + author="Luigi Piccinelli", + ext_modules=get_extensions(), + packages=find_packages( + exclude=( + "configs", + "tests", + ) + ), + cmdclass={"build_ext": torch.utils.cpp_extension.BuildExtension}, +) diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/knn/src/knn.cu b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/knn/src/knn.cu new file mode 100644 index 0000000000000000000000000000000000000000..ba0732dca6ee00732286d5e3a15191aaaf7c5409 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/knn/src/knn.cu @@ -0,0 +1,587 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include +#include +#include +#include +#include +#include + +#include "utils/dispatch.cuh" +#include "utils/mink.cuh" + +// A chunk of work is blocksize-many points of P1. +// The number of potential chunks to do is N*(1+(P1-1)/blocksize) +// call (1+(P1-1)/blocksize) chunks_per_cloud +// These chunks are divided among the gridSize-many blocks. +// In block b, we work on chunks b, b+gridSize, b+2*gridSize etc . +// In chunk i, we work on cloud i/chunks_per_cloud on points starting from +// blocksize*(i%chunks_per_cloud). + +template +__global__ void KNearestNeighborKernelV0( + const scalar_t* __restrict__ points1, + const scalar_t* __restrict__ points2, + const int64_t* __restrict__ lengths1, + const int64_t* __restrict__ lengths2, + scalar_t* __restrict__ dists, + int64_t* __restrict__ idxs, + const size_t N, + const size_t P1, + const size_t P2, + const size_t D, + const size_t K, + const size_t norm) { + // Store both dists and indices for knn in global memory. + const int64_t chunks_per_cloud = (1 + (P1 - 1) / blockDim.x); + const int64_t chunks_to_do = N * chunks_per_cloud; + for (int64_t chunk = blockIdx.x; chunk < chunks_to_do; chunk += gridDim.x) { + const int64_t n = chunk / chunks_per_cloud; + const int64_t start_point = blockDim.x * (chunk % chunks_per_cloud); + int64_t p1 = start_point + threadIdx.x; + if (p1 >= lengths1[n]) + continue; + int offset = n * P1 * K + p1 * K; + int64_t length2 = lengths2[n]; + MinK mink(dists + offset, idxs + offset, K); + for (int p2 = 0; p2 < length2; ++p2) { + // Find the distance between points1[n, p1] and points[n, p2] + scalar_t dist = 0; + for (int d = 0; d < D; ++d) { + scalar_t coord1 = points1[n * P1 * D + p1 * D + d]; + scalar_t coord2 = points2[n * P2 * D + p2 * D + d]; + scalar_t diff = coord1 - coord2; + scalar_t norm_diff = (norm == 2) ? (diff * diff) : abs(diff); + dist += norm_diff; + } + mink.add(dist, p2); + } + } +} + +template +__global__ void KNearestNeighborKernelV1( + const scalar_t* __restrict__ points1, + const scalar_t* __restrict__ points2, + const int64_t* __restrict__ lengths1, + const int64_t* __restrict__ lengths2, + scalar_t* __restrict__ dists, + int64_t* __restrict__ idxs, + const size_t N, + const size_t P1, + const size_t P2, + const size_t K, + const size_t norm) { + // Same idea as the previous version, but hoist D into a template argument + // so we can cache the current point in a thread-local array. We still store + // the current best K dists and indices in global memory, so this should work + // for very large K and fairly large D. + scalar_t cur_point[D]; + const int64_t chunks_per_cloud = (1 + (P1 - 1) / blockDim.x); + const int64_t chunks_to_do = N * chunks_per_cloud; + for (int64_t chunk = blockIdx.x; chunk < chunks_to_do; chunk += gridDim.x) { + const int64_t n = chunk / chunks_per_cloud; + const int64_t start_point = blockDim.x * (chunk % chunks_per_cloud); + int64_t p1 = start_point + threadIdx.x; + if (p1 >= lengths1[n]) + continue; + for (int d = 0; d < D; ++d) { + cur_point[d] = points1[n * P1 * D + p1 * D + d]; + } + int offset = n * P1 * K + p1 * K; + int64_t length2 = lengths2[n]; + MinK mink(dists + offset, idxs + offset, K); + for (int p2 = 0; p2 < length2; ++p2) { + // Find the distance between cur_point and points[n, p2] + scalar_t dist = 0; + for (int d = 0; d < D; ++d) { + scalar_t diff = cur_point[d] - points2[n * P2 * D + p2 * D + d]; + scalar_t norm_diff = (norm == 2) ? (diff * diff) : abs(diff); + dist += norm_diff; + } + mink.add(dist, p2); + } + } +} + +// This is a shim functor to allow us to dispatch using DispatchKernel1D +template +struct KNearestNeighborV1Functor { + static void run( + size_t blocks, + size_t threads, + const scalar_t* __restrict__ points1, + const scalar_t* __restrict__ points2, + const int64_t* __restrict__ lengths1, + const int64_t* __restrict__ lengths2, + scalar_t* __restrict__ dists, + int64_t* __restrict__ idxs, + const size_t N, + const size_t P1, + const size_t P2, + const size_t K, + const size_t norm) { + cudaStream_t stream = at::cuda::getCurrentCUDAStream(); + KNearestNeighborKernelV1<<>>( + points1, points2, lengths1, lengths2, dists, idxs, N, P1, P2, K, norm); + } +}; + +template +__global__ void KNearestNeighborKernelV2( + const scalar_t* __restrict__ points1, + const scalar_t* __restrict__ points2, + const int64_t* __restrict__ lengths1, + const int64_t* __restrict__ lengths2, + scalar_t* __restrict__ dists, + int64_t* __restrict__ idxs, + const int64_t N, + const int64_t P1, + const int64_t P2, + const size_t norm) { + // Same general implementation as V2, but also hoist K into a template arg. + scalar_t cur_point[D]; + scalar_t min_dists[K]; + int min_idxs[K]; + const int64_t chunks_per_cloud = (1 + (P1 - 1) / blockDim.x); + const int64_t chunks_to_do = N * chunks_per_cloud; + for (int64_t chunk = blockIdx.x; chunk < chunks_to_do; chunk += gridDim.x) { + const int64_t n = chunk / chunks_per_cloud; + const int64_t start_point = blockDim.x * (chunk % chunks_per_cloud); + int64_t p1 = start_point + threadIdx.x; + if (p1 >= lengths1[n]) + continue; + for (int d = 0; d < D; ++d) { + cur_point[d] = points1[n * P1 * D + p1 * D + d]; + } + int64_t length2 = lengths2[n]; + MinK mink(min_dists, min_idxs, K); + for (int p2 = 0; p2 < length2; ++p2) { + scalar_t dist = 0; + for (int d = 0; d < D; ++d) { + int offset = n * P2 * D + p2 * D + d; + scalar_t diff = cur_point[d] - points2[offset]; + scalar_t norm_diff = (norm == 2) ? (diff * diff) : abs(diff); + dist += norm_diff; + } + mink.add(dist, p2); + } + for (int k = 0; k < mink.size(); ++k) { + idxs[n * P1 * K + p1 * K + k] = min_idxs[k]; + dists[n * P1 * K + p1 * K + k] = min_dists[k]; + } + } +} + +// This is a shim so we can dispatch using DispatchKernel2D +template +struct KNearestNeighborKernelV2Functor { + static void run( + size_t blocks, + size_t threads, + const scalar_t* __restrict__ points1, + const scalar_t* __restrict__ points2, + const int64_t* __restrict__ lengths1, + const int64_t* __restrict__ lengths2, + scalar_t* __restrict__ dists, + int64_t* __restrict__ idxs, + const int64_t N, + const int64_t P1, + const int64_t P2, + const size_t norm) { + cudaStream_t stream = at::cuda::getCurrentCUDAStream(); + KNearestNeighborKernelV2<<>>( + points1, points2, lengths1, lengths2, dists, idxs, N, P1, P2, norm); + } +}; + +template +__global__ void KNearestNeighborKernelV3( + const scalar_t* __restrict__ points1, + const scalar_t* __restrict__ points2, + const int64_t* __restrict__ lengths1, + const int64_t* __restrict__ lengths2, + scalar_t* __restrict__ dists, + int64_t* __restrict__ idxs, + const size_t N, + const size_t P1, + const size_t P2, + const size_t norm) { + // Same idea as V2, but use register indexing for thread-local arrays. + // Enabling sorting for this version leads to huge slowdowns; I suspect + // that it forces min_dists into local memory rather than registers. + // As a result this version is always unsorted. + scalar_t cur_point[D]; + scalar_t min_dists[K]; + int min_idxs[K]; + const int64_t chunks_per_cloud = (1 + (P1 - 1) / blockDim.x); + const int64_t chunks_to_do = N * chunks_per_cloud; + for (int64_t chunk = blockIdx.x; chunk < chunks_to_do; chunk += gridDim.x) { + const int64_t n = chunk / chunks_per_cloud; + const int64_t start_point = blockDim.x * (chunk % chunks_per_cloud); + int64_t p1 = start_point + threadIdx.x; + if (p1 >= lengths1[n]) + continue; + for (int d = 0; d < D; ++d) { + cur_point[d] = points1[n * P1 * D + p1 * D + d]; + } + int64_t length2 = lengths2[n]; + RegisterMinK mink(min_dists, min_idxs); + for (int p2 = 0; p2 < length2; ++p2) { + scalar_t dist = 0; + for (int d = 0; d < D; ++d) { + int offset = n * P2 * D + p2 * D + d; + scalar_t diff = cur_point[d] - points2[offset]; + scalar_t norm_diff = (norm == 2) ? (diff * diff) : abs(diff); + dist += norm_diff; + } + mink.add(dist, p2); + } + for (int k = 0; k < mink.size(); ++k) { + idxs[n * P1 * K + p1 * K + k] = min_idxs[k]; + dists[n * P1 * K + p1 * K + k] = min_dists[k]; + } + } +} + +// This is a shim so we can dispatch using DispatchKernel2D +template +struct KNearestNeighborKernelV3Functor { + static void run( + size_t blocks, + size_t threads, + const scalar_t* __restrict__ points1, + const scalar_t* __restrict__ points2, + const int64_t* __restrict__ lengths1, + const int64_t* __restrict__ lengths2, + scalar_t* __restrict__ dists, + int64_t* __restrict__ idxs, + const size_t N, + const size_t P1, + const size_t P2, + const size_t norm) { + cudaStream_t stream = at::cuda::getCurrentCUDAStream(); + KNearestNeighborKernelV3<<>>( + points1, points2, lengths1, lengths2, dists, idxs, N, P1, P2, norm); + } +}; + +constexpr int V1_MIN_D = 1; +constexpr int V1_MAX_D = 32; + +constexpr int V2_MIN_D = 1; +constexpr int V2_MAX_D = 8; +constexpr int V2_MIN_K = 1; +constexpr int V2_MAX_K = 32; + +constexpr int V3_MIN_D = 1; +constexpr int V3_MAX_D = 8; +constexpr int V3_MIN_K = 1; +constexpr int V3_MAX_K = 4; + +bool InBounds(const int64_t min, const int64_t x, const int64_t max) { + return min <= x && x <= max; +} + +bool KnnCheckVersion(int version, const int64_t D, const int64_t K) { + if (version == 0) { + return true; + } else if (version == 1) { + return InBounds(V1_MIN_D, D, V1_MAX_D); + } else if (version == 2) { + return InBounds(V2_MIN_D, D, V2_MAX_D) && InBounds(V2_MIN_K, K, V2_MAX_K); + } else if (version == 3) { + return InBounds(V3_MIN_D, D, V3_MAX_D) && InBounds(V3_MIN_K, K, V3_MAX_K); + } + return false; +} + +int ChooseVersion(const int64_t D, const int64_t K) { + for (int version = 3; version >= 1; version--) { + if (KnnCheckVersion(version, D, K)) { + return version; + } + } + return 0; +} + +std::tuple KNearestNeighborIdxCuda( + const at::Tensor& p1, + const at::Tensor& p2, + const at::Tensor& lengths1, + const at::Tensor& lengths2, + const int norm, + const int K, + int version) { + // Check inputs are on the same device + at::TensorArg p1_t{p1, "p1", 1}, p2_t{p2, "p2", 2}, + lengths1_t{lengths1, "lengths1", 3}, lengths2_t{lengths2, "lengths2", 4}; + at::CheckedFrom c = "KNearestNeighborIdxCuda"; + at::checkAllSameGPU(c, {p1_t, p2_t, lengths1_t, lengths2_t}); + at::checkAllSameType(c, {p1_t, p2_t}); + + // Set the device for the kernel launch based on the device of the input + at::cuda::CUDAGuard device_guard(p1.device()); + cudaStream_t stream = at::cuda::getCurrentCUDAStream(); + + const auto N = p1.size(0); + const auto P1 = p1.size(1); + const auto P2 = p2.size(1); + const auto D = p2.size(2); + const int64_t K_64 = K; + + TORCH_CHECK((norm == 1) || (norm == 2), "Norm must be 1 or 2."); + + TORCH_CHECK(p1.size(2) == D, "Point sets must have the same last dimension"); + auto long_dtype = lengths1.options().dtype(at::kLong); + auto idxs = at::zeros({N, P1, K}, long_dtype); + auto dists = at::zeros({N, P1, K}, p1.options()); + + if (idxs.numel() == 0) { + AT_CUDA_CHECK(cudaGetLastError()); + return std::make_tuple(idxs, dists); + } + + if (version < 0) { + version = ChooseVersion(D, K); + } else if (!KnnCheckVersion(version, D, K)) { + int new_version = ChooseVersion(D, K); + std::cout << "WARNING: Requested KNN version " << version + << " is not compatible with D = " << D << "; K = " << K + << ". Falling back to version = " << new_version << std::endl; + version = new_version; + } + + // At this point we should have a valid version no matter what data the user + // gave us. But we can check once more to be sure; however this time + // assert fail since failing at this point means we have a bug in our version + // selection or checking code. + AT_ASSERTM(KnnCheckVersion(version, D, K), "Invalid version"); + + const size_t threads = 256; + const size_t blocks = 256; + if (version == 0) { + AT_DISPATCH_FLOATING_TYPES( + p1.scalar_type(), "knn_kernel_cuda", ([&] { + KNearestNeighborKernelV0<<>>( + p1.contiguous().data_ptr(), + p2.contiguous().data_ptr(), + lengths1.contiguous().data_ptr(), + lengths2.contiguous().data_ptr(), + dists.data_ptr(), + idxs.data_ptr(), + N, + P1, + P2, + D, + K, + norm); + })); + } else if (version == 1) { + AT_DISPATCH_FLOATING_TYPES(p1.scalar_type(), "knn_kernel_cuda", ([&] { + DispatchKernel1D< + KNearestNeighborV1Functor, + scalar_t, + V1_MIN_D, + V1_MAX_D>( + D, + blocks, + threads, + p1.contiguous().data_ptr(), + p2.contiguous().data_ptr(), + lengths1.contiguous().data_ptr(), + lengths2.contiguous().data_ptr(), + dists.data_ptr(), + idxs.data_ptr(), + N, + P1, + P2, + K, + norm); + })); + } else if (version == 2) { + AT_DISPATCH_FLOATING_TYPES(p1.scalar_type(), "knn_kernel_cuda", ([&] { + DispatchKernel2D< + KNearestNeighborKernelV2Functor, + scalar_t, + V2_MIN_D, + V2_MAX_D, + V2_MIN_K, + V2_MAX_K>( + D, + K_64, + blocks, + threads, + p1.contiguous().data_ptr(), + p2.contiguous().data_ptr(), + lengths1.contiguous().data_ptr(), + lengths2.contiguous().data_ptr(), + dists.data_ptr(), + idxs.data_ptr(), + N, + P1, + P2, + norm); + })); + } else if (version == 3) { + AT_DISPATCH_FLOATING_TYPES(p1.scalar_type(), "knn_kernel_cuda", ([&] { + DispatchKernel2D< + KNearestNeighborKernelV3Functor, + scalar_t, + V3_MIN_D, + V3_MAX_D, + V3_MIN_K, + V3_MAX_K>( + D, + K_64, + blocks, + threads, + p1.contiguous().data_ptr(), + p2.contiguous().data_ptr(), + lengths1.contiguous().data_ptr(), + lengths2.contiguous().data_ptr(), + dists.data_ptr(), + idxs.data_ptr(), + N, + P1, + P2, + norm); + })); + } + AT_CUDA_CHECK(cudaGetLastError()); + return std::make_tuple(idxs, dists); +} + +// ------------------------------------------------------------- // +// Backward Operators // +// ------------------------------------------------------------- // + +// TODO(gkioxari) support all data types once AtomicAdd supports doubles. +// Currently, support is for floats only. +__global__ void KNearestNeighborBackwardKernel( + const float* __restrict__ p1, // (N, P1, D) + const float* __restrict__ p2, // (N, P2, D) + const int64_t* __restrict__ lengths1, // (N,) + const int64_t* __restrict__ lengths2, // (N,) + const int64_t* __restrict__ idxs, // (N, P1, K) + const float* __restrict__ grad_dists, // (N, P1, K) + float* __restrict__ grad_p1, // (N, P1, D) + float* __restrict__ grad_p2, // (N, P2, D) + const size_t N, + const size_t P1, + const size_t P2, + const size_t K, + const size_t D, + const size_t norm) { + const size_t tid = blockIdx.x * blockDim.x + threadIdx.x; + const size_t stride = gridDim.x * blockDim.x; + + for (size_t i = tid; i < N * P1 * K * D; i += stride) { + const size_t n = i / (P1 * K * D); // batch index + size_t rem = i % (P1 * K * D); + const size_t p1_idx = rem / (K * D); // index of point in p1 + rem = rem % (K * D); + const size_t k = rem / D; // k-th nearest neighbor + const size_t d = rem % D; // d-th dimension in the feature vector + + const size_t num1 = lengths1[n]; // number of valid points in p1 in batch + const size_t num2 = lengths2[n]; // number of valid points in p2 in batch + if ((p1_idx < num1) && (k < num2)) { + const float grad_dist = grad_dists[n * P1 * K + p1_idx * K + k]; + // index of point in p2 corresponding to the k-th nearest neighbor + const int64_t p2_idx = idxs[n * P1 * K + p1_idx * K + k]; + // If the index is the pad value of -1 then ignore it + if (p2_idx == -1) { + continue; + } + float diff = 0.0; + if (norm == 1) { + float sign = + (p1[n * P1 * D + p1_idx * D + d] > p2[n * P2 * D + p2_idx * D + d]) + ? 1.0 + : -1.0; + diff = grad_dist * sign; + } else { // norm is 2 + diff = 2.0 * grad_dist * + (p1[n * P1 * D + p1_idx * D + d] - p2[n * P2 * D + p2_idx * D + d]); + } + atomicAdd(grad_p1 + n * P1 * D + p1_idx * D + d, diff); + atomicAdd(grad_p2 + n * P2 * D + p2_idx * D + d, -1.0f * diff); + } + } +} + +std::tuple KNearestNeighborBackwardCuda( + const at::Tensor& p1, + const at::Tensor& p2, + const at::Tensor& lengths1, + const at::Tensor& lengths2, + const at::Tensor& idxs, + int norm, + const at::Tensor& grad_dists) { + // Check inputs are on the same device + at::TensorArg p1_t{p1, "p1", 1}, p2_t{p2, "p2", 2}, + lengths1_t{lengths1, "lengths1", 3}, lengths2_t{lengths2, "lengths2", 4}, + idxs_t{idxs, "idxs", 5}, grad_dists_t{grad_dists, "grad_dists", 6}; + at::CheckedFrom c = "KNearestNeighborBackwardCuda"; + at::checkAllSameGPU( + c, {p1_t, p2_t, lengths1_t, lengths2_t, idxs_t, grad_dists_t}); + at::checkAllSameType(c, {p1_t, p2_t, grad_dists_t}); + + // This is nondeterministic because atomicAdd + at::globalContext().alertNotDeterministic("KNearestNeighborBackwardCuda"); + + // Set the device for the kernel launch based on the device of the input + at::cuda::CUDAGuard device_guard(p1.device()); + cudaStream_t stream = at::cuda::getCurrentCUDAStream(); + + const auto N = p1.size(0); + const auto P1 = p1.size(1); + const auto P2 = p2.size(1); + const auto D = p2.size(2); + const auto K = idxs.size(2); + + TORCH_CHECK(p1.size(2) == D, "Point sets must have the same last dimension"); + TORCH_CHECK(idxs.size(0) == N, "KNN idxs must have the same batch dimension"); + TORCH_CHECK( + idxs.size(1) == P1, "KNN idxs must have the same point dimension as p1"); + TORCH_CHECK(grad_dists.size(0) == N); + TORCH_CHECK(grad_dists.size(1) == P1); + TORCH_CHECK(grad_dists.size(2) == K); + + auto grad_p1 = at::zeros({N, P1, D}, p1.options()); + auto grad_p2 = at::zeros({N, P2, D}, p2.options()); + + if (grad_p1.numel() == 0 || grad_p2.numel() == 0) { + AT_CUDA_CHECK(cudaGetLastError()); + return std::make_tuple(grad_p1, grad_p2); + } + + const int blocks = 64; + const int threads = 512; + + KNearestNeighborBackwardKernel<<>>( + p1.contiguous().data_ptr(), + p2.contiguous().data_ptr(), + lengths1.contiguous().data_ptr(), + lengths2.contiguous().data_ptr(), + idxs.contiguous().data_ptr(), + grad_dists.contiguous().data_ptr(), + grad_p1.data_ptr(), + grad_p2.data_ptr(), + N, + P1, + P2, + K, + D, + norm); + + AT_CUDA_CHECK(cudaGetLastError()); + return std::make_tuple(grad_p1, grad_p2); +} \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/knn/src/knn.h b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/knn/src/knn.h new file mode 100644 index 0000000000000000000000000000000000000000..e43a0231119bf170502e1078d77110a3cd4510aa --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/knn/src/knn.h @@ -0,0 +1,157 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once +#include +#include +#include "utils/pytorch3d_cutils.h" + +// Compute indices of K nearest neighbors in pointcloud p2 to points +// in pointcloud p1. +// +// Args: +// p1: FloatTensor of shape (N, P1, D) giving a batch of pointclouds each +// containing P1 points of dimension D. +// p2: FloatTensor of shape (N, P2, D) giving a batch of pointclouds each +// containing P2 points of dimension D. +// lengths1: LongTensor, shape (N,), giving actual length of each P1 cloud. +// lengths2: LongTensor, shape (N,), giving actual length of each P2 cloud. +// norm: int specifying the norm for the distance (1 for L1, 2 for L2) +// K: int giving the number of nearest points to return. +// version: Integer telling which implementation to use. +// +// Returns: +// p1_neighbor_idx: LongTensor of shape (N, P1, K), where +// p1_neighbor_idx[n, i, k] = j means that the kth nearest +// neighbor to p1[n, i] in the cloud p2[n] is p2[n, j]. +// It is padded with zeros so that it can be used easily in a later +// gather() operation. +// +// p1_neighbor_dists: FloatTensor of shape (N, P1, K) containing the squared +// distance from each point p1[n, p, :] to its K neighbors +// p2[n, p1_neighbor_idx[n, p, k], :]. + +// CPU implementation. +std::tuple KNearestNeighborIdxCpu( + const at::Tensor& p1, + const at::Tensor& p2, + const at::Tensor& lengths1, + const at::Tensor& lengths2, + const int norm, + const int K); + +// CUDA implementation +std::tuple KNearestNeighborIdxCuda( + const at::Tensor& p1, + const at::Tensor& p2, + const at::Tensor& lengths1, + const at::Tensor& lengths2, + const int norm, + const int K, + const int version); + +// Implementation which is exposed. +std::tuple KNearestNeighborIdx( + const at::Tensor& p1, + const at::Tensor& p2, + const at::Tensor& lengths1, + const at::Tensor& lengths2, + const int norm, + const int K, + const int version) { + if (p1.is_cuda() || p2.is_cuda()) { +#ifdef WITH_CUDA + CHECK_CUDA(p1); + CHECK_CUDA(p2); + return KNearestNeighborIdxCuda( + p1, p2, lengths1, lengths2, norm, K, version); +#else + AT_ERROR("Not compiled with GPU support."); +#endif + } + return KNearestNeighborIdxCpu(p1, p2, lengths1, lengths2, norm, K); +} + +// Compute gradients with respect to p1 and p2 +// +// Args: +// p1: FloatTensor of shape (N, P1, D) giving a batch of pointclouds each +// containing P1 points of dimension D. +// p2: FloatTensor of shape (N, P2, D) giving a batch of pointclouds each +// containing P2 points of dimension D. +// lengths1: LongTensor, shape (N,), giving actual length of each P1 cloud. +// lengths2: LongTensor, shape (N,), giving actual length of each P2 cloud. +// p1_neighbor_idx: LongTensor of shape (N, P1, K), where +// p1_neighbor_idx[n, i, k] = j means that the kth nearest +// neighbor to p1[n, i] in the cloud p2[n] is p2[n, j]. +// It is padded with zeros so that it can be used easily in a later +// gather() operation. This is computed from the forward pass. +// norm: int specifying the norm for the distance (1 for L1, 2 for L2) +// grad_dists: FLoatTensor of shape (N, P1, K) which contains the input +// gradients. +// +// Returns: +// grad_p1: FloatTensor of shape (N, P1, D) containing the output gradients +// wrt p1. +// grad_p2: FloatTensor of shape (N, P2, D) containing the output gradients +// wrt p2. + +// CPU implementation. +std::tuple KNearestNeighborBackwardCpu( + const at::Tensor& p1, + const at::Tensor& p2, + const at::Tensor& lengths1, + const at::Tensor& lengths2, + const at::Tensor& idxs, + const int norm, + const at::Tensor& grad_dists); + +// CUDA implementation +std::tuple KNearestNeighborBackwardCuda( + const at::Tensor& p1, + const at::Tensor& p2, + const at::Tensor& lengths1, + const at::Tensor& lengths2, + const at::Tensor& idxs, + const int norm, + const at::Tensor& grad_dists); + +// Implementation which is exposed. +std::tuple KNearestNeighborBackward( + const at::Tensor& p1, + const at::Tensor& p2, + const at::Tensor& lengths1, + const at::Tensor& lengths2, + const at::Tensor& idxs, + const int norm, + const at::Tensor& grad_dists) { + if (p1.is_cuda() || p2.is_cuda()) { +#ifdef WITH_CUDA + CHECK_CUDA(p1); + CHECK_CUDA(p2); + return KNearestNeighborBackwardCuda( + p1, p2, lengths1, lengths2, idxs, norm, grad_dists); +#else + AT_ERROR("Not compiled with GPU support."); +#endif + } + return KNearestNeighborBackwardCpu( + p1, p2, lengths1, lengths2, idxs, norm, grad_dists); +} + +// Utility to check whether a KNN version can be used. +// +// Args: +// version: Integer in the range 0 <= version <= 3 indicating one of our +// KNN implementations. +// D: Number of dimensions for the input and query point clouds +// K: Number of neighbors to be found +// +// Returns: +// Whether the indicated KNN version can be used. +bool KnnCheckVersion(int version, const int64_t D, const int64_t K); \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/knn/src/knn_cpu.cpp b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/knn/src/knn_cpu.cpp new file mode 100644 index 0000000000000000000000000000000000000000..694ab11ea62c2eb285e1a03f6e4c0862498c24ae --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/knn/src/knn_cpu.cpp @@ -0,0 +1,128 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include +#include +#include + +std::tuple KNearestNeighborIdxCpu( + const at::Tensor& p1, + const at::Tensor& p2, + const at::Tensor& lengths1, + const at::Tensor& lengths2, + const int norm, + const int K) { + const int N = p1.size(0); + const int P1 = p1.size(1); + const int D = p1.size(2); + + auto long_opts = lengths1.options().dtype(torch::kInt64); + torch::Tensor idxs = torch::full({N, P1, K}, 0, long_opts); + torch::Tensor dists = torch::full({N, P1, K}, 0, p1.options()); + + auto p1_a = p1.accessor(); + auto p2_a = p2.accessor(); + auto lengths1_a = lengths1.accessor(); + auto lengths2_a = lengths2.accessor(); + auto idxs_a = idxs.accessor(); + auto dists_a = dists.accessor(); + + for (int n = 0; n < N; ++n) { + const int64_t length1 = lengths1_a[n]; + const int64_t length2 = lengths2_a[n]; + for (int64_t i1 = 0; i1 < length1; ++i1) { + // Use a priority queue to store (distance, index) tuples. + std::priority_queue> q; + for (int64_t i2 = 0; i2 < length2; ++i2) { + float dist = 0; + for (int d = 0; d < D; ++d) { + float diff = p1_a[n][i1][d] - p2_a[n][i2][d]; + if (norm == 1) { + dist += abs(diff); + } else { // norm is 2 (default) + dist += diff * diff; + } + } + int size = static_cast(q.size()); + if (size < K || dist < std::get<0>(q.top())) { + q.emplace(dist, i2); + if (size >= K) { + q.pop(); + } + } + } + while (!q.empty()) { + auto t = q.top(); + q.pop(); + const int k = q.size(); + dists_a[n][i1][k] = std::get<0>(t); + idxs_a[n][i1][k] = std::get<1>(t); + } + } + } + return std::make_tuple(idxs, dists); +} + +// ------------------------------------------------------------- // +// Backward Operators // +// ------------------------------------------------------------- // + +std::tuple KNearestNeighborBackwardCpu( + const at::Tensor& p1, + const at::Tensor& p2, + const at::Tensor& lengths1, + const at::Tensor& lengths2, + const at::Tensor& idxs, + const int norm, + const at::Tensor& grad_dists) { + const int N = p1.size(0); + const int P1 = p1.size(1); + const int D = p1.size(2); + const int P2 = p2.size(1); + const int K = idxs.size(2); + + torch::Tensor grad_p1 = torch::full({N, P1, D}, 0, p1.options()); + torch::Tensor grad_p2 = torch::full({N, P2, D}, 0, p2.options()); + + auto p1_a = p1.accessor(); + auto p2_a = p2.accessor(); + auto lengths1_a = lengths1.accessor(); + auto lengths2_a = lengths2.accessor(); + auto idxs_a = idxs.accessor(); + auto grad_dists_a = grad_dists.accessor(); + auto grad_p1_a = grad_p1.accessor(); + auto grad_p2_a = grad_p2.accessor(); + + for (int n = 0; n < N; ++n) { + const int64_t length1 = lengths1_a[n]; + int64_t length2 = lengths2_a[n]; + length2 = (length2 < K) ? length2 : K; + for (int64_t i1 = 0; i1 < length1; ++i1) { + for (int64_t k = 0; k < length2; ++k) { + const int64_t i2 = idxs_a[n][i1][k]; + // If the index is the pad value of -1 then ignore it + if (i2 == -1) { + continue; + } + for (int64_t d = 0; d < D; ++d) { + float diff = 0.0; + if (norm == 1) { + float sign = (p1_a[n][i1][d] > p2_a[n][i2][d]) ? 1.0 : -1.0; + diff = grad_dists_a[n][i1][k] * sign; + } else { // norm is 2 (default) + diff = 2.0f * grad_dists_a[n][i1][k] * + (p1_a[n][i1][d] - p2_a[n][i2][d]); + } + grad_p1_a[n][i1][d] += diff; + grad_p2_a[n][i2][d] += -1.0f * diff; + } + } + } + } + return std::make_tuple(grad_p1, grad_p2); +} \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/knn/src/knn_ext.cpp b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/knn/src/knn_ext.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f2fc9b4374ea5a2196d8ddee4e3cd5c0a907ddaa --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/knn/src/knn_ext.cpp @@ -0,0 +1,10 @@ +#include +#include "knn.h" + +PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { +#ifdef WITH_CUDA + m.def("knn_check_version", &KnnCheckVersion); +#endif + m.def("knn_points_idx", &KNearestNeighborIdx); + m.def("knn_points_backward", &KNearestNeighborBackward); +} \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/knn/src/utils/dispatch.cuh b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/knn/src/utils/dispatch.cuh new file mode 100644 index 0000000000000000000000000000000000000000..af197b4392106391236f9f00d999a02e6ac2defa --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/knn/src/utils/dispatch.cuh @@ -0,0 +1,357 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +// This file provides utilities for dispatching to specialized versions of +// functions. This is especially useful for CUDA kernels, since specializing +// them to particular input sizes can often allow the compiler to unroll loops +// and place arrays into registers, which can give huge performance speedups. +// +// As an example, suppose we have the following function which is specialized +// based on a compile-time int64_t value: +// +// template +// struct SquareOffset { +// static void run(T y) { +// T val = x * x + y; +// std::cout << val << std::endl; +// } +// } +// +// This function takes one compile-time argument x, and one run-time argument y. +// We might want to compile specialized versions of this for x=0, x=1, etc and +// then dispatch to the correct one based on the runtime value of x. +// One simple way to achieve this is with a lookup table: +// +// template +// void DispatchSquareOffset(const int64_t x, T y) { +// if (x == 0) { +// SquareOffset::run(y); +// } else if (x == 1) { +// SquareOffset::run(y); +// } else if (x == 2) { +// SquareOffset::run(y); +// } +// } +// +// This function takes both x and y as run-time arguments, and dispatches to +// different specialized versions of SquareOffset based on the run-time value +// of x. This works, but it's tedious and error-prone. If we want to change the +// set of x values for which we provide compile-time specializations, then we +// will need to do a lot of tedius editing of the dispatch function. Also, if we +// want to provide compile-time specializations for another function other than +// SquareOffset, we will need to duplicate the entire lookup table. +// +// To solve these problems, we can use the DispatchKernel1D function provided by +// this file instead: +// +// template +// void DispatchSquareOffset(const int64_t x, T y) { +// constexpr int64_t xmin = 0; +// constexpr int64_t xmax = 2; +// DispatchKernel1D(x, y); +// } +// +// DispatchKernel1D uses template metaprogramming to compile specialized +// versions of SquareOffset for all values of x with xmin <= x <= xmax, and +// then dispatches to the correct one based on the run-time value of x. If we +// want to change the range of x values for which SquareOffset is specialized +// at compile-time, then all we have to do is change the values of the +// compile-time constants xmin and xmax. +// +// This file also allows us to similarly dispatch functions that depend on two +// compile-time int64_t values, using the DispatchKernel2D function like this: +// +// template +// struct Sum { +// static void run(T z, T w) { +// T val = x + y + z + w; +// std::cout << val << std::endl; +// } +// } +// +// template +// void DispatchSum(const int64_t x, const int64_t y, int z, int w) { +// constexpr int64_t xmin = 1; +// constexpr int64_t xmax = 3; +// constexpr int64_t ymin = 2; +// constexpr int64_t ymax = 5; +// DispatchKernel2D(x, y, z, w); +// } +// +// Like its 1D counterpart, DispatchKernel2D uses template metaprogramming to +// compile specialized versions of sum for all values of (x, y) with +// xmin <= x <= xmax and ymin <= y <= ymax, then dispatches to the correct +// specialized version based on the runtime values of x and y. + +// Define some helper structs in an anonymous namespace. +namespace { + +// 1D dispatch: general case. +// Kernel is the function we want to dispatch to; it should take a typename and +// an int64_t as template args, and it should define a static void function +// run which takes any number of arguments of any type. +// In order to dispatch, we will take an additional template argument curN, +// and increment it via template recursion until it is equal to the run-time +// argument N. +template < + template + class Kernel, + typename T, + int64_t minN, + int64_t maxN, + int64_t curN, + typename... Args> +struct DispatchKernelHelper1D { + static void run(const int64_t N, Args... args) { + if (curN == N) { + // The compile-time value curN is equal to the run-time value N, so we + // can dispatch to the run method of the Kernel. + Kernel::run(args...); + } else if (curN < N) { + // Increment curN via template recursion + DispatchKernelHelper1D::run( + N, args...); + } + // We shouldn't get here -- throw an error? + } +}; + +// 1D dispatch: Specialization when curN == maxN +// We need this base case to avoid infinite template recursion. +template < + template + class Kernel, + typename T, + int64_t minN, + int64_t maxN, + typename... Args> +struct DispatchKernelHelper1D { + static void run(const int64_t N, Args... args) { + if (N == maxN) { + Kernel::run(args...); + } + // We shouldn't get here -- throw an error? + } +}; + +// 2D dispatch, general case. +// This is similar to the 1D case: we take additional template args curN and +// curM, and increment them via template recursion until they are equal to +// the run-time values of N and M, at which point we dispatch to the run +// method of the kernel. +template < + template + class Kernel, + typename T, + int64_t minN, + int64_t maxN, + int64_t curN, + int64_t minM, + int64_t maxM, + int64_t curM, + typename... Args> +struct DispatchKernelHelper2D { + static void run(const int64_t N, const int64_t M, Args... args) { + if (curN == N && curM == M) { + Kernel::run(args...); + } else if (curN < N && curM < M) { + // Increment both curN and curM. This isn't strictly necessary; we could + // just increment one or the other at each step. But this helps to cut + // on the number of recursive calls we make. + DispatchKernelHelper2D< + Kernel, + T, + minN, + maxN, + curN + 1, + minM, + maxM, + curM + 1, + Args...>::run(N, M, args...); + } else if (curN < N) { + // Increment curN only + DispatchKernelHelper2D< + Kernel, + T, + minN, + maxN, + curN + 1, + minM, + maxM, + curM, + Args...>::run(N, M, args...); + } else if (curM < M) { + // Increment curM only + DispatchKernelHelper2D< + Kernel, + T, + minN, + maxN, + curN, + minM, + maxM, + curM + 1, + Args...>::run(N, M, args...); + } + } +}; + +// 2D dispatch, specialization for curN == maxN +template < + template + class Kernel, + typename T, + int64_t minN, + int64_t maxN, + int64_t minM, + int64_t maxM, + int64_t curM, + typename... Args> +struct DispatchKernelHelper2D< + Kernel, + T, + minN, + maxN, + maxN, + minM, + maxM, + curM, + Args...> { + static void run(const int64_t N, const int64_t M, Args... args) { + if (maxN == N && curM == M) { + Kernel::run(args...); + } else if (curM < maxM) { + DispatchKernelHelper2D< + Kernel, + T, + minN, + maxN, + maxN, + minM, + maxM, + curM + 1, + Args...>::run(N, M, args...); + } + // We should not get here -- throw an error? + } +}; + +// 2D dispatch, specialization for curM == maxM +template < + template + class Kernel, + typename T, + int64_t minN, + int64_t maxN, + int64_t curN, + int64_t minM, + int64_t maxM, + typename... Args> +struct DispatchKernelHelper2D< + Kernel, + T, + minN, + maxN, + curN, + minM, + maxM, + maxM, + Args...> { + static void run(const int64_t N, const int64_t M, Args... args) { + if (curN == N && maxM == M) { + Kernel::run(args...); + } else if (curN < maxN) { + DispatchKernelHelper2D< + Kernel, + T, + minN, + maxN, + curN + 1, + minM, + maxM, + maxM, + Args...>::run(N, M, args...); + } + // We should not get here -- throw an error? + } +}; + +// 2D dispatch, specialization for curN == maxN, curM == maxM +template < + template + class Kernel, + typename T, + int64_t minN, + int64_t maxN, + int64_t minM, + int64_t maxM, + typename... Args> +struct DispatchKernelHelper2D< + Kernel, + T, + minN, + maxN, + maxN, + minM, + maxM, + maxM, + Args...> { + static void run(const int64_t N, const int64_t M, Args... args) { + if (maxN == N && maxM == M) { + Kernel::run(args...); + } + // We should not get here -- throw an error? + } +}; + +} // namespace + +// This is the function we expect users to call to dispatch to 1D functions +template < + template + class Kernel, + typename T, + int64_t minN, + int64_t maxN, + typename... Args> +void DispatchKernel1D(const int64_t N, Args... args) { + if (minN <= N && N <= maxN) { + // Kick off the template recursion by calling the Helper with curN = minN + DispatchKernelHelper1D::run( + N, args...); + } + // Maybe throw an error if we tried to dispatch outside the allowed range? +} + +// This is the function we expect users to call to dispatch to 2D functions +template < + template + class Kernel, + typename T, + int64_t minN, + int64_t maxN, + int64_t minM, + int64_t maxM, + typename... Args> +void DispatchKernel2D(const int64_t N, const int64_t M, Args... args) { + if (minN <= N && N <= maxN && minM <= M && M <= maxM) { + // Kick off the template recursion by calling the Helper with curN = minN + // and curM = minM + DispatchKernelHelper2D< + Kernel, + T, + minN, + maxN, + minN, + minM, + maxM, + minM, + Args...>::run(N, M, args...); + } + // Maybe throw an error if we tried to dispatch outside the specified range? +} \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/knn/src/utils/index_utils.cuh b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/knn/src/utils/index_utils.cuh new file mode 100644 index 0000000000000000000000000000000000000000..d3f7f7afa0d9fdc8c2c23187cd1c12d2ccd670f5 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/knn/src/utils/index_utils.cuh @@ -0,0 +1,224 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +// This converts dynamic array lookups into static array lookups, for small +// arrays up to size 32. +// +// Suppose we have a small thread-local array: +// +// float vals[10]; +// +// Ideally we should only index this array using static indices: +// +// for (int i = 0; i < 10; ++i) vals[i] = i * i; +// +// If we do so, then the CUDA compiler may be able to place the array into +// registers, which can have a big performance improvement. However if we +// access the array dynamically, the the compiler may force the array into +// local memory, which has the same latency as global memory. +// +// These functions convert dynamic array access into static array access +// using a brute-force lookup table. It can be used like this: +// +// float vals[10]; +// int idx = 3; +// float val = 3.14f; +// RegisterIndexUtils::set(vals, idx, val); +// float val2 = RegisterIndexUtils::get(vals, idx); +// +// The implementation is based on fbcuda/RegisterUtils.cuh: +// https://github.com/facebook/fbcuda/blob/master/RegisterUtils.cuh +// To avoid depending on the entire library, we just reimplement these two +// functions. The fbcuda implementation is a bit more sophisticated, and uses +// the preprocessor to generate switch statements that go up to N for each +// value of N. We are lazy and just have a giant explicit switch statement. +// +// We might be able to use a template metaprogramming approach similar to +// DispatchKernel1D for this. However DispatchKernel1D is intended to be used +// for dispatching to the correct CUDA kernel on the host, while this is +// is intended to run on the device. I was concerned that a metaprogramming +// approach for this might lead to extra function calls at runtime if the +// compiler fails to optimize them away, which could be very slow on device. +// However I didn't actually benchmark or test this. +template +struct RegisterIndexUtils { + __device__ __forceinline__ static T get(const T arr[N], int idx) { + if (idx < 0 || idx >= N) + return T(); + switch (idx) { + case 0: + return arr[0]; + case 1: + return arr[1]; + case 2: + return arr[2]; + case 3: + return arr[3]; + case 4: + return arr[4]; + case 5: + return arr[5]; + case 6: + return arr[6]; + case 7: + return arr[7]; + case 8: + return arr[8]; + case 9: + return arr[9]; + case 10: + return arr[10]; + case 11: + return arr[11]; + case 12: + return arr[12]; + case 13: + return arr[13]; + case 14: + return arr[14]; + case 15: + return arr[15]; + case 16: + return arr[16]; + case 17: + return arr[17]; + case 18: + return arr[18]; + case 19: + return arr[19]; + case 20: + return arr[20]; + case 21: + return arr[21]; + case 22: + return arr[22]; + case 23: + return arr[23]; + case 24: + return arr[24]; + case 25: + return arr[25]; + case 26: + return arr[26]; + case 27: + return arr[27]; + case 28: + return arr[28]; + case 29: + return arr[29]; + case 30: + return arr[30]; + case 31: + return arr[31]; + }; + return T(); + } + + __device__ __forceinline__ static void set(T arr[N], int idx, T val) { + if (idx < 0 || idx >= N) + return; + switch (idx) { + case 0: + arr[0] = val; + break; + case 1: + arr[1] = val; + break; + case 2: + arr[2] = val; + break; + case 3: + arr[3] = val; + break; + case 4: + arr[4] = val; + break; + case 5: + arr[5] = val; + break; + case 6: + arr[6] = val; + break; + case 7: + arr[7] = val; + break; + case 8: + arr[8] = val; + break; + case 9: + arr[9] = val; + break; + case 10: + arr[10] = val; + break; + case 11: + arr[11] = val; + break; + case 12: + arr[12] = val; + break; + case 13: + arr[13] = val; + break; + case 14: + arr[14] = val; + break; + case 15: + arr[15] = val; + break; + case 16: + arr[16] = val; + break; + case 17: + arr[17] = val; + break; + case 18: + arr[18] = val; + break; + case 19: + arr[19] = val; + break; + case 20: + arr[20] = val; + break; + case 21: + arr[21] = val; + break; + case 22: + arr[22] = val; + break; + case 23: + arr[23] = val; + break; + case 24: + arr[24] = val; + break; + case 25: + arr[25] = val; + break; + case 26: + arr[26] = val; + break; + case 27: + arr[27] = val; + break; + case 28: + arr[28] = val; + break; + case 29: + arr[29] = val; + break; + case 30: + arr[30] = val; + break; + case 31: + arr[31] = val; + break; + } + } +}; \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/knn/src/utils/mink.cuh b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/knn/src/utils/mink.cuh new file mode 100644 index 0000000000000000000000000000000000000000..7512aabc2ca2a536eba8b4f14562ef47718cd064 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/knn/src/utils/mink.cuh @@ -0,0 +1,165 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once +#define MINK_H + +#include "index_utils.cuh" + +// A data structure to keep track of the smallest K keys seen so far as well +// as their associated values, intended to be used in device code. +// This data structure doesn't allocate any memory; keys and values are stored +// in arrays passed to the constructor. +// +// The implementation is generic; it can be used for any key type that supports +// the < operator, and can be used with any value type. +// +// Example usage: +// +// float keys[K]; +// int values[K]; +// MinK mink(keys, values, K); +// for (...) { +// // Produce some key and value from somewhere +// mink.add(key, value); +// } +// mink.sort(); +// +// Now keys and values store the smallest K keys seen so far and the values +// associated to these keys: +// +// for (int k = 0; k < K; ++k) { +// float key_k = keys[k]; +// int value_k = values[k]; +// } +template +class MinK { + public: + // Constructor. + // + // Arguments: + // keys: Array in which to store keys + // values: Array in which to store values + // K: How many values to keep track of + __device__ MinK(key_t* keys, value_t* vals, int K) + : keys(keys), vals(vals), K(K), _size(0) {} + + // Try to add a new key and associated value to the data structure. If the key + // is one of the smallest K seen so far then it will be kept; otherwise it + // it will not be kept. + // + // This takes O(1) operations if the new key is not kept, or if the structure + // currently contains fewer than K elements. Otherwise this takes O(K) time. + // + // Arguments: + // key: The key to add + // val: The value associated to the key + __device__ __forceinline__ void add(const key_t& key, const value_t& val) { + if (_size < K) { + keys[_size] = key; + vals[_size] = val; + if (_size == 0 || key > max_key) { + max_key = key; + max_idx = _size; + } + _size++; + } else if (key < max_key) { + keys[max_idx] = key; + vals[max_idx] = val; + max_key = key; + for (int k = 0; k < K; ++k) { + key_t cur_key = keys[k]; + if (cur_key > max_key) { + max_key = cur_key; + max_idx = k; + } + } + } + } + + // Get the number of items currently stored in the structure. + // This takes O(1) time. + __device__ __forceinline__ int size() { + return _size; + } + + // Sort the items stored in the structure using bubble sort. + // This takes O(K^2) time. + __device__ __forceinline__ void sort() { + for (int i = 0; i < _size - 1; ++i) { + for (int j = 0; j < _size - i - 1; ++j) { + if (keys[j + 1] < keys[j]) { + key_t key = keys[j]; + value_t val = vals[j]; + keys[j] = keys[j + 1]; + vals[j] = vals[j + 1]; + keys[j + 1] = key; + vals[j + 1] = val; + } + } + } + } + + private: + key_t* keys; + value_t* vals; + int K; + int _size; + key_t max_key; + int max_idx; +}; + +// This is a version of MinK that only touches the arrays using static indexing +// via RegisterIndexUtils. If the keys and values are stored in thread-local +// arrays, then this may allow the compiler to place them in registers for +// fast access. +// +// This has the same API as RegisterMinK, but doesn't support sorting. +// We found that sorting via RegisterIndexUtils gave very poor performance, +// and suspect it may have prevented the compiler from placing the arrays +// into registers. +template +class RegisterMinK { + public: + __device__ RegisterMinK(key_t* keys, value_t* vals) + : keys(keys), vals(vals), _size(0) {} + + __device__ __forceinline__ void add(const key_t& key, const value_t& val) { + if (_size < K) { + RegisterIndexUtils::set(keys, _size, key); + RegisterIndexUtils::set(vals, _size, val); + if (_size == 0 || key > max_key) { + max_key = key; + max_idx = _size; + } + _size++; + } else if (key < max_key) { + RegisterIndexUtils::set(keys, max_idx, key); + RegisterIndexUtils::set(vals, max_idx, val); + max_key = key; + for (int k = 0; k < K; ++k) { + key_t cur_key = RegisterIndexUtils::get(keys, k); + if (cur_key > max_key) { + max_key = cur_key; + max_idx = k; + } + } + } + } + + __device__ __forceinline__ int size() { + return _size; + } + + private: + key_t* keys; + value_t* vals; + int _size; + key_t max_key; + int max_idx; +}; \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/knn/src/utils/pytorch3d_cutils.h b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/knn/src/utils/pytorch3d_cutils.h new file mode 100644 index 0000000000000000000000000000000000000000..c46b5aea5682bbef6960c7eb2cc1bf052fb6e32a --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/knn/src/utils/pytorch3d_cutils.h @@ -0,0 +1,17 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once +#include + +#define CHECK_CUDA(x) TORCH_CHECK(x.is_cuda(), #x " must be a CUDA tensor.") +#define CHECK_CONTIGUOUS(x) \ + TORCH_CHECK(x.is_contiguous(), #x " must be contiguous.") +#define CHECK_CONTIGUOUS_CUDA(x) \ + CHECK_CUDA(x); \ + CHECK_CONTIGUOUS(x) \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/losses/__init__.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/losses/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9ae1e082e035a6678ac68e21562af4a23d403cc3 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/losses/__init__.py @@ -0,0 +1,7 @@ +from .arel import ARel +from .confidence import Confidence +from .distill import SelfDistill, TeacherDistill +from .dummy import Dummy +from .local_ssi import EdgeGuidedLocalSSI, LocalSSI +from .regression import Regression +from .silog import SILog diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/losses/arel.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/losses/arel.py new file mode 100644 index 0000000000000000000000000000000000000000..9d9c0d9fb51c1868e215746149abdb90c3c917e3 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/losses/arel.py @@ -0,0 +1,46 @@ +import torch +import torch.nn as nn + +from .utils import FNS, masked_mean + + +class ARel(nn.Module): + def __init__( + self, + weight: float, + output_fn: str = "sqrt", + input_fn: str = "linear", + eps: float = 1e-5, + ): + super().__init__() + self.name: str = self.__class__.__name__ + self.weight: float = weight + self.dims = [-2, -1] + self.output_fn = FNS[output_fn] + self.input_fn = FNS[input_fn] + self.eps: float = eps + + @torch.autocast(device_type="cuda", enabled=False, dtype=torch.float32) + def forward( + self, input: torch.Tensor, target: torch.Tensor, mask: torch.Tensor, **kwargs + ) -> torch.Tensor: + mask = mask.bool().clone() + + input = self.input_fn(input.float()) + target = self.input_fn(target.float()) + + error = (input - target).norm(dim=1) / target.norm(dim=1).clip(min=0.05) + mask = mask.squeeze(1) + + error_image = masked_mean(data=error, mask=mask, dim=self.dims).squeeze(1, 2) + error_image = self.output_fn(error_image) + return error_image + + @classmethod + def build(cls, config): + obj = cls( + weight=config["weight"], + output_fn=config["output_fn"], + input_fn=config["input_fn"], + ) + return obj diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/losses/confidence.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/losses/confidence.py new file mode 100644 index 0000000000000000000000000000000000000000..dca6ea4f63fadc10b3916e82ef2b82f076137219 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/losses/confidence.py @@ -0,0 +1,63 @@ +import torch +import torch.nn as nn + +from .utils import FNS, masked_mean + + +class Confidence(nn.Module): + def __init__( + self, + weight: float, + output_fn: str = "sqrt", + input_fn: str = "linear", + rescale: bool = True, + eps: float = 1e-5, + ): + super(Confidence, self).__init__() + self.name: str = self.__class__.__name__ + self.weight = weight + self.rescale = rescale + self.eps = eps + self.output_fn = FNS[output_fn] + self.input_fn = FNS[input_fn] + + @torch.autocast(device_type="cuda", enabled=False, dtype=torch.float32) + def forward( + self, + input: torch.Tensor, + target_pred: torch.Tensor, + target_gt: torch.Tensor, + mask: torch.Tensor, + ): + B, C = target_gt.shape[:2] + mask = mask.bool() + target_gt = target_gt.float().reshape(B, C, -1) + target_pred = target_pred.float().reshape(B, C, -1) + input = input.float().reshape(B, -1) + mask = mask.reshape(B, -1) + + if self.rescale: + target_pred = torch.stack( + [ + p * torch.median(gt[:, m]) / torch.median(p[:, m]) + for p, gt, m in zip(target_pred, target_gt, mask) + ] + ) + + error = torch.abs( + (self.input_fn(target_pred) - self.input_fn(target_gt)).norm(dim=1) - input + ) + losses = masked_mean(error, dim=[-1], mask=mask).squeeze(dim=-1) + losses = self.output_fn(losses) + + return losses + + @classmethod + def build(cls, config): + obj = cls( + weight=config["weight"], + output_fn=config["output_fn"], + input_fn=config["input_fn"], + rescale=config.get("rescale", True), + ) + return obj diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/losses/distill.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/losses/distill.py new file mode 100644 index 0000000000000000000000000000000000000000..6871a34f81f2e017ca4953ded4f9fc24c411d53b --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/losses/distill.py @@ -0,0 +1,221 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F +from einops import rearrange + +from .utils import FNS, masked_mean + + +class SelfDistill(nn.Module): + def __init__(self, weight: float, output_fn: str = "sqrt", eps: float = 1e-5): + super().__init__() + self.name: str = self.__class__.__name__ + self.weight: float = weight + self.dims = (-2, -1) + self.output_fn = FNS[output_fn] + self.eps: float = eps + + @torch.autocast(device_type="cuda", enabled=False, dtype=torch.float32) + def forward( + self, + input: torch.Tensor, + intrinsics: torch.Tensor, + mask: torch.Tensor, + flips: torch.Tensor, + downsample_ratio=14, + ) -> torch.Tensor: + chunks = input.shape[0] // 2 + mask = F.interpolate(mask.float(), size=input.shape[-2:], mode="nearest") + + iters = zip( + input.chunk(chunks), + mask.chunk(chunks), + intrinsics.chunk(chunks), + flips.chunk(chunks), + ) + inputs0, inputs1, masks = [], [], [] + for i, (pair_input, pair_mask, pair_cam, pair_flip) in enumerate(iters): + + mask0, mask1 = pair_mask + input0, input1 = pair_input + cam0, cam1 = pair_cam + flip0, flip1 = pair_flip + + fx_0 = cam0[0, 0] / downsample_ratio + fx_1 = cam1[0, 0] / downsample_ratio + cx_0 = cam0[0, 2] / downsample_ratio + cx_1 = cam1[0, 2] / downsample_ratio + cy_0 = cam0[1, 2] / downsample_ratio + cy_1 = cam1[1, 2] / downsample_ratio + + # flip image + if flip0 ^ flip1: + input0 = torch.flip(input0, dims=(2,)) + mask0 = torch.flip(mask0, dims=(2,)) + cx_0 = input0.shape[-1] - cx_0 + + # calc zoom + zoom_x = float(fx_1 / fx_0) + + # apply zoom + input0 = F.interpolate( + input0.unsqueeze(0), scale_factor=zoom_x, mode="bilinear" + ).squeeze(0) + mask0 = F.interpolate( + mask0.unsqueeze(0), scale_factor=zoom_x, mode="nearest" + ).squeeze(0) + + # calc translation + change_left = int(cx_1 - (cx_0 - 0.5) * zoom_x - 0.5) + change_top = int(cy_1 - (cy_0 - 0.5) * zoom_x - 0.5) + change_right = input1.shape[-1] - change_left - input0.shape[-1] + change_bottom = input1.shape[-2] - change_top - input0.shape[-2] + + # apply translation + pad_left = max(0, change_left) + pad_right = max(0, change_right) + pad_top = max(0, change_top) + pad_bottom = max(0, change_bottom) + + crop_left = max(0, -change_left) + crop_right = max(0, -change_right) + crop_top = max(0, -change_top) + crop_bottom = max(0, -change_bottom) + + input0 = F.pad( + input0, + (pad_left, pad_right, pad_top, pad_bottom), + mode="constant", + value=0, + ) + mask0 = F.pad( + mask0, + (pad_left, pad_right, pad_top, pad_bottom), + mode="constant", + value=0, + ) + input0 = input0[ + :, + crop_top : input0.shape[-2] - crop_bottom, + crop_left : input0.shape[-1] - crop_right, + ] + mask0 = mask0[ + :, + crop_top : mask0.shape[-2] - crop_bottom, + crop_left : mask0.shape[-1] - crop_right, + ] + + mask = torch.logical_and(mask0, mask1) + + inputs0.append(input0) + inputs1.append(input1) + masks.append(mask) + + inputs0 = torch.stack(inputs0, dim=0) + inputs1 = torch.stack(inputs1, dim=0) + masks = torch.stack(masks, dim=0) + loss1 = self.loss(inputs0, inputs1.detach(), masks) + loss2 = self.loss(inputs1, inputs0.detach(), masks) + return torch.cat([loss1, loss2], dim=0) + + def loss( + self, + input: torch.Tensor, + target: torch.Tensor, + mask: torch.Tensor, + ) -> torch.Tensor: + loss = masked_mean( + (input - target).square().mean(dim=1), mask=mask, dim=[-2, -1] + ) + return self.output_fn(loss + self.eps) + + @classmethod + def build(cls, config): + obj = cls( + weight=config["weight"], + output_fn=config["output_fn"], + ) + return obj + + +class TeacherDistill(nn.Module): + def __init__( + self, + weight: float, + output_fn: str = "sqrt", + cross: bool = False, + eps: float = 1e-5, + ): + super().__init__() + assert output_fn in FNS + self.name: str = self.__class__.__name__ + self.weight: float = weight + self.dims = (-2, -1) + self.output_fn = FNS[output_fn] + self.eps: float = eps + self.cross = cross + self.threshold = 0.05 + self.head_dim = 64 # hardcoded for vit + + @torch.autocast(device_type="cuda", enabled=False, dtype=torch.float32) + def forward( + self, + student_features: torch.Tensor, + teacher_features: torch.Tensor, + student_tokens: torch.Tensor, + teacher_tokens: torch.Tensor, + mask: torch.Tensor, + # metas: List[Dict[str, torch.Tensor]], + ) -> torch.Tensor: + B = student_features.shape[0] + device = student_features.device + chunks = student_features.shape[0] // 2 + + mask = ( + F.interpolate( + mask.float() + 1e-3, size=student_features.shape[-2:], mode="nearest" + ) + > 0.5 + ) + + # chunk features as self.head_dim + student_features = rearrange( + student_features, "b (n c) h w -> b c h w n", c=self.head_dim + ) + teacher_features = rearrange( + teacher_features, "b (n c) h w -> b c h w n", c=self.head_dim + ) + student_tokens = rearrange( + student_tokens, "b t (n c) -> b t c n", c=self.head_dim + ) + teacher_tokens = rearrange( + teacher_tokens, "b t (n c) -> b t c n", c=self.head_dim + ) + + distance = ( + (student_features - teacher_features) + .square() + .sum(dim=1, keepdim=True) + .sqrt() + .mean(dim=-1) + ) + loss_features = masked_mean(distance, mask=mask, dim=[-2, -1]) + loss_features = self.output_fn(loss_features.clamp(min=self.eps)).squeeze( + 1, 2, 3 + ) + + distance = ( + (student_tokens - teacher_tokens).square().sum(dim=-2).sqrt().mean(dim=-1) + ) + loss_tokens = self.output_fn(distance.clamp(min=self.eps)).squeeze(1) + + return loss_features + 0.01 * loss_tokens + + @classmethod + def build(cls, config): + obj = cls( + weight=config["weight"], + output_fn=config["output_fn"], + cross=config["cross"], + ) + return obj diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/losses/dummy.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/losses/dummy.py new file mode 100644 index 0000000000000000000000000000000000000000..77a4c99dc888bf2a5d80c7d324257db863622d28 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/losses/dummy.py @@ -0,0 +1,17 @@ +import torch +import torch.nn as nn + + +class Dummy(nn.Module): + def __init__(self, *args, **kwargs): + super().__init__() + self.name: str = self.__class__.__name__ + self.weight = 1.0 + + def forward(self, dummy: torch.Tensor, *args, **kwargs) -> torch.Tensor: + return torch.tensor([0.0] * dummy.shape[0], device=dummy.device) + + @classmethod + def build(cls, config): + obj = cls() + return obj diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/losses/local_ssi.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/losses/local_ssi.py new file mode 100644 index 0000000000000000000000000000000000000000..78bdd057d4d8984965d7e224c61181e455793c7c --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/losses/local_ssi.py @@ -0,0 +1,362 @@ +import numpy as np +import torch +import torch.nn as nn +import torch.nn.functional as F + +from unidepth.utils.geometric import erode + +from .utils import FNS, ind2sub, masked_mean, masked_quantile, ssi + + +def sample_strong_edges(edges_img, quantile=0.95, reshape=8): + # flat + edges_img = F.interpolate( + edges_img, scale_factor=1 / reshape, mode="bilinear", align_corners=False + ) + edges_img_flat = edges_img.flatten(1) + + # Find strong edges + edges_mask = edges_img_flat > torch.quantile( + edges_img_flat, quantile, dim=-1, keepdim=True + ) + num_samples = edges_mask.sum(dim=-1) + if (num_samples < 10).any(): + # sample random edges where num_samples < 2 + random = torch.rand_like(edges_img_flat[num_samples < 10, :]) > quantile + edges_mask[num_samples < 10, :] = torch.logical_or( + edges_mask[num_samples < 10, :], random + ) + num_samples = edges_mask.sum(dim=-1) + + min_samples = num_samples.min() + + # Compute the coordinates of the strong edges as B, N, 2 + edges_coords = torch.stack( + [torch.nonzero(x, as_tuple=False)[:min_samples].squeeze() for x in edges_mask] + ) + edges_coords = ( + torch.stack(ind2sub(edges_coords, edges_img.shape[-1]), dim=-1) * reshape + ) + return edges_coords + + +@torch.jit.script +def extract_patches(tensor, sample_coords, patch_size: tuple[int, int] = (32, 32)): + N, _, H, W = tensor.shape + device = tensor.device + dtype = tensor.dtype + patch_width, patch_height = patch_size + pad_width = patch_width // 2 + pad_height = patch_height // 2 + + # Pad the RGB images for both sheep + tensor_padded = F.pad( + tensor, + (pad_width, pad_width, pad_height, pad_height), + mode="constant", + value=0.0, + ) + + # Adjust edge coordinates to account for padding + sample_coords_padded = sample_coords + torch.tensor( + [pad_height, pad_width], dtype=dtype, device=device + ).reshape(1, 1, 2) + + # Calculate the indices for gather operation + x_centers = sample_coords_padded[:, :, 1].int() + y_centers = sample_coords_padded[:, :, 0].int() + + all_patches = [] + for tensor_i, x_centers_i, y_centers_i in zip(tensor_padded, x_centers, y_centers): + patches = [] + for x_center, y_center in zip(x_centers_i, y_centers_i): + y_start, y_end = y_center - pad_height, y_center + pad_height + 1 + x_start, x_end = x_center - pad_width, x_center + pad_width + 1 + patches.append(tensor_i[..., y_start:y_end, x_start:x_end]) + all_patches.append(torch.stack(patches, dim=0)) + + return torch.stack(all_patches, dim=0).reshape(N, -1, patch_height * patch_width) + + +class LocalSSI(nn.Module): + def __init__( + self, + weight: float, + output_fn: str = "sqrt", + patch_size: tuple[int, int] = (32, 32), + min_samples: int = 4, + num_levels: int = 4, + input_fn: str = "linear", + eps: float = 1e-5, + ): + super(LocalSSI, self).__init__() + self.name: str = self.__class__.__name__ + self.weight = weight + self.output_fn = FNS[output_fn] + self.input_fn = FNS[input_fn] + self.min_samples = min_samples + self.eps = eps + patch_logrange = np.linspace( + start=np.log2(min(patch_size)), + stop=np.log2(max(patch_size)), + endpoint=True, + num=num_levels + 1, + ) + self.patch_logrange = [ + (x, y) for x, y in zip(patch_logrange[:-1], patch_logrange[1:]) + ] + self.rescale_fn = ssi + + @torch.autocast(device_type="cuda", enabled=False, dtype=torch.float32) + def forward( + self, + input: torch.Tensor, + target: torch.Tensor, + mask: torch.Tensor, + *args, + **kwargs, + ) -> torch.Tensor: + mask = mask.bool() + input = self.input_fn(input.float()) + target = self.input_fn(target.float()) + B, C, H, W = input.shape + total_errors = [] + + for ii, patch_logrange in enumerate(self.patch_logrange): + + log_kernel = ( + np.random.uniform(*patch_logrange) + if self.training + else np.mean(patch_logrange) + ) + kernel_size = int( + (2**log_kernel) * min(input.shape[-2:]) + ) # always smaller than min_shape + kernel_size = (kernel_size, kernel_size) + stride = (int(kernel_size[0] * 0.9), int(kernel_size[1] * 0.9)) + + # unfold is always exceeding right/bottom, roll image only negative + # to have them back in the unfolding window + max_roll = ( + (W - kernel_size[1]) % stride[1], + (H - kernel_size[0]) % stride[0], + ) + roll_x, roll_y = np.random.randint(-max_roll[0], 1), np.random.randint( + -max_roll[1], 1 + ) + input_fold = torch.roll(input, shifts=(roll_y, roll_x), dims=(2, 3)) + target_fold = torch.roll(target, shifts=(roll_y, roll_x), dims=(2, 3)) + mask_fold = torch.roll(mask.float(), shifts=(roll_y, roll_x), dims=(2, 3)) + + # unfold in patches + input_fold = F.unfold( + input_fold, kernel_size=kernel_size, stride=stride + ).permute( + 0, 2, 1 + ) # B N C*H_p*W_p + target_fold = F.unfold( + target_fold, kernel_size=kernel_size, stride=stride + ).permute(0, 2, 1) + mask_fold = ( + F.unfold(mask_fold, kernel_size=kernel_size, stride=stride) + .bool() + .permute(0, 2, 1) + ) + + # calculate error patchwise, then mean over patch, then over image based if sample size is significant + input_fold, target_fold, _ = self.rescale_fn( + input_fold, target_fold, mask_fold, dim=[-1] + ) + error = (input_fold - target_fold).abs() + + # calculate elements more then 95 percentile and lower than 5percentile of error + valid_patches = mask_fold.sum(dim=-1) >= self.min_samples + error_mean_patch = masked_mean(error, mask_fold, dim=[-1]).squeeze(-1) + error_mean_image = self.output_fn(error_mean_patch.clamp(min=self.eps)) + error_mean_image = masked_mean( + error_mean_image, mask=valid_patches, dim=[-1] + ) + total_errors.append(error_mean_image.squeeze(-1)) + + # global + input_rescale = input.reshape(B, C, -1) + target_rescale = target.reshape(B, C, -1) + mask = mask.reshape(B, 1, -1).clone() + input, target, mask = self.rescale_fn( + input_rescale, target_rescale, mask, dim=[-1] + ) + error = (input - target).abs().squeeze(1) + + mask = mask.squeeze(1) + error_mean_image = masked_mean(error, mask, dim=[-1]).squeeze(-1) + error_mean_image = self.output_fn(error_mean_image.clamp(min=self.eps)) + + total_errors.append(error_mean_image) + + errors = torch.stack(total_errors).mean(dim=0) + return errors + + @classmethod + def build(cls, config): + obj = cls( + weight=config["weight"], + patch_size=config["patch_size"], + output_fn=config["output_fn"], + min_samples=config["min_samples"], + num_levels=config["num_levels"], + input_fn=config["input_fn"], + ) + return obj + + +class EdgeGuidedLocalSSI(nn.Module): + def __init__( + self, + weight: float, + output_fn: str = "sqrt", + min_samples: int = 4, + input_fn: str = "linear", + use_global: bool = True, + eps: float = 1e-5, + ): + super(EdgeGuidedLocalSSI, self).__init__() + self.name: str = self.__class__.__name__ + self.weight = weight + self.output_fn = FNS[output_fn] + self.input_fn = FNS[input_fn] + self.min_samples = min_samples + self.eps = eps + self.use_global = use_global + self.rescale_fn = ssi + + delta_x = torch.tensor( + [[-1.0, 0.0, 1.0], [-2.0, 0.0, 2.0], [-1.0, 0.0, 1.0]], requires_grad=False + ) + delta_y = torch.tensor( + [[-1.0, -2.0, -1.0], [0.0, 0.0, 0.0], [1.0, 2.0, 1.0]], requires_grad=False + ) + self.delta_x = delta_x.reshape(1, 1, 3, 3) + self.delta_y = delta_y.reshape(1, 1, 3, 3) + + try: + from unidepth.ops.extract_patches import RandomPatchExtractor + + self.random_patch_extractor = RandomPatchExtractor() + except Exception as e: + self.random_patch_extractor = extract_patches + print( + "EdgeGuidedLocalSSI reverts to a non cuda-optimized operation, " + "you will experince large slowdown, " + "please install it: ", + "`cd ./unidepth/ops/extract_patches && bash compile.sh`", + ) + + def get_edge(self, image, mask): + channels = image.shape[1] + device = image.device + delta_x = self.delta_x.to(device).repeat(channels, 1, 1, 1) + delta_y = self.delta_y.to(device).repeat(channels, 1, 1, 1) + image_Gx = F.conv2d(image, delta_x, groups=channels, padding="same") / 8 + image_Gy = F.conv2d(image, delta_y, groups=channels, padding="same") / 8 + image_Gx = ( + image_Gx.square().mean(dim=1, keepdim=True).sqrt() + ) # RMSE over color dim + image_Gy = image_Gy.square().mean(dim=1, keepdim=True).sqrt() + edges = torch.sqrt(image_Gx**2 + image_Gy**2) + edges[:, :, :3, :] = 0 + edges[:, :, -3:, :] = 0 + edges[:, :, :, :3] = 0 + edges[:, :, :, -3:] = 0 + edges[~mask.bool()] = 0 + return edges + + def compute_sample_patch_error( + self, input, target, mask, sampling_coords, kernel_size, image_size + ): + B, C, H, W = input.shape + patch_size = kernel_size[0] * kernel_size[1] + input = self.random_patch_extractor( + input, sampling_coords, kernel_size + ).reshape(B, -1, patch_size) + target = self.random_patch_extractor( + target, sampling_coords, kernel_size + ).reshape(B, -1, patch_size) + mask = ( + self.random_patch_extractor(mask.float(), sampling_coords, kernel_size) + .bool() + .reshape(B, -1, patch_size) + ) + input, target, mask = self.rescale_fn(input, target, mask, dim=[-1]) + error = (input - target).abs().clamp(min=self.eps) + + valid_patches = mask.sum(dim=-1) >= self.min_samples + error_mean_patch = masked_mean(error, mask, dim=[-1]).squeeze(-1) + error_mean_image = self.output_fn(error_mean_patch.clamp(min=self.eps)) + error_mean_image = masked_mean(error_mean_image, mask=valid_patches, dim=[-1]) + return error_mean_image + + def compute_image_error(self, input, target, mask, image_size): + H, W = image_size + input = input.reshape(-1, 1, H * W) + target = target.reshape(-1, 1, H * W) + mask = mask.reshape(-1, 1, H * W) + input, target, mask = self.rescale_fn(input, target, mask, dim=[-1]) + error = (input - target).abs().clamp(min=self.eps) + + error_mean_image = masked_mean(error, mask, dim=[-1]).squeeze(-1) + error_mean_image = self.output_fn(error_mean_image.clamp(min=self.eps)) + return error_mean_image + + @torch.autocast(device_type="cuda", enabled=False, dtype=torch.float32) + def forward( + self, + input: torch.Tensor, + target: torch.Tensor, + mask: torch.Tensor, + image: torch.Tensor | None = None, + validity_mask: torch.Tensor | None = None, + *args, + **kwargs, + ) -> torch.Tensor: + + mask = mask.bool() + input = self.input_fn(input.float()) + target = self.input_fn(target.float()) + B, _, H, W = input.shape + total_errors = [] + + # remove border and black border + if validity_mask is not None: + validity_mask = erode(validity_mask.float(), kernel_size=3) + + edges = self.get_edge(image, validity_mask) + # quantile was 0.95? + edges_coords = sample_strong_edges(edges, quantile=0.9, reshape=14) + log_kernel = np.random.uniform(0.04, 0.08) if self.training else 0.05 + kernel_size = int( + log_kernel * min(input.shape[-2:]) + ) # always smaller than min_shape + kernel_size = kernel_size + int(kernel_size % 2 == 0) # odd num + kernel_size = (kernel_size, kernel_size) + error_mean_image = self.compute_sample_patch_error( + input, target, mask, edges_coords, kernel_size, (H, W) + ) + total_errors.append(error_mean_image.squeeze(-1)) + + if self.use_global: + error_mean_image = self.compute_image_error(input, target, mask, (H, W)) + total_errors.append(error_mean_image.squeeze(-1)) + + errors = torch.stack(total_errors).mean(dim=0) + return errors + + @classmethod + def build(cls, config): + obj = cls( + weight=config["weight"], + output_fn=config["output_fn"], + input_fn=config["input_fn"], + use_global=config["use_global"], + min_samples=config.get("min_samples", 6), + ) + return obj diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/losses/regression.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/losses/regression.py new file mode 100644 index 0000000000000000000000000000000000000000..d53a45abb1a435010cdbbeea2c86cfcf9afb4a42 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/losses/regression.py @@ -0,0 +1,62 @@ +import torch +import torch.nn as nn + +from .utils import FNS, REGRESSION_DICT, masked_mean, masked_quantile + + +class Regression(nn.Module): + def __init__( + self, + weight: float, + input_fn: str, + output_fn: str, + alpha: float, + gamma: float, + fn: str, + dims: list[int] = [-1], + quantile: float = 0.0, + **kwargs, + ): + super().__init__() + self.name = self.__class__.__name__ + self.output_fn = FNS[output_fn] + self.input_fn = FNS[input_fn] + self.weight = weight + self.dims = dims + self.quantile = quantile + self.alpha = alpha + self.gamma = gamma + self.fn = REGRESSION_DICT[fn] + + @torch.autocast(device_type="cuda", enabled=False, dtype=torch.float32) + def forward( + self, + input: torch.Tensor, + target: torch.Tensor, + mask: torch.Tensor | None = None, + **kwargs, + ) -> torch.Tensor: + if mask is not None: # usually it is just repeated + mask = mask[:, 0] + + input = self.input_fn(input.float()) + target = self.input_fn(target.float()) + error = self.fn(input - target, gamma=self.gamma, alpha=self.alpha).mean(dim=1) + mean_error = masked_mean(data=error, mask=mask, dim=self.dims).squeeze( + self.dims + ) + mean_error = self.output_fn(mean_error) + return mean_error + + @classmethod + def build(cls, config): + obj = cls( + weight=config["weight"], + output_fn=config["output_fn"], + input_fn=config["input_fn"], + dims=config.get("dims", (-1,)), + alpha=config["alpha"], + gamma=config["gamma"], + fn=config["fn"], + ) + return obj diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/losses/silog.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/losses/silog.py new file mode 100644 index 0000000000000000000000000000000000000000..9a67cc31ff93ef37ee75d322b7b5df6cb676c9a8 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/losses/silog.py @@ -0,0 +1,61 @@ +import torch +import torch.nn as nn + +from .utils import (FNS, REGRESSION_DICT, masked_mean, masked_mean_var, + masked_quantile) + + +class SILog(nn.Module): + def __init__( + self, + weight: float, + input_fn: str = "linear", + output_fn: str = "sqrt", + integrated: float = 0.15, + dims: list[int] = [-3, -2, -1], + eps: float = 1e-5, + ): + super().__init__() + self.name: str = self.__class__.__name__ + self.weight: float = weight + + self.dims = dims + self.input_fn = FNS[input_fn] + self.output_fn = FNS[output_fn] + self.eps: float = eps + self.integrated = integrated + + @torch.autocast(device_type="cuda", enabled=False, dtype=torch.float32) + def forward( + self, + input: torch.Tensor, + target: torch.Tensor, + mask: torch.Tensor, + si: torch.Tensor, + **kwargs, + ) -> torch.Tensor: + mask = mask.bool() + error = self.input_fn(input.float()) - self.input_fn(target.float()) + mean_error, var_error = masked_mean_var( + data=error, mask=mask, dim=self.dims, keepdim=False + ) + if var_error.ndim > 1: + var_error = var_error.mean(dim=-1) + + if self.integrated > 0.0: + scale_error = mean_error**2 + var_error = var_error + self.integrated * scale_error * (1 - si.int()) + + out_loss = self.output_fn(var_error) + return out_loss + + @classmethod + def build(cls, config): + obj = cls( + weight=config["weight"], + dims=config["dims"], + output_fn=config["output_fn"], + input_fn=config["input_fn"], + integrated=config.get("integrated", 0.15), + ) + return obj diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/losses/utils.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/losses/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..fbb402796f3bda2a618b4838696a9a43e180ab2c --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/losses/utils.py @@ -0,0 +1,244 @@ +from math import prod +from typing import Any, Dict, List, Optional, Tuple + +import torch + +FNS = { + "sqrt": lambda x: torch.sqrt(x + 1e-4), + "log": lambda x: torch.log(x + 1e-4), + "log1": lambda x: torch.log(x + 1), + # if x -> 0 : log(1/x) + # if x -> inf : log(1+1/x) -> 1/x + hot + "log1i": lambda x: torch.log(1 + 50 / (1e-4 + x)), + "linear": lambda x: x, + "square": torch.square, + "disp": lambda x: 1 / (x + 1e-4), + "disp1": lambda x: 1 / (1 + x), +} + + +FNS_INV = { + "sqrt": torch.square, + "log": torch.exp, + "log1": lambda x: torch.exp(x) - 1, + "linear": lambda x: x, + "square": torch.sqrt, + "disp": lambda x: 1 / x, +} + + +def masked_mean_var( + data: torch.Tensor, mask: torch.Tensor, dim: List[int], keepdim: bool = True +): + if mask is None: + return data.mean(dim=dim, keepdim=keepdim), data.var(dim=dim, keepdim=keepdim) + mask = mask.float() + mask_sum = torch.sum(mask, dim=dim, keepdim=True) + # data = torch.nan_to_num(data, nan=0.0) + mask_mean = torch.sum(data * mask, dim=dim, keepdim=True) / torch.clamp( + mask_sum, min=1.0 + ) + mask_var = torch.sum( + mask * (data - mask_mean) ** 2, dim=dim, keepdim=True + ) / torch.clamp(mask_sum, min=1.0) + if not keepdim: + mask_mean, mask_var = mask_mean.squeeze(dim), mask_var.squeeze(dim) + return mask_mean, mask_var + + +def masked_mean(data: torch.Tensor, mask: torch.Tensor | None, dim: List[int]): + if mask is None: + return data.mean(dim=dim, keepdim=True) + mask = mask.float() + mask_sum = torch.sum(mask, dim=dim, keepdim=True) + mask_mean = torch.sum( + torch.nan_to_num(data, nan=0.0) * mask, dim=dim, keepdim=True + ) / mask_sum.clamp(min=1.0) + return mask_mean + + +def masked_quantile( + data: torch.Tensor, mask: torch.Tensor | None, dims: List[int], q: float +): + """ + Compute the quantile of the data only where the mask is 1 along specified dimensions. + + Args: + data (torch.Tensor): The input data tensor. + mask (torch.Tensor): The mask tensor with the same shape as data, containing 1s where data should be considered. + dims (list of int): The dimensions to compute the quantile over. + q (float): The quantile to compute, must be between 0 and 1. + + Returns: + torch.Tensor: The quantile computed over the specified dimensions, ignoring masked values. + """ + masked_data = data * mask if mask is not None else data + + # Get a list of all dimensions + all_dims = list(range(masked_data.dim())) + + # Revert negative dimensions + dims = [d % masked_data.dim() for d in dims] + + # Find the dimensions to keep (not included in the `dims` list) + keep_dims = [d for d in all_dims if d not in dims] + + # Permute dimensions to bring `dims` to the front + permute_order = dims + keep_dims + permuted_data = masked_data.permute(permute_order) + + # Reshape into 2D: (-1, remaining_dims) + collapsed_shape = ( + -1, + prod([permuted_data.size(d) for d in range(len(dims), permuted_data.dim())]), + ) + reshaped_data = permuted_data.reshape(collapsed_shape) + if mask is None: + return torch.quantile(reshaped_data, q, dim=0) + + permuted_mask = mask.permute(permute_order) + reshaped_mask = permuted_mask.reshape(collapsed_shape) + + # Calculate quantile along the first dimension where mask is true + quantiles = [] + for i in range(reshaped_data.shape[1]): + valid_data = reshaped_data[:, i][reshaped_mask[:, i]] + if valid_data.numel() == 0: + # print("Warning: No valid data found for quantile calculation.") + quantiles.append(reshaped_data[:, i].min() * 0.99) + else: + quantiles.append(torch.quantile(valid_data, q, dim=0)) + + # Stack back into a tensor with reduced dimensions + quantiles = torch.stack(quantiles) + quantiles = quantiles.reshape( + [permuted_data.size(d) for d in range(len(dims), permuted_data.dim())] + ) + + return quantiles + + +def masked_median(data: torch.Tensor, mask: torch.Tensor, dim: List[int]): + ndim = data.ndim + data = data.flatten(ndim - len(dim)) + mask = mask.flatten(ndim - len(dim)) + mask_median = torch.median(data[..., mask], dim=-1).values + return mask_median + + +def masked_median_mad(data: torch.Tensor, mask: torch.Tensor, dim: List[int]): + ndim = data.ndim + data = data.flatten(ndim - len(dim)) + mask = mask.flatten(ndim - len(dim)) + mask_median = torch.median(data[mask], dim=-1, keepdim=True).values + mask_mad = masked_mean((data - mask_median).abs(), mask, dim=[-1]) + return mask_median, mask_mad + + +def masked_weighted_mean_var( + data: torch.Tensor, mask: torch.Tensor, weights: torch.Tensor, dim: Tuple[int, ...] +): + if mask is None: + return data.mean(dim=dim, keepdim=True), data.var(dim=dim, keepdim=True) + mask = mask.float() + mask_mean = torch.sum(data * mask * weights, dim=dim, keepdim=True) / torch.sum( + mask * weights, dim=dim, keepdim=True + ).clamp(min=1.0) + # V1**2 - V2, V1: sum w_i, V2: sum w_i**2 + denom = torch.sum(weights * mask, dim=dim, keepdim=True).square() - torch.sum( + (mask * weights).square(), dim=dim, keepdim=True + ) + # correction is V1 / (V1**2 - V2), if w_i=1 => N/(N**2 - N) => 1/(N-1) (unbiased estimator of variance, cvd) + correction_factor = torch.sum(mask * weights, dim=dim, keepdim=True) / denom.clamp( + min=1.0 + ) + mask_var = correction_factor * torch.sum( + weights * mask * (data - mask_mean) ** 2, dim=dim, keepdim=True + ) + return mask_mean, mask_var + + +def ssi( + input: torch.Tensor, target: torch.Tensor, mask: torch.Tensor, dim: list[int] +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + # recalculate mask with points in 95% confidence interval + # the statistics are calculated on the stable points and + # are similar ot median/MAD, but median/MAD gradients + # are really weird, so this is a workaround + input_detach = input.detach() + input_mean, input_var = masked_mean_var(input_detach, mask=mask, dim=dim) + target_mean, target_var = masked_mean_var(target, mask=mask, dim=dim) + input_std = (input_var).clip(min=1e-6).sqrt() + target_std = (target_var).clip(min=1e-6).sqrt() + stable_points_input = torch.logical_and( + input_detach > input_mean - 1.96 * input_std, + input_detach < input_mean + 1.96 * input_std, + ) + stable_points_target = torch.logical_and( + target > target_mean - 1.96 * target_std, + target < target_mean + 1.96 * target_std, + ) + stable_mask = stable_points_target & stable_points_input & mask + + input_mean, input_var = masked_mean_var(input, mask=stable_mask, dim=dim) + target_mean, target_var = masked_mean_var(target, mask=stable_mask, dim=dim) + target_normalized = (target - target_mean) / FNS["sqrt"](target_var) + input_normalized = (input - input_mean) / FNS["sqrt"](input_var) + return input_normalized, target_normalized, stable_mask + + +def ind2sub(idx, cols): + r = idx // cols + c = idx % cols + return r, c + + +def sub2ind(r, c, cols): + idx = r * cols + c + return idx + + +def l2(input_tensor: torch.Tensor, gamma: float = 1.0, *args, **kwargs) -> torch.Tensor: + return gamma * (input_tensor / gamma) ** 2 + + +def l1(input_tensor: torch.Tensor, gamma: float = 1.0, *args, **kwargs) -> torch.Tensor: + return torch.abs(input_tensor) + + +def charbonnier( + input_tensor: torch.Tensor, gamma: float = 1.0, *args, **kwargs +) -> torch.Tensor: + return torch.sqrt(torch.square(input_tensor) + gamma**2) - gamma + + +def cauchy( + input_tensor: torch.Tensor, gamma: float = 1.0, *args, **kwargs +) -> torch.Tensor: + return gamma * torch.log(torch.square(input_tensor) / gamma + 1) + + +def geman_mcclure( + input_tensor: torch.Tensor, gamma: float = 1.0, *args, **kwargs +) -> torch.Tensor: + return gamma * torch.square(input_tensor) / (torch.square(input_tensor) + gamma) + + +def robust_loss( + input_tensor: torch.Tensor, alpha: float, gamma: float = 1.0, *args, **kwargs +) -> torch.Tensor: + coeff = abs(alpha - 2) / alpha + power = torch.square(input_tensor) / abs(alpha - 2) / (gamma**2) + 1 + return ( + gamma * coeff * (torch.pow(power, alpha / 2) - 1) + ) # mult gamma to keep grad magnitude invariant wrt gamma + + +REGRESSION_DICT = { + "l2": l2, + "l1": l1, + "cauchy": cauchy, + "charbonnier": charbonnier, + "geman_mcclure": geman_mcclure, + "robust_loss": robust_loss, +} diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/scheduler.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/scheduler.py new file mode 100644 index 0000000000000000000000000000000000000000..c2d7109008bab1e3eaf203199171d9ea538eb4ff --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/ops/scheduler.py @@ -0,0 +1,122 @@ +import weakref + +import numpy as np + + +class PlainCosineScheduler(object): + def __init__( + self, + klass, + key, + warmup_iters, + total_iters, + overwrite=False, + init_value=None, + base_value=None, + final_value=None, + step_init=-1, + ): + super().__init__() + self.iter = step_init + self.overwrite = overwrite + self.base_value = base_value + self.init_value = init_value if init_value is not None else base_value + self.final_value = final_value + self.total_iters = total_iters + self.warmup_iters = warmup_iters + self.key = key + self.klass = klass + self.schedulers = [self.get_scheduler()] + + def get_scheduler(self): + init_value = self.init_value + base_value = self.base_value + final_value = self.final_value + warmup_iters = self.warmup_iters + total_iters = self.total_iters + + # normalize in 0,1, then apply function (power) and denormalize + normalized_schedule = np.linspace(0, 1, warmup_iters, endpoint=True) + normalized_schedule = np.power(normalized_schedule, 1) + warmup_schedule = (base_value - init_value) * normalized_schedule + init_value + + # main scheduling + iters = np.arange(total_iters - warmup_iters + 1) + schedule = final_value + 0.5 * (base_value - final_value) * ( + 1 + np.cos(np.pi * iters / (len(iters) - 1)) + ) + return np.concatenate((warmup_schedule, schedule)) + + def step(self): + self.iter = self.iter + 1 + vals = self[self.iter] + for i, val in enumerate(vals): + setattr(self.klass, self.key, val) + + def __getitem__(self, it): + it = min(it, self.total_iters) + return [scheduler[it] for scheduler in self.schedulers] + + +class CosineScheduler(object): + def __init__( + self, + optimizer, + warmup_iters, + total_iters, + key, + overwrite=False, + init_value=None, + base_value=None, + final_value=None, + step_init=-1, + ): + super().__init__() + self.iter = step_init + self.overwrite = overwrite + self.optimizer = optimizer + self.base_value = base_value + self.init_value = init_value + self.final_value = final_value + self.total_iters = total_iters + self.warmup_iters = warmup_iters + self.key = key + self.schedulers = [ + self.get_schedulers(group) for group in optimizer.param_groups + ] + + def get_schedulers(self, group): + init_value = group.get(self.key + "_init", self.init_value) + base_value = group.get(self.key + "_base", self.base_value) + final_value = group.get(self.key + "_final", self.final_value) + warmup_iters = self.warmup_iters + total_iters = self.total_iters + if self.overwrite: + final_value = self.final_value + + # normalize in 0,1, then apply function (power) and denormalize + normalized_schedule = np.linspace(0, 1, warmup_iters, endpoint=True) + normalized_schedule = np.power(normalized_schedule, 1) + warmup_schedule = (base_value - init_value) * normalized_schedule + init_value + + # main scheduling + iters = np.arange(total_iters - warmup_iters + 1) + schedule = final_value + 0.5 * (base_value - final_value) * ( + 1 + np.cos(np.pi * iters / (len(iters) - 1)) + ) + return np.concatenate((warmup_schedule, schedule)) + + def step(self): + self.iter = self.iter + 1 + vals = self[self.iter] + for group, val in zip(self.optimizer.param_groups, vals): + if isinstance(group[self.key], (tuple, list)): + val = (val, *group[self.key][1:]) + group[self.key] = val + + def __getitem__(self, it): + it = min(it, self.total_iters) + return [scheduler[it] for scheduler in self.schedulers] + + def get(self): + return [group[self.key] for group in self.optimizer.param_groups] diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/utils/__init__.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0fa40d48f9b12da61463bea413c735d0244139fe --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/utils/__init__.py @@ -0,0 +1,12 @@ +from .camera import invert_pinhole +# from .validation import validate +from .coordinate import coords_grid, normalize_coords +from .distributed import (barrier, get_dist_info, get_rank, is_main_process, + setup_multi_processes, setup_slurm, + sync_tensor_across_gpus) +from .evaluation_depth import (DICT_METRICS, DICT_METRICS_3D, eval_3d, + eval_depth) +from .geometric import spherical_zbuffer_to_euclidean, unproject_points +from .misc import (format_seconds, get_params, identity, recursive_index, + remove_padding, to_cpu) +from .visualization import colorize, image_grid, log_train_artifacts diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/utils/camera.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/utils/camera.py new file mode 100644 index 0000000000000000000000000000000000000000..89263b242d387257c0fda2d760f9fb9c714788ae --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/utils/camera.py @@ -0,0 +1,1308 @@ +""" +Author: Luigi Piccinelli +Licensed under the CC-BY NC 4.0 license (http://creativecommons.org/licenses/by-nc/4.0/) +""" + +from copy import deepcopy + +import numpy as np +import torch +import torch.nn.functional as F + +from .coordinate import coords_grid +from .misc import recursive_to, squeeze_list + + +def invert_pinhole(K): + fx = K[..., 0, 0] + fy = K[..., 1, 1] + cx = K[..., 0, 2] + cy = K[..., 1, 2] + K_inv = torch.zeros_like(K) + K_inv[..., 0, 0] = 1.0 / fx + K_inv[..., 1, 1] = 1.0 / fy + K_inv[..., 0, 2] = -cx / fx + K_inv[..., 1, 2] = -cy / fy + K_inv[..., 2, 2] = 1.0 + return K_inv + + +class Camera: + """ + This is meant to be an abstract parent class, please use the others as actual cameras. + Pinhole, FIsheye624, MEI, OPENCV, EUCM, Spherical (Equirectangular). + + """ + + def __init__(self, params=None, K=None): + if params.ndim == 1: + params = params.unsqueeze(0) + + if K is None: + K = ( + torch.eye(3, device=params.device, dtype=params.dtype) + .unsqueeze(0) + .repeat(params.shape[0], 1, 1) + ) + K[..., 0, 0] = params[..., 0] + K[..., 1, 1] = params[..., 1] + K[..., 0, 2] = params[..., 2] + K[..., 1, 2] = params[..., 3] + + self.params = params + self.K = K + self.overlap_mask = None + self.projection_mask = None + + def project(self, xyz): + raise NotImplementedError + + def unproject(self, uv): + raise NotImplementedError + + def get_projection_mask(self): + return self.projection_mask + + def get_overlap_mask(self): + return self.overlap_mask + + def reconstruct(self, depth): + id_coords = coords_grid( + 1, depth.shape[-2], depth.shape[-1], device=depth.device + ) + rays = self.unproject(id_coords) + return ( + rays / rays[:, -1:].clamp(min=1e-4) * depth.clamp(min=1e-4) + ) # assumption z>0!!! + + def resize(self, factor): + self.K[..., :2, :] *= factor + self.params[..., :4] *= factor + return self + + def to(self, device, non_blocking=False): + self.params = self.params.to(device, non_blocking=non_blocking) + self.K = self.K.to(device, non_blocking=non_blocking) + return self + + def get_rays(self, shapes, noisy=False): + b, h, w = shapes + uv = coords_grid(1, h, w, device=self.K.device, noisy=noisy) + rays = self.unproject(uv) + return rays / torch.norm(rays, dim=1, keepdim=True).clamp(min=1e-4) + + def get_pinhole_rays(self, shapes, noisy=False): + b, h, w = shapes + uv = coords_grid(b, h, w, device=self.K.device, homogeneous=True, noisy=noisy) + rays = (invert_pinhole(self.K) @ uv.reshape(b, 3, -1)).reshape(b, 3, h, w) + return rays / torch.norm(rays, dim=1, keepdim=True).clamp(min=1e-4) + + def flip(self, H, W, direction="horizontal"): + new_cx = ( + W - self.params[:, 2] if direction == "horizontal" else self.params[:, 2] + ) + new_cy = H - self.params[:, 3] if direction == "vertical" else self.params[:, 3] + self.params = torch.stack( + [self.params[:, 0], self.params[:, 1], new_cx, new_cy], dim=1 + ) + self.K[..., 0, 2] = new_cx + self.K[..., 1, 2] = new_cy + return self + + def clone(self): + return deepcopy(self) + + def crop(self, left, top, right=None, bottom=None): + self.K[..., 0, 2] -= left + self.K[..., 1, 2] -= top + self.params[..., 2] -= left + self.params[..., 3] -= top + return self + + # helper function to get how fov changes based on new original size and new size + def get_new_fov(self, new_shape, original_shape): + new_hfov = 2 * torch.atan( + self.params[..., 2] / self.params[..., 0] * new_shape[1] / original_shape[1] + ) + new_vfov = 2 * torch.atan( + self.params[..., 3] / self.params[..., 1] * new_shape[0] / original_shape[0] + ) + return new_hfov, new_vfov + + def mask_overlap_projection(self, projected): + B, _, H, W = projected.shape + id_coords = coords_grid(B, H, W, device=projected.device) + + # check for mask where flow would overlap with other part of the image + # eleemtns coming from the border are then masked out + flow = projected - id_coords + gamma = 0.1 + sample_grid = gamma * flow + id_coords # sample along the flow + sample_grid[:, 0] = sample_grid[:, 0] / (W - 1) * 2 - 1 + sample_grid[:, 1] = sample_grid[:, 1] / (H - 1) * 2 - 1 + sampled_flow = F.grid_sample( + flow, + sample_grid.permute(0, 2, 3, 1), + mode="bilinear", + align_corners=False, + padding_mode="border", + ) + mask = ( + (1 - gamma) * torch.norm(flow, dim=1, keepdim=True) + < torch.norm(sampled_flow, dim=1, keepdim=True) + ) | (torch.norm(flow, dim=1, keepdim=True) < 1) + return mask + + def _pad_params(self): + # Ensure params are padded to length 16 + if self.params.shape[1] < 16: + padding = torch.zeros( + 16 - self.params.shape[1], + device=self.params.device, + dtype=self.params.dtype, + ) + padding = padding.unsqueeze(0).repeat(self.params.shape[0], 1) + return torch.cat([self.params, padding], dim=1) + return self.params + + @staticmethod + def flatten_cameras(cameras): # -> list[Camera]: + # Recursively flatten BatchCamera into primitive cameras + flattened_cameras = [] + for camera in cameras: + if isinstance(camera, BatchCamera): + flattened_cameras.extend(BatchCamera.flatten_cameras(camera.cameras)) + elif isinstance(camera, list): + flattened_cameras.extend(camera) + else: + flattened_cameras.append(camera) + return flattened_cameras + + @staticmethod + def _stack_or_cat_cameras(cameras, func, **kwargs): + # Generalized method to handle stacking or concatenation + flat_cameras = BatchCamera.flatten_cameras(cameras) + K_matrices = [camera.K for camera in flat_cameras] + padded_params = [camera._pad_params() for camera in flat_cameras] + + stacked_K = func(K_matrices, **kwargs) + stacked_params = func(padded_params, **kwargs) + + # Keep track of the original classes + original_class = [x.__class__.__name__ for x in flat_cameras] + return BatchCamera(stacked_params, stacked_K, original_class, flat_cameras) + + @classmethod + def __torch_function__(cls, func, types, args=(), kwargs=None): + if kwargs is None: + kwargs = {} + + if func is torch.cat: + return Camera._stack_or_cat_cameras(args[0], func, **kwargs) + + if func is torch.stack: + return Camera._stack_or_cat_cameras(args[0], func, **kwargs) + + if func is torch.flatten: + return Camera._stack_or_cat_cameras(args[0], torch.cat, **kwargs) + + return super().__torch_function__(func, types, args, kwargs) + + @property + def device(self): + return self.K.device + + # here we assume that cx,cy are more or less H/2 and W/2 + @property + def hfov(self): + return 2 * torch.atan(self.params[..., 2] / self.params[..., 0]) + + @property + def vfov(self): + return 2 * torch.atan(self.params[..., 3] / self.params[..., 1]) + + @property + def max_fov(self): + return 150.0 / 180.0 * np.pi, 150.0 / 180.0 * np.pi + + +class Pinhole(Camera): + def __init__(self, params=None, K=None): + assert params is not None or K is not None + if params is None: + params = torch.stack( + [K[..., 0, 0], K[..., 1, 1], K[..., 0, 2], K[..., 1, 2]], dim=-1 + ) + super().__init__(params=params, K=K) + + @torch.autocast(device_type="cuda", enabled=False, dtype=torch.float32) + def project(self, pcd): + b, _, h, w = pcd.shape + pcd_flat = pcd.reshape(b, 3, -1) # [B, 3, H*W] + cam_coords = self.K @ pcd_flat + pcd_proj = cam_coords[:, :2] / cam_coords[:, -1:].clamp(min=0.01) + pcd_proj = pcd_proj.reshape(b, 2, h, w) + invalid = ( + (pcd_proj[:, 0] >= 0) + & (pcd_proj[:, 0] < w) + & (pcd_proj[:, 1] >= 0) + & (pcd_proj[:, 1] < h) + ) + self.projection_mask = (~invalid).unsqueeze(1) + return pcd_proj + + @torch.autocast(device_type="cuda", enabled=False, dtype=torch.float32) + def unproject(self, uv): + b, _, h, w = uv.shape + uv_flat = uv.reshape(b, 2, -1) # [B, 2, H*W] + uv_homogeneous = torch.cat( + [uv_flat, torch.ones(b, 1, h * w, device=uv.device)], dim=1 + ) # [B, 3, H*W] + K_inv = torch.inverse(self.K.float()) + xyz = K_inv @ uv_homogeneous + xyz = xyz / xyz[:, -1:].clip(min=1e-4) + xyz = xyz.reshape(b, 3, h, w) + self.unprojection_mask = xyz[:, -1:] > 1e-4 + return xyz + + @torch.autocast(device_type="cuda", enabled=False, dtype=torch.float32) + def reconstruct(self, depth): + b, _, h, w = depth.shape + uv = coords_grid(b, h, w, device=depth.device) + xyz = self.unproject(uv) * depth.clip(min=0.0) + return xyz + + +class EUCM(Camera): + def __init__(self, params): + super().__init__(params=params, K=None) + + @torch.autocast(device_type="cuda", enabled=False, dtype=torch.float32) + def project(self, xyz): + H, W = xyz.shape[-2:] + fx, fy, cx, cy, alpha, beta = self.params[:6].unbind(dim=1) + x, y, z = xyz.unbind(dim=1) + d = torch.sqrt(beta * (x**2 + y**2) + z**2) + + x = x / (alpha * d + (1 - alpha) * z).clip(min=1e-3) + y = y / (alpha * d + (1 - alpha) * z).clip(min=1e-3) + + Xnorm = fx * x + cx + Ynorm = fy * y + cy + + coords = torch.stack([Xnorm, Ynorm], dim=1) + + invalid = ( + (coords[:, 0] < 0) + | (coords[:, 0] > W) + | (coords[:, 1] < 0) + | (coords[:, 1] > H) + | (z < 0) + ) + self.projection_mask = (~invalid).unsqueeze(1) + + return coords + + @torch.autocast(device_type="cuda", enabled=False, dtype=torch.float32) + def unproject(self, uv): + u, v = uv.unbind(dim=1) + fx, fy, cx, cy, alpha, beta = self.params.unbind(dim=1) + mx = (u - cx) / fx + my = (v - cy) / fy + r_square = mx**2 + my**2 + valid_mask = r_square < torch.where( + alpha < 0.5, 1e6, 1 / (beta * (2 * alpha - 1)) + ) + sqrt_val = 1 - (2 * alpha - 1) * beta * r_square + mz = (1 - beta * (alpha**2) * r_square) / ( + alpha * torch.sqrt(sqrt_val.clip(min=1e-5)) + (1 - alpha) + ) + coeff = 1 / torch.sqrt(mx**2 + my**2 + mz**2 + 1e-5) + + x = coeff * mx + y = coeff * my + z = coeff * mz + self.unprojection_mask = valid_mask & (z > 1e-3) + + xnorm = torch.stack((x, y, z.clamp(1e-3)), dim=1) + return xnorm + + +class Spherical(Camera): + def __init__(self, params): + # Hfov and Vofv are in radians and halved! + super().__init__(params=params, K=None) + + def resize(self, factor): + self.K[..., :2, :] *= factor + self.params[..., :6] *= factor + return self + + def crop(self, left, top, right, bottom): + self.K[..., 0, 2] -= left + self.K[..., 1, 2] -= top + self.params[..., 2] -= left + self.params[..., 3] -= top + W, H = self.params[..., 4], self.params[..., 5] + angle_ratio_W = (W - left - right) / W + angle_ratio_H = (H - top - bottom) / H + + self.params[..., 4] -= left + right + self.params[..., 5] -= top + bottom + + # rescale hfov and vfov + self.params[..., 6] *= angle_ratio_W + self.params[..., 7] *= angle_ratio_H + return self + + @torch.autocast(device_type="cuda", enabled=False, dtype=torch.float32) + def project(self, xyz): + width, height = self.params[..., 4], self.params[..., 5] + hfov, vfov = 2 * self.params[..., 6], 2 * self.params[..., 7] + longitude = torch.atan2(xyz[:, 0], xyz[:, 2]) + latitude = torch.asin(xyz[:, 1] / torch.norm(xyz, dim=1).clamp(min=1e-5)) + + u = longitude / hfov * (width - 1) + (width - 1) / 2 + v = latitude / vfov * (height - 1) + (height - 1) / 2 + + return torch.stack([u, v], dim=1) + + @torch.autocast(device_type="cuda", enabled=False, dtype=torch.float32) + def unproject(self, uv): + u, v = uv.unbind(dim=1) + + width, height = self.params[..., 4], self.params[..., 5] + hfov, vfov = 2 * self.params[..., 6], 2 * self.params[..., 7] + longitude = (u - (width - 1) / 2) / (width - 1) * hfov + latitude = (v - (height - 1) / 2) / (height - 1) * vfov + x = torch.cos(latitude) * torch.sin(longitude) + z = torch.cos(latitude) * torch.cos(longitude) + y = torch.sin(latitude) + unit_sphere = torch.stack([x, y, z], dim=1) + unit_sphere = unit_sphere / torch.norm(unit_sphere, dim=1, keepdim=True).clip( + min=1e-5 + ) + + return unit_sphere + + def reconstruct(self, depth): + id_coords = coords_grid( + 1, depth.shape[-2], depth.shape[-1], device=depth.device + ) + return self.unproject(id_coords) * depth + + def get_new_fov(self, new_shape, original_shape): + new_hfov = 2 * self.params[..., 6] * new_shape[1] / original_shape[1] + new_vfov = 2 * self.params[..., 7] * new_shape[0] / original_shape[0] + return new_hfov, new_vfov + + @property + def hfov(self): + return 2 * self.params[..., 6] + + @property + def vfov(self): + return 2 * self.params[..., 7] + + @property + def max_fov(self): + return 2 * np.pi, 0.9 * np.pi # avoid strong distortion on tops + + +class OPENCV(Camera): + def __init__(self, params): + super().__init__(params=params, K=None) + self.use_radial = self.params[..., 4:10].abs().sum() > 1e-6 + assert ( + self.params[..., 7:10].abs().sum() == 0.0 + ), "Do not support poly division model" + self.use_tangential = self.params[..., 10:12].abs().sum() > 1e-6 + self.use_thin_prism = self.params[..., 12:].abs().sum() > 1e-6 + + @torch.autocast(device_type="cuda", enabled=False, dtype=torch.float32) + def project(self, xyz): + eps = 1e-9 + B, _, H, W = xyz.shape + N = H * W + xyz = xyz.permute(0, 2, 3, 1).reshape(B, N, 3) + + # Radial correction. + z = xyz[:, :, 2].reshape(B, N, 1) + z = torch.where(torch.abs(z) < eps, eps * torch.sign(z), z) + ab = xyz[:, :, :2] / z + r = torch.norm(ab, dim=-1, p=2, keepdim=True) + th = r + + # Create powers of th (th^3, th^5, ...) + th_pow = torch.cat([torch.pow(th, 2 + i * 2) for i in range(3)], dim=-1) + distortion_coeffs_num = self.params[:, 4:7].reshape(B, 1, 3) + distortion_coeffs_den = self.params[:, 7:10].reshape(B, 1, 3) + th_num = 1 + torch.sum(th_pow * distortion_coeffs_num, dim=-1, keepdim=True) + th_den = 1 + torch.sum(th_pow * distortion_coeffs_den, dim=-1, keepdim=True) + + xr_yr = ab * th_num / th_den + uv_dist = xr_yr + + # Tangential correction. + p0 = self.params[..., -6].reshape(B, 1) + p1 = self.params[..., -5].reshape(B, 1) + xr = xr_yr[:, :, 0].reshape(B, N) + yr = xr_yr[:, :, 1].reshape(B, N) + xr_yr_sq = torch.square(xr_yr) + xr_sq = xr_yr_sq[:, :, 0].reshape(B, N) + yr_sq = xr_yr_sq[:, :, 1].reshape(B, N) + rd_sq = xr_sq + yr_sq + uv_dist_tu = uv_dist[:, :, 0] + ( + (2.0 * xr_sq + rd_sq) * p0 + 2.0 * xr * yr * p1 + ) + uv_dist_tv = uv_dist[:, :, 1] + ( + (2.0 * yr_sq + rd_sq) * p1 + 2.0 * xr * yr * p0 + ) + uv_dist = torch.stack( + [uv_dist_tu, uv_dist_tv], dim=-1 + ) # Avoids in-place complaint. + + # Thin Prism correction. + s0 = self.params[..., -4].reshape(B, 1) + s1 = self.params[..., -3].reshape(B, 1) + s2 = self.params[..., -2].reshape(B, 1) + s3 = self.params[..., -1].reshape(B, 1) + rd_4 = torch.square(rd_sq) + uv_dist[:, :, 0] = uv_dist[:, :, 0] + (s0 * rd_sq + s1 * rd_4) + uv_dist[:, :, 1] = uv_dist[:, :, 1] + (s2 * rd_sq + s3 * rd_4) + + # Finally, apply standard terms: focal length and camera centers. + if self.params.shape[-1] == 15: + fx_fy = self.params[..., 0].reshape(B, 1, 1) + cx_cy = self.params[..., 1:3].reshape(B, 1, 2) + else: + fx_fy = self.params[..., 0:2].reshape(B, 1, 2) + cx_cy = self.params[..., 2:4].reshape(B, 1, 2) + result = uv_dist * fx_fy + cx_cy + + result = result.reshape(B, H, W, 2).permute(0, 3, 1, 2) + invalid = ( + (result[:, 0] < 0) + | (result[:, 0] > W) + | (result[:, 1] < 0) + | (result[:, 1] > H) + ) + self.projection_mask = (~invalid).unsqueeze(1) + self.overlap_mask = self.mask_overlap_projection(result) + + return result + + @torch.autocast(device_type="cuda", enabled=False, dtype=torch.float32) + def unproject(self, uv, max_iters: int = 10): + eps = 1e-3 + B, _, H, W = uv.shape + N = H * W + uv = uv.permute(0, 2, 3, 1).reshape(B, N, 2) + + if self.params.shape[-1] == 15: + fx_fy = self.params[..., 0].reshape(B, 1, 1) + cx_cy = self.params[..., 1:3].reshape(B, 1, 2) + else: + fx_fy = self.params[..., 0:2].reshape(B, 1, 2) + cx_cy = self.params[..., 2:4].reshape(B, 1, 2) + + uv_dist = (uv - cx_cy) / fx_fy + + # Compute xr_yr using Newton's method. + xr_yr = uv_dist.clone() # Initial guess. + max_iters_tanprism = ( + max_iters if self.use_thin_prism or self.use_tangential else 0 + ) + + for _ in range(max_iters_tanprism): + uv_dist_est = xr_yr.clone() + xr = xr_yr[..., 0].reshape(B, N) + yr = xr_yr[..., 1].reshape(B, N) + xr_yr_sq = torch.square(xr_yr) + xr_sq = xr_yr_sq[..., 0].reshape(B, N) + yr_sq = xr_yr_sq[..., 1].reshape(B, N) + rd_sq = xr_sq + yr_sq + + if self.use_tangential: + # Tangential terms. + p0 = self.params[..., -6].reshape(B, 1) + p1 = self.params[..., -5].reshape(B, 1) + uv_dist_est[..., 0] = uv_dist_est[..., 0] + ( + (2.0 * xr_sq + rd_sq) * p0 + 2.0 * xr * yr * p1 + ) + uv_dist_est[..., 1] = uv_dist_est[..., 1] + ( + (2.0 * yr_sq + rd_sq) * p1 + 2.0 * xr * yr * p0 + ) + + if self.use_thin_prism: + # Thin Prism terms. + s0 = self.params[..., -4].reshape(B, 1) + s1 = self.params[..., -3].reshape(B, 1) + s2 = self.params[..., -2].reshape(B, 1) + s3 = self.params[..., -1].reshape(B, 1) + rd_4 = torch.square(rd_sq) + uv_dist_est[:, :, 0] = uv_dist_est[:, :, 0] + (s0 * rd_sq + s1 * rd_4) + uv_dist_est[:, :, 1] = uv_dist_est[:, :, 1] + (s2 * rd_sq + s3 * rd_4) + + # Compute the derivative of uv_dist w.r.t. xr_yr. + duv_dist_dxr_yr = uv.new_ones(B, N, 2, 2) + + if self.use_tangential: + duv_dist_dxr_yr[..., 0, 0] = 1.0 + 6.0 * xr * p0 + 2.0 * yr * p1 + offdiag = 2.0 * (xr * p1 + yr * p0) + duv_dist_dxr_yr[..., 0, 1] = offdiag + duv_dist_dxr_yr[..., 1, 0] = offdiag + duv_dist_dxr_yr[..., 1, 1] = 1.0 + 6.0 * yr * p1 + 2.0 * xr * p0 + + if self.use_thin_prism: + xr_yr_sq_norm = xr_sq + yr_sq + temp1 = 2.0 * (s0 + 2.0 * s1 * xr_yr_sq_norm) + duv_dist_dxr_yr[..., 0, 0] = duv_dist_dxr_yr[..., 0, 0] + (xr * temp1) + duv_dist_dxr_yr[..., 0, 1] = duv_dist_dxr_yr[..., 0, 1] + (yr * temp1) + temp2 = 2.0 * (s2 + 2.0 * s3 * xr_yr_sq_norm) + duv_dist_dxr_yr[..., 1, 0] = duv_dist_dxr_yr[..., 1, 0] + (xr * temp2) + duv_dist_dxr_yr[..., 1, 1] = duv_dist_dxr_yr[..., 1, 1] + (yr * temp2) + + mat = duv_dist_dxr_yr.reshape(-1, 2, 2) + a = mat[:, 0, 0].reshape(-1, 1, 1) + b = mat[:, 0, 1].reshape(-1, 1, 1) + c = mat[:, 1, 0].reshape(-1, 1, 1) + d = mat[:, 1, 1].reshape(-1, 1, 1) + det = 1.0 / ((a * d) - (b * c)) + top = torch.cat([d, -b], dim=-1) + bot = torch.cat([-c, a], dim=-1) + inv = det * torch.cat([top, bot], dim=-2) + inv = inv.reshape(B, N, 2, 2) + diff = uv_dist - uv_dist_est + a = inv[..., 0, 0] + b = inv[..., 0, 1] + c = inv[..., 1, 0] + d = inv[..., 1, 1] + e = diff[..., 0] + f = diff[..., 1] + step = torch.stack([a * e + b * f, c * e + d * f], dim=-1) + # Newton step. + xr_yr = xr_yr + step + + # Compute theta using Newton's method. + xr_yr_norm = xr_yr.norm(p=2, dim=2).reshape(B, N, 1) + th = xr_yr_norm.clone() + max_iters_radial = max_iters if self.use_radial else 0 + c = ( + torch.tensor([2.0 * i + 3 for i in range(3)], device=self.device) + .reshape(1, 1, 3) + .repeat(B, 1, 1) + ) + radial_params_num = self.params[..., 4:7].reshape(B, 1, 3) + + # Trust region parameters + delta = torch.full((B, N, 1), 0.1, device=self.device) # Initial trust radius + delta_max = torch.tensor(1.0, device=self.device) # Maximum trust radius + eta = 0.1 # Acceptable reduction threshold + + for i in range(max_iters_radial): + th_sq = th * th # th^2 + # Compute powers of th^2 up to th^(12) + theta_powers = torch.cat( + [th_sq ** (i + 1) for i in range(3)], dim=-1 + ) # Shape: (B, N, 6) + + # Compute th_radial: radial distortion model applied to th + th_radial = 1.0 + torch.sum( + theta_powers * radial_params_num, dim=-1, keepdim=True + ) + th_radial = th_radial * th # Multiply by th at the end + + # Compute derivative dthd_th + dthd_th = 1.0 + torch.sum( + c * radial_params_num * theta_powers, dim=-1, keepdim=True + ) + dthd_th = dthd_th # Already includes derivative terms + + # Compute residual + residual = th_radial - xr_yr_norm # Shape: (B, N, 1) + residual_norm = torch.norm(residual, dim=2, keepdim=True) # For each pixel + + # Check for convergence + if torch.max(torch.abs(residual)) < eps: + break + + # Avoid division by zero by adding a small epsilon + safe_dthd_th = dthd_th.clone() + zero_derivative_mask = dthd_th.abs() < eps + safe_dthd_th[zero_derivative_mask] = eps + + # Compute Newton's step + step = -residual / safe_dthd_th + + # Compute predicted reduction + predicted_reduction = -(residual * step).sum(dim=2, keepdim=True) + + # Adjust step based on trust region + step_norm = torch.norm(step, dim=2, keepdim=True) + over_trust_mask = step_norm > delta + + # Scale step if it exceeds trust radius + step_scaled = step.clone() + step_scaled[over_trust_mask] = step[over_trust_mask] * ( + delta[over_trust_mask] / step_norm[over_trust_mask] + ) + + # Update theta + th_new = th + step_scaled + + # Compute new residual + th_sq_new = th_new * th_new + theta_powers_new = torch.cat( + [th_sq_new ** (j + 1) for j in range(3)], dim=-1 + ) + th_radial_new = 1.0 + torch.sum( + theta_powers_new * radial_params_num, dim=-1, keepdim=True + ) + th_radial_new = th_radial_new * th_new + residual_new = th_radial_new - xr_yr_norm + residual_new_norm = torch.norm(residual_new, dim=2, keepdim=True) + + # Compute actual reduction + actual_reduction = residual_norm - residual_new_norm + + # Compute ratio of actual to predicted reduction + # predicted_reduction[predicted_reduction.abs() < eps] = eps #* torch.sign(predicted_reduction[predicted_reduction.abs() < eps]) + rho = actual_reduction / predicted_reduction + rho[(actual_reduction == 0) & (predicted_reduction == 0)] = 1.0 + + # Update trust radius delta + delta_update_mask = rho > 0.5 + delta[delta_update_mask] = torch.min( + 2.0 * delta[delta_update_mask], delta_max + ) + + delta_decrease_mask = rho < 0.2 + delta[delta_decrease_mask] = 0.25 * delta[delta_decrease_mask] + + # Accept or reject the step + accept_step_mask = rho > eta + th = torch.where(accept_step_mask, th_new, th) + + # Compute the ray direction using theta and xr_yr. + close_to_zero = torch.logical_and(th.abs() < eps, xr_yr_norm.abs() < eps) + ray_dir = torch.where(close_to_zero, xr_yr, th / xr_yr_norm * xr_yr) + + ray = torch.cat([ray_dir, uv.new_ones(B, N, 1)], dim=2) + ray = ray.reshape(B, H, W, 3).permute(0, 3, 1, 2) + + return ray + + +class Fisheye624(Camera): + def __init__(self, params): + super().__init__(params=params, K=None) + self.use_radial = self.params[..., 4:10].abs().sum() > 1e-6 + self.use_tangential = self.params[..., 10:12].abs().sum() > 1e-6 + self.use_thin_prism = self.params[..., 12:].abs().sum() > 1e-6 + + @torch.autocast(device_type="cuda", enabled=False, dtype=torch.float32) + def project(self, xyz): + eps = 1e-9 + B, _, H, W = xyz.shape + N = H * W + xyz = xyz.permute(0, 2, 3, 1).reshape(B, N, 3) + + # Radial correction. + z = xyz[:, :, 2].reshape(B, N, 1) + z = torch.where(torch.abs(z) < eps, eps * torch.sign(z), z) + ab = xyz[:, :, :2] / z + r = torch.norm(ab, dim=-1, p=2, keepdim=True) + th = torch.atan(r) + th_divr = torch.where(r < eps, torch.ones_like(ab), ab / r) + + th_pow = torch.cat( + [torch.pow(th, 3 + i * 2) for i in range(6)], dim=-1 + ) # Create powers of th (th^3, th^5, ...) + distortion_coeffs = self.params[:, 4:10].reshape(B, 1, 6) + th_k = th + torch.sum(th_pow * distortion_coeffs, dim=-1, keepdim=True) + + xr_yr = th_k * th_divr + uv_dist = xr_yr + + # Tangential correction. + p0 = self.params[..., -6].reshape(B, 1) + p1 = self.params[..., -5].reshape(B, 1) + xr = xr_yr[:, :, 0].reshape(B, N) + yr = xr_yr[:, :, 1].reshape(B, N) + xr_yr_sq = torch.square(xr_yr) + xr_sq = xr_yr_sq[:, :, 0].reshape(B, N) + yr_sq = xr_yr_sq[:, :, 1].reshape(B, N) + rd_sq = xr_sq + yr_sq + uv_dist_tu = uv_dist[:, :, 0] + ( + (2.0 * xr_sq + rd_sq) * p0 + 2.0 * xr * yr * p1 + ) + uv_dist_tv = uv_dist[:, :, 1] + ( + (2.0 * yr_sq + rd_sq) * p1 + 2.0 * xr * yr * p0 + ) + uv_dist = torch.stack( + [uv_dist_tu, uv_dist_tv], dim=-1 + ) # Avoids in-place complaint. + + # Thin Prism correction. + s0 = self.params[..., -4].reshape(B, 1) + s1 = self.params[..., -3].reshape(B, 1) + s2 = self.params[..., -2].reshape(B, 1) + s3 = self.params[..., -1].reshape(B, 1) + rd_4 = torch.square(rd_sq) + uv_dist[:, :, 0] = uv_dist[:, :, 0] + (s0 * rd_sq + s1 * rd_4) + uv_dist[:, :, 1] = uv_dist[:, :, 1] + (s2 * rd_sq + s3 * rd_4) + + # Finally, apply standard terms: focal length and camera centers. + if self.params.shape[-1] == 15: + fx_fy = self.params[..., 0].reshape(B, 1, 1) + cx_cy = self.params[..., 1:3].reshape(B, 1, 2) + else: + fx_fy = self.params[..., 0:2].reshape(B, 1, 2) + cx_cy = self.params[..., 2:4].reshape(B, 1, 2) + result = uv_dist * fx_fy + cx_cy + + result = result.reshape(B, H, W, 2).permute(0, 3, 1, 2) + invalid = ( + (result[:, 0] < 0) + | (result[:, 0] > W) + | (result[:, 1] < 0) + | (result[:, 1] > H) + ) + self.projection_mask = (~invalid).unsqueeze(1) + self.overlap_mask = self.mask_overlap_projection(result) + + return result + + @torch.autocast(device_type="cuda", enabled=False, dtype=torch.float32) + def unproject(self, uv, max_iters: int = 10): + eps = 1e-3 + B, _, H, W = uv.shape + N = H * W + uv = uv.permute(0, 2, 3, 1).reshape(B, N, 2) + + if self.params.shape[-1] == 15: + fx_fy = self.params[..., 0].reshape(B, 1, 1) + cx_cy = self.params[..., 1:3].reshape(B, 1, 2) + else: + fx_fy = self.params[..., 0:2].reshape(B, 1, 2) + cx_cy = self.params[..., 2:4].reshape(B, 1, 2) + + uv_dist = (uv - cx_cy) / fx_fy + + # Compute xr_yr using Trust-region method. + xr_yr = uv_dist.clone() + max_iters_tanprism = ( + max_iters if self.use_thin_prism or self.use_tangential else 0 + ) + + for _ in range(max_iters_tanprism): + uv_dist_est = xr_yr.clone() + xr = xr_yr[..., 0].reshape(B, N) + yr = xr_yr[..., 1].reshape(B, N) + xr_yr_sq = torch.square(xr_yr) + xr_sq = xr_yr_sq[..., 0].reshape(B, N) + yr_sq = xr_yr_sq[..., 1].reshape(B, N) + rd_sq = xr_sq + yr_sq + + if self.use_tangential: + # Tangential terms. + p0 = self.params[..., -6].reshape(B, 1) + p1 = self.params[..., -5].reshape(B, 1) + uv_dist_est[..., 0] = uv_dist_est[..., 0] + ( + (2.0 * xr_sq + rd_sq) * p0 + 2.0 * xr * yr * p1 + ) + uv_dist_est[..., 1] = uv_dist_est[..., 1] + ( + (2.0 * yr_sq + rd_sq) * p1 + 2.0 * xr * yr * p0 + ) + + if self.use_thin_prism: + # Thin Prism terms. + s0 = self.params[..., -4].reshape(B, 1) + s1 = self.params[..., -3].reshape(B, 1) + s2 = self.params[..., -2].reshape(B, 1) + s3 = self.params[..., -1].reshape(B, 1) + rd_4 = torch.square(rd_sq) + uv_dist_est[:, :, 0] = uv_dist_est[:, :, 0] + (s0 * rd_sq + s1 * rd_4) + uv_dist_est[:, :, 1] = uv_dist_est[:, :, 1] + (s2 * rd_sq + s3 * rd_4) + + # Compute the derivative of uv_dist w.r.t. xr_yr. + duv_dist_dxr_yr = uv.new_ones(B, N, 2, 2) + + if self.use_tangential: + duv_dist_dxr_yr[..., 0, 0] = 1.0 + 6.0 * xr * p0 + 2.0 * yr * p1 + offdiag = 2.0 * (xr * p1 + yr * p0) + duv_dist_dxr_yr[..., 0, 1] = offdiag + duv_dist_dxr_yr[..., 1, 0] = offdiag + duv_dist_dxr_yr[..., 1, 1] = 1.0 + 6.0 * yr * p1 + 2.0 * xr * p0 + + if self.use_thin_prism: + xr_yr_sq_norm = xr_sq + yr_sq + temp1 = 2.0 * (s0 + 2.0 * s1 * xr_yr_sq_norm) + duv_dist_dxr_yr[..., 0, 0] = duv_dist_dxr_yr[..., 0, 0] + (xr * temp1) + duv_dist_dxr_yr[..., 0, 1] = duv_dist_dxr_yr[..., 0, 1] + (yr * temp1) + temp2 = 2.0 * (s2 + 2.0 * s3 * xr_yr_sq_norm) + duv_dist_dxr_yr[..., 1, 0] = duv_dist_dxr_yr[..., 1, 0] + (xr * temp2) + duv_dist_dxr_yr[..., 1, 1] = duv_dist_dxr_yr[..., 1, 1] + (yr * temp2) + + mat = duv_dist_dxr_yr.reshape(-1, 2, 2) + a = mat[:, 0, 0].reshape(-1, 1, 1) + b = mat[:, 0, 1].reshape(-1, 1, 1) + c = mat[:, 1, 0].reshape(-1, 1, 1) + d = mat[:, 1, 1].reshape(-1, 1, 1) + det = 1.0 / ((a * d) - (b * c)) + top = torch.cat([d, -b], dim=-1) + bot = torch.cat([-c, a], dim=-1) + inv = det * torch.cat([top, bot], dim=-2) + inv = inv.reshape(B, N, 2, 2) + diff = uv_dist - uv_dist_est + a = inv[..., 0, 0] + b = inv[..., 0, 1] + c = inv[..., 1, 0] + d = inv[..., 1, 1] + e = diff[..., 0] + f = diff[..., 1] + step = torch.stack([a * e + b * f, c * e + d * f], dim=-1) + # Newton step. + xr_yr = xr_yr + step + + # Compute theta using Newton's method. + xr_yr_norm = xr_yr.norm(p=2, dim=2).reshape(B, N, 1) + th = xr_yr_norm.clone() + max_iters_radial = max_iters if self.use_radial else 0 + c = ( + torch.tensor([2.0 * i + 3 for i in range(6)], device=self.device) + .reshape(1, 1, 6) + .repeat(B, 1, 1) + ) + radial_params = self.params[..., 4:10].reshape(B, 1, 6) + + # Trust region parameters + delta = torch.full((B, N, 1), 0.1, device=self.device) # Initial trust radius + delta_max = torch.tensor(1.0, device=self.device) # Maximum trust radius + eta = 0.1 # Acceptable reduction threshold + + for i in range(max_iters_radial): + th_sq = th * th + # Compute powers of th^2 up to th^(12) + theta_powers = torch.cat( + [th_sq ** (i + 1) for i in range(6)], dim=-1 + ) # Shape: (B, N, 6) + + # Compute th_radial: radial distortion model applied to th + th_radial = 1.0 + torch.sum( + theta_powers * radial_params, dim=-1, keepdim=True + ) + th_radial = th_radial * th + + # Compute derivative dthd_th + dthd_th = 1.0 + torch.sum( + c * radial_params * theta_powers, dim=-1, keepdim=True + ) + + # Compute residual + residual = th_radial - xr_yr_norm # Shape: (B, N, 1) + residual_norm = torch.norm(residual, dim=2, keepdim=True) + + # Check for convergence + if torch.max(torch.abs(residual)) < eps: + break + + # Avoid division by zero by adding a small epsilon + safe_dthd_th = dthd_th.clone() + zero_derivative_mask = dthd_th.abs() < eps + safe_dthd_th[zero_derivative_mask] = eps + + # Compute Newton's step + step = -residual / safe_dthd_th + + # Compute predicted reduction + predicted_reduction = -(residual * step).sum(dim=2, keepdim=True) + + # Adjust step based on trust region + step_norm = torch.norm(step, dim=2, keepdim=True) + over_trust_mask = step_norm > delta + + # Scale step if it exceeds trust radius + step_scaled = step.clone() + step_scaled[over_trust_mask] = step[over_trust_mask] * ( + delta[over_trust_mask] / step_norm[over_trust_mask] + ) + + # Update theta + th_new = th + step_scaled + + # Compute new residual + th_sq_new = th_new * th_new + theta_powers_new = torch.cat( + [th_sq_new ** (j + 1) for j in range(6)], dim=-1 + ) + th_radial_new = 1.0 + torch.sum( + theta_powers_new * radial_params, dim=-1, keepdim=True + ) + th_radial_new = th_radial_new * th_new + residual_new = th_radial_new - xr_yr_norm + residual_new_norm = torch.norm(residual_new, dim=2, keepdim=True) + + # Compute actual reduction + actual_reduction = residual_norm - residual_new_norm + + # Compute ratio of actual to predicted reduction + rho = actual_reduction / predicted_reduction + rho[(actual_reduction == 0) & (predicted_reduction == 0)] = 1.0 + + # Update trust radius delta + delta_update_mask = rho > 0.5 + delta[delta_update_mask] = torch.min( + 2.0 * delta[delta_update_mask], delta_max + ) + + delta_decrease_mask = rho < 0.2 + delta[delta_decrease_mask] = 0.25 * delta[delta_decrease_mask] + + # Accept or reject the step + accept_step_mask = rho > eta + th = torch.where(accept_step_mask, th_new, th) + + # Compute the ray direction using theta and xr_yr. + close_to_zero = torch.logical_and(th.abs() < eps, xr_yr_norm.abs() < eps) + ray_dir = torch.where(close_to_zero, xr_yr, torch.tan(th) / xr_yr_norm * xr_yr) + + ray = torch.cat([ray_dir, uv.new_ones(B, N, 1)], dim=2) + ray = ray.reshape(B, H, W, 3).permute(0, 3, 1, 2) + + return ray + + +class MEI(Camera): + def __init__(self, params): + super().__init__(params=params, K=None) + # fx fy cx cy k1 k2 p1 p2 xi + self.use_radial = self.params[..., 4:6].abs().sum() > 1e-6 + self.use_tangential = self.params[..., 6:8].abs().sum() > 1e-6 + + @torch.autocast(device_type="cuda", enabled=False, dtype=torch.float32) + def unproject(self, uv, max_iters: int = 20): + eps = 1e-6 + B, _, H, W = uv.shape + N = H * W + uv = uv.permute(0, 2, 3, 1).reshape(B, N, 2) + + k1, k2, p0, p1, xi = self.params[..., 4:9].unbind(dim=1) + fx_fy = self.params[..., 0:2].reshape(B, 1, 2) + cx_cy = self.params[..., 2:4].reshape(B, 1, 2) + + uv_dist = (uv - cx_cy) / fx_fy + + # Compute xr_yr using Newton's method. + xr_yr = uv_dist.clone() # Initial guess. + max_iters_tangential = max_iters if self.use_tangential else 0 + for _ in range(max_iters_tangential): + uv_dist_est = xr_yr.clone() + + # Tangential terms. + xr = xr_yr[..., 0] + yr = xr_yr[..., 1] + xr_yr_sq = xr_yr**2 + xr_sq = xr_yr_sq[..., 0] + yr_sq = xr_yr_sq[..., 1] + rd_sq = xr_sq + yr_sq + uv_dist_est[..., 0] = uv_dist_est[..., 0] + ( + (2.0 * xr_sq + rd_sq) * p0 + 2.0 * xr * yr * p1 + ) + uv_dist_est[..., 1] = uv_dist_est[..., 1] + ( + (2.0 * yr_sq + rd_sq) * p1 + 2.0 * xr * yr * p0 + ) + + # Compute the derivative of uv_dist w.r.t. xr_yr. + duv_dist_dxr_yr = torch.ones((B, N, 2, 2), device=uv.device) + duv_dist_dxr_yr[..., 0, 0] = 1.0 + 6.0 * xr * p0 + 2.0 * yr * p1 + offdiag = 2.0 * (xr * p1 + yr * p0) + duv_dist_dxr_yr[..., 0, 1] = offdiag + duv_dist_dxr_yr[..., 1, 0] = offdiag + duv_dist_dxr_yr[..., 1, 1] = 1.0 + 6.0 * yr * p1 + 2.0 * xr * p0 + + mat = duv_dist_dxr_yr.reshape(-1, 2, 2) + a = mat[:, 0, 0].reshape(-1, 1, 1) + b = mat[:, 0, 1].reshape(-1, 1, 1) + c = mat[:, 1, 0].reshape(-1, 1, 1) + d = mat[:, 1, 1].reshape(-1, 1, 1) + det = 1.0 / ((a * d) - (b * c)) + top = torch.cat([d, -b], dim=-1) + bot = torch.cat([-c, a], dim=-1) + inv = det * torch.cat([top, bot], dim=-2) + inv = inv.reshape(B, N, 2, 2) + + diff = uv_dist - uv_dist_est + a = inv[..., 0, 0] + b = inv[..., 0, 1] + c = inv[..., 1, 0] + d = inv[..., 1, 1] + e = diff[..., 0] + f = diff[..., 1] + step = torch.stack([a * e + b * f, c * e + d * f], dim=-1) + + # Newton step. + xr_yr = xr_yr + step + + # Compute theta using Newton's method. + xr_yr_norm = xr_yr.norm(p=2, dim=2).reshape(B, N, 1) + th = xr_yr_norm.clone() + max_iters_radial = max_iters if self.use_radial else 0 + for _ in range(max_iters_radial): + th_radial = 1.0 + k1 * torch.pow(th, 2) + k2 * torch.pow(th, 4) + dthd_th = 1.0 + 3.0 * k1 * torch.pow(th, 2) + 5.0 * k2 * torch.pow(th, 4) + th_radial = th_radial * th + step = (xr_yr_norm - th_radial) / dthd_th + # handle dthd_th close to 0. + step = torch.where( + torch.abs(dthd_th) > eps, step, torch.sign(step) * eps * 10.0 + ) + th = th + step + + # Compute the ray direction using theta and xr_yr. + close_to_zero = (torch.abs(th) < eps) & (torch.abs(xr_yr_norm) < eps) + ray_dir = torch.where(close_to_zero, xr_yr, th * xr_yr / xr_yr_norm) + + # Compute the 3D projective ray + rho2_u = ( + ray_dir.norm(p=2, dim=2, keepdim=True) ** 2 + ) # B N 1 # x_c * x_c + y_c * y_c + xi = xi.reshape(B, 1, 1) + sqrt_term = torch.sqrt(1.0 + (1.0 - xi * xi) * rho2_u) + P_z = 1.0 - xi * (rho2_u + 1.0) / (xi + sqrt_term) + + # Special case when xi is 1.0 (unit sphere projection ??) + P_z = torch.where(xi == 1.0, (1.0 - rho2_u) / 2.0, P_z) + + ray = torch.cat([ray_dir, P_z], dim=-1) + ray = ray.reshape(B, H, W, 3).permute(0, 3, 1, 2) + + return ray + + @torch.autocast(device_type="cuda", enabled=False, dtype=torch.float32) + def project(self, xyz): + is_flat = xyz.ndim == 3 + B, N = xyz.shape[:2] + + if not is_flat: + B, _, H, W = xyz.shape + N = H * W + xyz = xyz.permute(0, 2, 3, 1).reshape(B, N, 3) + + k1, k2, p0, p1, xi = self.params[..., 4:].unbind(dim=1) + fx_fy = self.params[..., 0:2].reshape(B, 1, 2) + cx_cy = self.params[..., 2:4].reshape(B, 1, 2) + + norm = xyz.norm(p=2, dim=-1, keepdim=True) + ab = xyz[..., :-1] / (xyz[..., -1:] + xi.reshape(B, 1, 1) * norm) + + # radial correction + r = ab.norm(dim=-1, p=2, keepdim=True) + k1 = self.params[..., 4].reshape(B, 1, 1) + k2 = self.params[..., 5].reshape(B, 1, 1) + # ab / r * th * (1 + k1 * (th ** 2) + k2 * (th**4)) + # but here r = th, no spherical distortion + xr_yr = ab * (1 + k1 * (r**2) + k2 * (r**4)) + + # Tangential correction. + uv_dist = xr_yr + p0 = self.params[:, -3].reshape(B, 1) + p1 = self.params[:, -2].reshape(B, 1) + xr = xr_yr[..., 0].reshape(B, N) + yr = xr_yr[..., 1].reshape(B, N) + xr_yr_sq = torch.square(xr_yr) + xr_sq = xr_yr_sq[:, :, 0].reshape(B, N) + yr_sq = xr_yr_sq[:, :, 1].reshape(B, N) + rd_sq = xr_sq + yr_sq + uv_dist_tu = uv_dist[:, :, 0] + ( + (2.0 * xr_sq + rd_sq) * p0 + 2.0 * xr * yr * p1 + ) + uv_dist_tv = uv_dist[:, :, 1] + ( + (2.0 * yr_sq + rd_sq) * p1 + 2.0 * xr * yr * p0 + ) + uv_dist = torch.stack( + [uv_dist_tu, uv_dist_tv], dim=-1 + ) # Avoids in-place complaint. + + result = uv_dist * fx_fy + cx_cy + + if not is_flat: + result = result.reshape(B, H, W, 2).permute(0, 3, 1, 2) + invalid = ( + (result[:, 0] < 0) + | (result[:, 0] > W) + | (result[:, 1] < 0) + | (result[:, 1] > H) + ) + self.projection_mask = (~invalid).unsqueeze(1) + # creates hole in the middle... ?? + # self.overlap_mask = self.mask_overlap_projection(result) + + return result + + +class BatchCamera(Camera): + """ + This is not to be used directly, but to be used as a wrapper around multiple cameras. + It should expose only the `from_camera` method as it the only way to create a BatchCamera. + """ + + def __init__(self, params, K, original_class, cameras): + super().__init__(params, K) + self.original_class = original_class + self.cameras = cameras + + # Delegate these methods to original camera + @torch.autocast(device_type="cuda", enabled=False, dtype=torch.float32) + def project(self, points_3d): + return torch.cat( + [ + camera.project(points_3d[i : i + 1]) + for i, camera in enumerate(self.cameras) + ] + ) + + @torch.autocast(device_type="cuda", enabled=False, dtype=torch.float32) + def unproject(self, points_2d): + val = torch.cat( + [camera.unproject(points_2d) for i, camera in enumerate(self.cameras)] + ) + return val + + def crop(self, left, top, right=None, bottom=None): + val = torch.cat( + [ + camera.crop(left, top, right, bottom) + for i, camera in enumerate(self.cameras) + ] + ) + return val + + def resize(self, ratio): + val = torch.cat([camera.resize(ratio) for i, camera in enumerate(self.cameras)]) + return val + + def reconstruct(self, depth): + val = torch.cat( + [ + camera.reconstruct(depth[i : i + 1]) + for i, camera in enumerate(self.cameras) + ] + ) + return val + + def get_projection_mask(self): + return torch.cat( + [camera.projection_mask for i, camera in enumerate(self.cameras)] + ) + + def to(self, device, non_blocking=False): + self = super().to(device, non_blocking=non_blocking) + self.cameras = recursive_to( + self.cameras, device, non_blocking=non_blocking, cls=Camera + ) + return self + + def reshape(self, *shape): + # Reshape the intrinsic matrix (K) and params + # we know that the shape of K is (..., 3, 3) and params is (..., 16) + reshaped_K = self.K.reshape(*shape, 3, 3) + reshaped_params = self.params.reshape(*shape, self.params.shape[-1]) + + self.cameras = np.array(self.cameras, dtype=object).reshape(shape).tolist() + self.original_class = ( + np.array(self.original_class, dtype=object).reshape(shape).tolist() + ) + + # Create a new BatchCamera with reshaped K and params + return BatchCamera( + reshaped_params, reshaped_K, self.original_class, self.cameras + ) + + def get_new_fov(self, new_shape, original_shape): + return [ + camera.get_new_fov(new_shape, original_shape) + for i, camera in enumerate(self.cameras) + ] + + def squeeze(self, dim): + return BatchCamera( + self.params.squeeze(dim), + self.K.squeeze(dim), + squeeze_list(self.original_class, dim=dim), + squeeze_list(self.cameras, dim=dim), + ) + + def __getitem__(self, idx): + if isinstance(idx, int): + return self.cameras[idx] + + elif isinstance(idx, slice): + return BatchCamera( + self.params[idx], + self.K[idx], + self.original_class[idx], + self.cameras[idx], + ) + + raise TypeError(f"Invalid index type: {type(idx)}") + + def __setitem__(self, idx, value): + # If it's an integer index, return a single camera + if isinstance(idx, int): + self.cameras[idx] = value + self.params[idx, :] = 0.0 + self.params[idx, : value.params.shape[1]] = value.params[0] + self.K[idx] = value.K[0] + + self.original_class[idx] = getattr( + value, "original_class", value.__class__.__name__ + ) + + # If it's a slice, return a new BatchCamera with sliced cameras + elif isinstance(idx, slice): + # Update each internal attribute using the slice + self.params[idx] = value.params + self.K[idx] = value.K + self.original_class[idx] = value.original_class + self.cameras[idx] = value.cameras + + def __len__(self): + return len(self.cameras) + + @classmethod + def from_camera(cls, camera): + return cls(camera.params, camera.K, [camera.__class__.__name__], [camera]) + + @property + def is_perspective(self): + return [isinstance(camera, Pinhole) for camera in self.cameras] + + @property + def is_spherical(self): + return [isinstance(camera, Spherical) for camera in self.cameras] + + @property + def is_eucm(self): + return [isinstance(camera, EUCM) for camera in self.cameras] + + @property + def is_fisheye(self): + return [isinstance(camera, Fisheye624) for camera in self.cameras] + + @property + def is_pinhole(self): + return [isinstance(camera, Pinhole) for camera in self.cameras] + + @property + def hfov(self): + return [camera.hfov for camera in self.cameras] + + @property + def vfov(self): + return [camera.vfov for camera in self.cameras] + + @property + def max_fov(self): + return [camera.max_fov for camera in self.cameras] diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/utils/chamfer_distance.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/utils/chamfer_distance.py new file mode 100644 index 0000000000000000000000000000000000000000..856a440b3d7f76e8f92ed70ca596a058991dd71d --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/utils/chamfer_distance.py @@ -0,0 +1,158 @@ +import warnings +from typing import Union + +import torch + +try: + from unidepth.ops.knn import knn_points +except ImportError as e: + warnings.warn( + "!! To run evaluation you need KNN. Please compile KNN: " + "`cd unidepth/ops/knn with && bash compile.sh`." + ) + knn_points = lambda x : x + + +def _validate_chamfer_reduction_inputs( + batch_reduction: Union[str, None], point_reduction: str +): + """Check the requested reductions are valid. + + Args: + batch_reduction: Reduction operation to apply for the loss across the + batch, can be one of ["mean", "sum"] or None. + point_reduction: Reduction operation to apply for the loss across the + points, can be one of ["mean", "sum"]. + """ + if batch_reduction is not None and batch_reduction not in ["mean", "sum"]: + raise ValueError('batch_reduction must be one of ["mean", "sum"] or None') + if point_reduction not in ["mean", "sum"]: + raise ValueError('point_reduction must be one of ["mean", "sum"]') + + +def _handle_pointcloud_input( + points: torch.Tensor, + lengths: Union[torch.Tensor, None], + normals: Union[torch.Tensor, None], +): + """ + If points is an instance of Pointclouds, retrieve the padded points tensor + along with the number of points per batch and the padded normals. + Otherwise, return the input points (and normals) with the number of points per cloud + set to the size of the second dimension of `points`. + """ + if points.ndim != 3: + raise ValueError("Expected points to be of shape (N, P, D)") + X = points + if lengths is not None and (lengths.ndim != 1 or lengths.shape[0] != X.shape[0]): + raise ValueError("Expected lengths to be of shape (N,)") + if lengths is None: + lengths = torch.full( + (X.shape[0],), X.shape[1], dtype=torch.int64, device=points.device + ) + if normals is not None and normals.ndim != 3: + raise ValueError("Expected normals to be of shape (N, P, 3") + + return X, lengths, normals + + +class ChamferDistance(torch.nn.Module): + def forward( + self, + x, + y, + x_lengths=None, + y_lengths=None, + x_normals=None, + y_normals=None, + weights=None, + batch_reduction: Union[str, None] = "mean", + point_reduction: str = "mean", + ): + """ + Chamfer distance between two pointclouds x and y. + + Args: + x: FloatTensor of shape (N, P1, D) or a Pointclouds object representing + a batch of point clouds with at most P1 points in each batch element, + batch size N and feature dimension D. + y: FloatTensor of shape (N, P2, D) or a Pointclouds object representing + a batch of point clouds with at most P2 points in each batch element, + batch size N and feature dimension D. + x_lengths: Optional LongTensor of shape (N,) giving the number of points in each + cloud in x. + y_lengths: Optional LongTensor of shape (N,) giving the number of points in each + cloud in x. + x_normals: Optional FloatTensor of shape (N, P1, D). + y_normals: Optional FloatTensor of shape (N, P2, D). + weights: Optional FloatTensor of shape (N,) giving weights for + batch elements for reduction operation. + batch_reduction: Reduction operation to apply for the loss across the + batch, can be one of ["mean", "sum"] or None. + point_reduction: Reduction operation to apply for the loss across the + points, can be one of ["mean", "sum"]. + + Returns: + 2-element tuple containing + + - **loss**: Tensor giving the reduced distance between the pointclouds + in x and the pointclouds in y. + - **loss_normals**: Tensor giving the reduced cosine distance of normals + between pointclouds in x and pointclouds in y. Returns None if + x_normals and y_normals are None. + """ + _validate_chamfer_reduction_inputs(batch_reduction, point_reduction) + + x, x_lengths, x_normals = _handle_pointcloud_input(x, x_lengths, x_normals) + y, y_lengths, y_normals = _handle_pointcloud_input(y, y_lengths, y_normals) + + return_normals = x_normals is not None and y_normals is not None + + N, P1, D = x.shape + P2 = y.shape[1] + + # Check if inputs are heterogeneous and create a lengths mask. + is_x_heterogeneous = (x_lengths != P1).any() + is_y_heterogeneous = (y_lengths != P2).any() + x_mask = ( + torch.arange(P1, device=x.device)[None] >= x_lengths[:, None] + ) # shape [N, P1] + y_mask = ( + torch.arange(P2, device=y.device)[None] >= y_lengths[:, None] + ) # shape [N, P2] + + if y.shape[0] != N or y.shape[2] != D: + raise ValueError("y does not have the correct shape.") + if weights is not None: + if weights.size(0) != N: + raise ValueError("weights must be of shape (N,).") + if not (weights >= 0).all(): + raise ValueError("weights cannot be negative.") + if weights.sum() == 0.0: + weights = weights.view(N, 1) + if batch_reduction in ["mean", "sum"]: + return ( + (x.sum((1, 2)) * weights).sum() * 0.0, + (x.sum((1, 2)) * weights).sum() * 0.0, + ) + return ( + (x.sum((1, 2)) * weights) * 0.0, + (x.sum((1, 2)) * weights) * 0.0, + ) + + x_nn = knn_points(x, y, lengths1=x_lengths, lengths2=y_lengths, K=1) + y_nn = knn_points(y, x, lengths1=y_lengths, lengths2=x_lengths, K=1) + + cham_x = x_nn.dists[..., 0] # (N, P1) + cham_y = y_nn.dists[..., 0] # (N, P2) + + if is_x_heterogeneous: + cham_x[x_mask] = 0.0 + if is_y_heterogeneous: + cham_y[y_mask] = 0.0 + + if weights is not None: + cham_x *= weights.view(N, 1) + cham_y *= weights.view(N, 1) + + return cham_x, cham_y, x_nn.idx[..., -1], y_nn.idx[..., -1] diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/utils/constants.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/utils/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..60d16124acef45fcf415d450b7aa226f1cc77253 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/utils/constants.py @@ -0,0 +1,20 @@ +""" +Author: Luigi Piccinelli +Licensed under the CC-BY NC 4.0 license (http://creativecommons.org/licenses/by-nc/4.0/) +""" + +import math + +import torch + +OPENAI_DATASET_MEAN = (0.48145466, 0.4578275, 0.40821073) +OPENAI_DATASET_STD = (0.26862954, 0.26130258, 0.27577711) +IMAGENET_DATASET_MEAN = (0.485, 0.456, 0.406) +IMAGENET_DATASET_STD = (0.229, 0.224, 0.225) +DEPTH_BINS = torch.cat( + ( + torch.logspace(math.log10(0.1), math.log10(180.0), steps=512), + torch.tensor([260.0]), + ), + dim=0, +) diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/utils/coordinate.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/utils/coordinate.py new file mode 100644 index 0000000000000000000000000000000000000000..a09129982737d288db26a3717337af136d163c32 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/utils/coordinate.py @@ -0,0 +1,27 @@ +import torch + + +def coords_grid(b, h, w, homogeneous=False, device=None, noisy=False): + pixel_coords_x = torch.linspace(0.5, w - 0.5, w, device=device) + pixel_coords_y = torch.linspace(0.5, h - 0.5, h, device=device) + if noisy: # \pm 0.5px noise + pixel_coords_x += torch.rand_like(pixel_coords_x) - 0.5 + pixel_coords_y += torch.rand_like(pixel_coords_y) - 0.5 + + stacks = [pixel_coords_x.repeat(h, 1), pixel_coords_y.repeat(w, 1).t()] + if homogeneous: + ones = torch.ones_like(stacks[0]) # [H, W] + stacks.append(ones) + grid = torch.stack(stacks, dim=0).float() # [2, H, W] or [3, H, W] + grid = grid[None].repeat(b, 1, 1, 1) # [B, 2, H, W] or [B, 3, H, W] + if device is not None: + grid = grid.to(device) + + return grid + + +def normalize_coords(coords, h, w): + c = torch.tensor([(w - 1) / 2.0, (h - 1) / 2.0], device=coords.device).view( + 1, 2, 1, 1 + ) + return (coords - c) / c diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/utils/distributed.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/utils/distributed.py new file mode 100644 index 0000000000000000000000000000000000000000..2b38e3f7a6998b81f29d91e00192507f28621b13 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/utils/distributed.py @@ -0,0 +1,244 @@ +import os +import pickle +import platform +import subprocess +import warnings + +import cv2 +import torch +import torch.utils.data.distributed +from torch import distributed as dist +from torch import multiprocessing as mp + +_LOCAL_PROCESS_GROUP = None + + +def is_dist_avail_and_initialized(): + if not dist.is_available(): + return False + if not dist.is_initialized(): + return False + return True + + +def get_rank(): + if not is_dist_avail_and_initialized(): + return 0 + return dist.get_rank() + + +def get_local_rank() -> int: + """ + Returns: + The rank of the current process within the local (per-machine) process group. + """ + if not is_dist_avail_and_initialized(): + return 0 + assert _LOCAL_PROCESS_GROUP is not None + return dist.get_rank(group=_LOCAL_PROCESS_GROUP) + + +def get_local_size() -> int: + """ + Returns: + The size of the per-machine process group, + i.e. the number of processes per machine. + """ + if not is_dist_avail_and_initialized(): + return 1 + assert _LOCAL_PROCESS_GROUP is not None + return dist.get_world_size(group=_LOCAL_PROCESS_GROUP) + + +def get_world_size(): + if not is_dist_avail_and_initialized(): + return 1 + return dist.get_world_size() + + +def barrier(): + if not is_dist_avail_and_initialized(): + return + dist.barrier() + + +def is_main_process(): + return get_rank() == 0 + + +def is_rank_zero(args): + return args.rank == 0 + + +def get_dist_info(): + if dist.is_available() and dist.is_initialized(): + rank = dist.get_rank() + world_size = dist.get_world_size() + else: + rank = 0 + world_size = 1 + return rank, world_size + + +def setup_multi_processes(cfg): + """Setup multi-processing environment variables.""" + # set multi-process start method as `fork` to speed up the training + if platform.system() != "Windows": + mp_start_method = cfg.get("mp_start_method", "fork") + current_method = mp.get_start_method(allow_none=True) + if current_method is not None and current_method != mp_start_method: + warnings.warn( + f"Multi-processing start method `{mp_start_method}` is " + f"different from the previous setting `{current_method}`." + f"It will be force set to `{mp_start_method}`. You can change " + f"this behavior by changing `mp_start_method` in your config." + ) + mp.set_start_method(mp_start_method, force=True) + + # disable opencv multithreading to avoid system being overloaded + # opencv_num_threads = cfg.get('opencv_num_threads', 0) + # cv2.setNumThreads(opencv_num_threads) + + # setup OMP threads + # This code is referred from https://github.com/pytorch/pytorch/blob/master/torch/distributed/run.py # noqa + # workers_per_gpu = cfg.get('workers_per_gpu', 4) + + # if 'OMP_NUM_THREADS' not in os.environ and workers_per_gpu > 1: + # omp_num_threads = 1 + # warnings.warn( + # f'Setting OMP_NUM_THREADS environment variable for each process ' + # f'to be {omp_num_threads} in default, to avoid your system being ' + # f'overloaded, please further tune the variable for optimal ' + # f'performance in your application as needed.') + # os.environ['OMP_NUM_THREADS'] = str(omp_num_threads) + + # setup MKL threads + # if 'MKL_NUM_THREADS' not in os.environ and workers_per_gpu > 1: + # mkl_num_threads = os.environ.get('OMP_NUM_THREADS', 1) + # warnings.warn( + # f'Setting MKL_NUM_THREADS environment variable for each process ' + # f'to be {mkl_num_threads} in default, to avoid your system being ' + # f'overloaded, please further tune the variable for optimal ' + # f'performance in your application as needed.') + # os.environ['MKL_NUM_THREADS'] = str(mkl_num_threads) + + +def setup_slurm(backend: str, port: str) -> None: + proc_id = int(os.environ["SLURM_PROCID"]) + ntasks = int(os.environ["SLURM_NTASKS"]) + node_list = os.environ["SLURM_NODELIST"] + + num_gpus = torch.cuda.device_count() + + torch.cuda.set_device(proc_id % num_gpus) + addr = subprocess.getoutput(f"scontrol show hostname {node_list} | head -n1") + os.environ["MASTER_PORT"] = str(port) + os.environ["MASTER_ADDR"] = addr + os.environ["WORLD_SIZE"] = str(ntasks) + os.environ["LOCAL_RANK"] = str(proc_id % num_gpus) + os.environ["RANK"] = str(proc_id) + print( + proc_id, + ntasks, + num_gpus, + proc_id % num_gpus, + node_list, + addr, + os.environ["MASTER_PORT"], + os.system("nvidia-smi -L"), + ) + dist.init_process_group(backend, rank=proc_id, world_size=ntasks) + + +def sync_tensor_across_gpus(t, dim=0, cat=True): + if t is None or not (dist.is_available() and dist.is_initialized()): + return t + t = torch.atleast_1d(t) + group = dist.group.WORLD + group_size = torch.distributed.get_world_size(group) + + local_size = torch.tensor(t.size(dim), device=t.device) + all_sizes = [torch.zeros_like(local_size) for _ in range(group_size)] + dist.all_gather(all_sizes, local_size) + max_size = max(all_sizes) + size_diff = max_size.item() - local_size.item() + if size_diff: + padding = torch.zeros(size_diff, device=t.device, dtype=t.dtype) + t = torch.cat((t, padding)) + + gather_t_tensor = [torch.zeros_like(t) for _ in range(group_size)] + dist.all_gather(gather_t_tensor, t) + all_ts = [] + for t, size in zip(gather_t_tensor, all_sizes): + all_ts.append(t[:size]) + if cat: + return torch.cat(all_ts, dim=0) + return all_ts + + +def sync_string_across_gpus(keys: list[str], device, dim=0): + keys_serialized = pickle.dumps(keys, protocol=pickle.HIGHEST_PROTOCOL) + keys_serialized_tensor = ( + torch.frombuffer(keys_serialized, dtype=torch.uint8).clone().to(device) + ) + keys_serialized_tensor = sync_tensor_across_gpus( + keys_serialized_tensor, dim=0, cat=False + ) + keys = [ + key + for keys in keys_serialized_tensor + for key in pickle.loads(bytes(keys.cpu().tolist())) + ] + return keys + + +def create_local_process_group() -> None: + num_workers_per_machine = torch.cuda.device_count() + global _LOCAL_PROCESS_GROUP + assert _LOCAL_PROCESS_GROUP is None + assert get_world_size() % num_workers_per_machine == 0 + num_machines = get_world_size() // num_workers_per_machine + machine_rank = get_rank() // num_workers_per_machine + for i in range(num_machines): + ranks_on_i = list( + range(i * num_workers_per_machine, (i + 1) * num_workers_per_machine) + ) + pg = dist.new_group(ranks_on_i) + if i == machine_rank: + _LOCAL_PROCESS_GROUP = pg + + +def _get_global_gloo_group(): + if dist.get_backend() == "nccl": + return dist.new_group(backend="gloo") + else: + return dist.group.WORLD + + +def all_gather(data, group=None): + if get_world_size() == 1: + return [data] + if group is None: + group = ( + _get_global_gloo_group() + ) # use CPU group by default, to reduce GPU RAM usage. + world_size = dist.get_world_size(group) + if world_size == 1: + return [data] + + output = [None for _ in range(world_size)] + dist.all_gather_object(output, data, group=group) + return output + + +def local_broadcast_process_authkey(): + if get_local_size() == 1: + return + local_rank = get_local_rank() + authkey = bytes(mp.current_process().authkey) + all_keys = all_gather(authkey) + local_leader_key = all_keys[get_rank() - local_rank] + if authkey != local_leader_key: + # print("Process authkey is different from the key of local leader! workers are launched independently ??") + # print("Overwriting local authkey ...") + mp.current_process().authkey = local_leader_key diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/utils/ema_torch.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/utils/ema_torch.py new file mode 100644 index 0000000000000000000000000000000000000000..bea1d29a8c224b81b19ac68fe02453a4330ed58c --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/utils/ema_torch.py @@ -0,0 +1,341 @@ +""" +Author: Luigi Piccinelli +Licensed under the CC-BY NC 4.0 license (http://creativecommons.org/licenses/by-nc/4.0/) +""" + +from __future__ import division, unicode_literals + +import contextlib +import copy +import weakref +from math import tanh +from typing import Iterable, Optional + +import torch + + +class DummyExponentialMovingAverage: + def __init__(self, *args, **kwargs): + pass + + def _get_parameters(self, *args, **kwargs): + pass + + def get_current_decay(self, *args, **kwargs): + pass + + def update(self, *args, **kwargs): + pass + + def copy_to(self, *args, **kwargs): + pass + + def store(self, *args, **kwargs): + return + + def restore(self, *args, **kwargs): + return + + @contextlib.contextmanager + def average_parameters(self, *args, **kwargs): + try: + yield + finally: + pass + + def to(self, *args, **kwargs): + pass + + def state_dict(self, *args, **kwargs): + pass + + def load_state_dict(self, *args, **kwargs): + pass + + +class ExponentialMovingAverage: + """ + Maintains (exponential) moving average of a set of parameters. + + Args: + parameters: Iterable of `torch.nn.Parameter` (typically from + `model.parameters()`). + Note that EMA is computed on *all* provided parameters, + regardless of whether or not they have `requires_grad = True`; + this allows a single EMA object to be consistantly used even + if which parameters are trainable changes step to step. + + If you want to some parameters in the EMA, do not pass them + to the object in the first place. For example: + + ExponentialMovingAverage( + parameters=[p for p in model.parameters() if p.requires_grad], + decay=0.9 + ) + + will ignore parameters that do not require grad. + + decay: The exponential decay. + + use_num_updates: Whether to use number of updates when computing + averages. + """ + + def __init__( + self, + parameters: Iterable[torch.nn.Parameter], + decay: float, + use_num_updates: bool = True, + update_after_step: int = 10000, + tau: int = 20000, + switch: bool = False, + ): + if decay < 0.0 or decay > 1.0: + raise ValueError("Decay must be between 0 and 1") + self.decay = decay + self.switch = switch # fi keeping EMA params in model after epochs + self.num_updates = 0 if use_num_updates else None + parameters = list(parameters) + self.shadow_params = [p.clone().detach() for p in parameters] + self.collected_params = None + # By maintaining only a weakref to each parameter, + # we maintain the old GC behaviour of ExponentialMovingAverage: + # if the model goes out of scope but the ExponentialMovingAverage + # is kept, no references to the model or its parameters will be + # maintained, and the model will be cleaned up. + self._params_refs = [weakref.ref(p) for p in parameters] + self.update_after_step = update_after_step + self.tau = tau + + def _get_parameters( + self, parameters: Optional[Iterable[torch.nn.Parameter]] + ) -> Iterable[torch.nn.Parameter]: + if parameters is None: + parameters = [p() for p in self._params_refs] + if any(p is None for p in parameters): + raise ValueError( + "(One of) the parameters with which this ExponentialMovingAverage was initialized no longer exists (was garbage collected);" + " please either provide `parameters` explicitly or keep the model to which they belong from being garbage collected." + ) + return parameters + else: + parameters = list(parameters) + if len(parameters) != len(self.shadow_params): + raise ValueError( + "Number of parameters passed as argument is different " + "from number of shadow parameters maintained by this " + "ExponentialMovingAverage" + ) + return parameters + + def get_current_decay(self): + epoch = max(self.num_updates - self.update_after_step - 1, 0.0) + if epoch <= 0: + return 0.0 + value = tanh(epoch / self.tau) * self.decay + return value + + def update(self, parameters: Optional[Iterable[torch.nn.Parameter]] = None) -> None: + """ + Update currently maintained parameters. + + Call this every time the parameters are updated, such as the result of + the `optimizer.step()` call. + + Args: + parameters: Iterable of `torch.nn.Parameter`; usually the same set of + parameters used to initialize this object. If `None`, the + parameters with which this `ExponentialMovingAverage` was + initialized will be used. + """ + parameters = self._get_parameters(parameters) + decay = self.get_current_decay() + if self.num_updates is not None: + self.num_updates += 1 + + one_minus_decay = 1.0 - decay + with torch.no_grad(): + for s_param, param in zip(self.shadow_params, parameters): + tmp = s_param - param + # tmp will be a new tensor so we can do in-place + tmp.mul_(one_minus_decay) + s_param.sub_(tmp) + + def copy_to( + self, parameters: Optional[Iterable[torch.nn.Parameter]] = None + ) -> None: + """ + Copy current averaged parameters into given collection of parameters. + + Args: + parameters: Iterable of `torch.nn.Parameter`; the parameters to be + updated with the stored moving averages. If `None`, the + parameters with which this `ExponentialMovingAverage` was + initialized will be used. + """ + parameters = self._get_parameters(parameters) + for s_param, param in zip(self.shadow_params, parameters): + param.data.copy_(s_param.data) + + def store(self, parameters: Optional[Iterable[torch.nn.Parameter]] = None) -> None: + """ + Save the current parameters for restoring later. + + Args: + parameters: Iterable of `torch.nn.Parameter`; the parameters to be + temporarily stored. If `None`, the parameters of with which this + `ExponentialMovingAverage` was initialized will be used. + """ + parameters = self._get_parameters(parameters) + self.collected_params = [param.detach().clone() for param in parameters] + + def restore( + self, parameters: Optional[Iterable[torch.nn.Parameter]] = None + ) -> None: + """ + Restore the parameters stored with the `store` method. + Useful to validate the model with EMA parameters without affecting the + original optimization process. Store the parameters before the + `copy_to` method. After validation (or model saving), use this to + restore the former parameters. + + Args: + parameters: Iterable of `torch.nn.Parameter`; the parameters to be + updated with the stored parameters. If `None`, the + parameters with which this `ExponentialMovingAverage` was + initialized will be used. + """ + if self.collected_params is None: + raise RuntimeError( + "This ExponentialMovingAverage has no `store()`ed weights " + "to `restore()`" + ) + parameters = self._get_parameters(parameters) + for c_param, param in zip(self.collected_params, parameters): + param.data.copy_(c_param.data) + + @contextlib.contextmanager + def average_parameters( + self, parameters: Optional[Iterable[torch.nn.Parameter]] = None + ): + r""" + Context manager for validation/inference with averaged parameters. + + Equivalent to: + + ema.store() + ema.copy_to() + try: + ... + finally: + ema.restore() + + Args: + parameters: Iterable of `torch.nn.Parameter`; the parameters to be + updated with the stored parameters. If `None`, the + parameters with which this `ExponentialMovingAverage` was + initialized will be used. + """ + parameters = self._get_parameters(parameters) + self.store(parameters) + self.copy_to(parameters) + try: + yield + finally: + if not self.switch: + self.restore(parameters) + + def to(self, device=None, dtype=None) -> None: + r"""Move internal buffers of the ExponentialMovingAverage to `device`. + + Args: + device: like `device` argument to `torch.Tensor.to` + """ + # .to() on the tensors handles None correctly + self.shadow_params = [ + ( + p.to(device=device, dtype=dtype) + if p.is_floating_point() + else p.to(device=device) + ) + for p in self.shadow_params + ] + if self.collected_params is not None: + self.collected_params = [ + ( + p.to(device=device, dtype=dtype) + if p.is_floating_point() + else p.to(device=device) + ) + for p in self.collected_params + ] + return + + def state_dict(self) -> dict: + r"""Returns the state of the ExponentialMovingAverage as a dict.""" + # Following PyTorch conventions, references to tensors are returned: + # "returns a reference to the state and not its copy!" - + # https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict + return { + "decay": self.decay, + "num_updates": self.num_updates, + "shadow_params": self.shadow_params, + "collected_params": self.collected_params, + } + + def load_state_dict(self, state_dict: dict) -> None: + r"""Loads the ExponentialMovingAverage state. + + Args: + state_dict (dict): EMA state. Should be an object returned + from a call to :meth:`state_dict`. + """ + # deepcopy, to be consistent with module API + state_dict = copy.deepcopy(state_dict) + self.decay = state_dict["decay"] + if self.decay < 0.0 or self.decay > 1.0: + raise ValueError("Decay must be between 0 and 1") + self.num_updates = state_dict["num_updates"] + assert self.num_updates is None or isinstance( + self.num_updates, int + ), "Invalid num_updates" + + self.shadow_params = state_dict["shadow_params"] + assert isinstance(self.shadow_params, list), "shadow_params must be a list" + assert all( + isinstance(p, torch.Tensor) for p in self.shadow_params + ), "shadow_params must all be Tensors" + + self.collected_params = state_dict["collected_params"] + if self.collected_params is not None: + assert isinstance( + self.collected_params, list + ), "collected_params must be a list" + assert all( + isinstance(p, torch.Tensor) for p in self.collected_params + ), "collected_params must all be Tensors" + assert len(self.collected_params) == len( + self.shadow_params + ), "collected_params and shadow_params had different lengths" + + if len(self.shadow_params) == len(self._params_refs): + # Consistant with torch.optim.Optimizer, cast things to consistant + # device and dtype with the parameters + params = [p() for p in self._params_refs] + # If parameters have been garbage collected, just load the state + # we were given without change. + if not any(p is None for p in params): + # ^ parameter references are still good + for i, p in enumerate(params): + self.shadow_params[i] = self.shadow_params[i].to( + device=p.device, dtype=p.dtype + ) + if self.collected_params is not None: + self.collected_params[i] = self.collected_params[i].to( + device=p.device, dtype=p.dtype + ) + else: + raise ValueError( + "Tried to `load_state_dict()` with the wrong number of " + "parameters in the saved state." + ) diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/utils/evaluation_depth.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/utils/evaluation_depth.py new file mode 100644 index 0000000000000000000000000000000000000000..834576031481d6665e10e12db0a7f0fcf415ae8b --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/utils/evaluation_depth.py @@ -0,0 +1,170 @@ +from collections import defaultdict +from functools import partial + +import torch +import torch.nn.functional as F + +from unidepth.utils.chamfer_distance import ChamferDistance + +chamfer_cls = ChamferDistance() + + +def chamfer_dist(tensor1, tensor2): + x_lengths = torch.tensor((tensor1.shape[1],), device=tensor1.device) + y_lengths = torch.tensor((tensor2.shape[1],), device=tensor2.device) + dist1, dist2, idx1, idx2 = chamfer_cls( + tensor1, tensor2, x_lengths=x_lengths, y_lengths=y_lengths + ) + return (torch.sqrt(dist1) + torch.sqrt(dist2)) / 2 + + +def auc(tensor1, tensor2, thresholds): + x_lengths = torch.tensor((tensor1.shape[1],), device=tensor1.device) + y_lengths = torch.tensor((tensor2.shape[1],), device=tensor2.device) + dist1, dist2, idx1, idx2 = chamfer_cls( + tensor1, tensor2, x_lengths=x_lengths, y_lengths=y_lengths + ) + # compute precision recall + precisions = [(dist1 < threshold).sum() / dist1.numel() for threshold in thresholds] + recalls = [(dist2 < threshold).sum() / dist2.numel() for threshold in thresholds] + auc_value = torch.trapz( + torch.tensor(precisions, device=tensor1.device), + torch.tensor(recalls, device=tensor1.device), + ) + return auc_value + + +def delta(tensor1, tensor2, exponent): + inlier = torch.maximum((tensor1 / tensor2), (tensor2 / tensor1)) + return (inlier < 1.25**exponent).to(torch.float32).mean() + + +def tau(tensor1, tensor2, perc): + inlier = torch.maximum((tensor1 / tensor2), (tensor2 / tensor1)) + return (inlier < (1.0 + perc)).to(torch.float32).mean() + + +def ssi(tensor1, tensor2): + stability_mat = 1e-9 * torch.eye(2, device=tensor1.device) + tensor2_one = torch.stack( + [tensor2.detach(), torch.ones_like(tensor2).detach()], dim=1 + ) + scale_shift = torch.inverse(tensor2_one.T @ tensor2_one + stability_mat) @ ( + tensor2_one.T @ tensor1.unsqueeze(1) + ) + scale, shift = scale_shift.squeeze().chunk(2, dim=0) + return tensor2 * scale + shift + + +def si(tensor1, tensor2): + return tensor2 * torch.median(tensor1) / torch.median(tensor2) + + +def arel(tensor1, tensor2): + tensor2 = tensor2 * torch.median(tensor1) / torch.median(tensor2) + return (torch.abs(tensor1 - tensor2) / tensor1).mean() + + +def d_auc(tensor1, tensor2): + exponents = torch.linspace(0.01, 5.0, steps=100, device=tensor1.device) + deltas = [delta(tensor1, tensor2, exponent) for exponent in exponents] + return torch.trapz(torch.tensor(deltas, device=tensor1.device), exponents) / 5.0 + + +def f1_score(tensor1, tensor2, thresholds): + x_lengths = torch.tensor((tensor1.shape[1],), device=tensor1.device) + y_lengths = torch.tensor((tensor2.shape[1],), device=tensor2.device) + dist1, dist2, idx1, idx2 = chamfer_cls( + tensor1, tensor2, x_lengths=x_lengths, y_lengths=y_lengths + ) + # compute precision recall + precisions = [(dist1 < threshold).sum() / dist1.numel() for threshold in thresholds] + recalls = [(dist2 < threshold).sum() / dist2.numel() for threshold in thresholds] + precisions = torch.tensor(precisions, device=tensor1.device) + recalls = torch.tensor(recalls, device=tensor1.device) + f1_thresholds = 2 * precisions * recalls / (precisions + recalls) + f1_thresholds = torch.where( + torch.isnan(f1_thresholds), torch.zeros_like(f1_thresholds), f1_thresholds + ) + f1_value = torch.trapz(f1_thresholds) / len(thresholds) + return f1_value + + +DICT_METRICS = { + "d1": partial(delta, exponent=1.0), + "d2": partial(delta, exponent=2.0), + "d3": partial(delta, exponent=3.0), + "rmse": lambda gt, pred: torch.sqrt(((gt - pred) ** 2).mean()), + "rmselog": lambda gt, pred: torch.sqrt( + ((torch.log(gt) - torch.log(pred)) ** 2).mean() + ), + "arel": lambda gt, pred: (torch.abs(gt - pred) / gt).mean(), + "sqrel": lambda gt, pred: (((gt - pred) ** 2) / gt).mean(), + "log10": lambda gt, pred: torch.abs(torch.log10(pred) - torch.log10(gt)).mean(), + "silog": lambda gt, pred: 100 * torch.std(torch.log(pred) - torch.log(gt)).mean(), + "medianlog": lambda gt, pred: 100 + * (torch.log(pred) - torch.log(gt)).median().abs(), + "d_auc": d_auc, + "tau": partial(tau, perc=0.03), +} + + +DICT_METRICS_3D = { + "MSE_3d": lambda gt, pred, thresholds: torch.norm(gt - pred, dim=0, p=2), + "chamfer": lambda gt, pred, thresholds: chamfer_dist( + gt.unsqueeze(0).permute(0, 2, 1), pred.unsqueeze(0).permute(0, 2, 1) + ), + "F1": lambda gt, pred, thresholds: f1_score( + gt.unsqueeze(0).permute(0, 2, 1), + pred.unsqueeze(0).permute(0, 2, 1), + thresholds=thresholds, + ), +} + +DICT_METRICS_D = { + "a1": lambda gt, pred: (torch.maximum((gt / pred), (pred / gt)) > 1.25**1.0).to( + torch.float32 + ), + "abs_rel": lambda gt, pred: (torch.abs(gt - pred) / gt), +} + + +def eval_depth( + gts: torch.Tensor, preds: torch.Tensor, masks: torch.Tensor, max_depth=None +): + summary_metrics = defaultdict(list) + preds = F.interpolate(preds, gts.shape[-2:], mode="bilinear") + for i, (gt, pred, mask) in enumerate(zip(gts, preds, masks)): + if max_depth is not None: + mask = mask & (gt <= max_depth) + for name, fn in DICT_METRICS.items(): + if name in ["tau", "d1", "arel"]: + for rescale_fn in ["ssi", "si"]: + summary_metrics[f"{name}_{rescale_fn}"].append( + fn(gt[mask], eval(rescale_fn)(gt[mask], pred[mask])) + ) + summary_metrics[name].append(fn(gt[mask], pred[mask]).mean()) + return {name: torch.stack(vals, dim=0) for name, vals in summary_metrics.items()} + + +def eval_3d( + gts: torch.Tensor, preds: torch.Tensor, masks: torch.Tensor, thresholds=None +): + summary_metrics = defaultdict(list) + ratio = min( + 1.0, (240 * 320 / masks.sum()) ** 0.5 + ) # rescale to avoid OOM during eval, FIXME + h_max, w_max = int(gts.shape[-2] * ratio), int(gts.shape[-1] * ratio) + gts = F.interpolate(gts, size=(h_max, w_max), mode="nearest-exact") + preds = F.interpolate(preds, size=(h_max, w_max), mode="nearest-exact") + masks = F.interpolate( + masks.float(), size=(h_max, w_max), mode="nearest-exact" + ).bool() + for i, (gt, pred, mask) in enumerate(zip(gts, preds, masks)): + if not torch.any(mask): + continue + for name, fn in DICT_METRICS_3D.items(): + summary_metrics[name].append( + fn(gt[:, mask.squeeze()], pred[:, mask.squeeze()], thresholds).mean() + ) + return {name: torch.stack(vals, dim=0) for name, vals in summary_metrics.items()} diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/utils/geometric.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/utils/geometric.py new file mode 100644 index 0000000000000000000000000000000000000000..e16fbe365df221571f5121e2cb15801da2957b30 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/utils/geometric.py @@ -0,0 +1,302 @@ +""" +Author: Luigi Piccinelli +Licensed under the CC-BY NC 4.0 license (http://creativecommons.org/licenses/by-nc/4.0/) +""" + +from typing import Tuple + +import torch +from torch.nn import functional as F + + +@torch.jit.script +def generate_rays( + camera_intrinsics: torch.Tensor, image_shape: Tuple[int, int], noisy: bool = False +): + batch_size, device, dtype = ( + camera_intrinsics.shape[0], + camera_intrinsics.device, + camera_intrinsics.dtype, + ) + height, width = image_shape + # Generate grid of pixel coordinates + pixel_coords_x = torch.linspace(0, width - 1, width, device=device, dtype=dtype) + pixel_coords_y = torch.linspace(0, height - 1, height, device=device, dtype=dtype) + if noisy: + pixel_coords_x += torch.rand_like(pixel_coords_x) - 0.5 + pixel_coords_y += torch.rand_like(pixel_coords_y) - 0.5 + pixel_coords = torch.stack( + [pixel_coords_x.repeat(height, 1), pixel_coords_y.repeat(width, 1).t()], dim=2 + ) # (H, W, 2) + pixel_coords = pixel_coords + 0.5 + + # Calculate ray directions + intrinsics_inv = torch.eye(3, device=device).unsqueeze(0).repeat(batch_size, 1, 1) + intrinsics_inv[:, 0, 0] = 1.0 / camera_intrinsics[:, 0, 0] + intrinsics_inv[:, 1, 1] = 1.0 / camera_intrinsics[:, 1, 1] + intrinsics_inv[:, 0, 2] = -camera_intrinsics[:, 0, 2] / camera_intrinsics[:, 0, 0] + intrinsics_inv[:, 1, 2] = -camera_intrinsics[:, 1, 2] / camera_intrinsics[:, 1, 1] + homogeneous_coords = torch.cat( + [pixel_coords, torch.ones_like(pixel_coords[:, :, :1])], dim=2 + ) # (H, W, 3) + ray_directions = torch.matmul( + intrinsics_inv, homogeneous_coords.permute(2, 0, 1).flatten(1) + ) # (3, H*W) + ray_directions = F.normalize(ray_directions, dim=1) # (B, 3, H*W) + ray_directions = ray_directions.permute(0, 2, 1) # (B, H*W, 3) + + theta = torch.atan2(ray_directions[..., 0], ray_directions[..., -1]) + phi = torch.acos(ray_directions[..., 1]) + # pitch = torch.asin(ray_directions[..., 1]) + # roll = torch.atan2(ray_directions[..., 0], - ray_directions[..., 1]) + angles = torch.stack([theta, phi], dim=-1) + return ray_directions, angles + + +@torch.jit.script +def spherical_zbuffer_to_euclidean(spherical_tensor: torch.Tensor) -> torch.Tensor: + theta = spherical_tensor[..., 0] # Extract polar angle + phi = spherical_tensor[..., 1] # Extract azimuthal angle + z = spherical_tensor[..., 2] # Extract zbuffer depth + + # y = r * cos(phi) + # x = r * sin(phi) * sin(theta) + # z = r * sin(phi) * cos(theta) + # => + # r = z / sin(phi) / cos(theta) + # y = z / (sin(phi) / cos(phi)) / cos(theta) + # x = z * sin(theta) / cos(theta) + x = z * torch.tan(theta) + y = z / torch.tan(phi) / torch.cos(theta) + + euclidean_tensor = torch.stack((x, y, z), dim=-1) + return euclidean_tensor + + +@torch.jit.script +def spherical_to_euclidean(spherical_tensor: torch.Tensor) -> torch.Tensor: + theta = spherical_tensor[..., 0] # Extract polar angle + phi = spherical_tensor[..., 1] # Extract azimuthal angle + r = spherical_tensor[..., 2] # Extract radius + # y = r * cos(phi) + # x = r * sin(phi) * sin(theta) + # z = r * sin(phi) * cos(theta) + x = r * torch.sin(phi) * torch.sin(theta) + y = r * torch.cos(phi) + z = r * torch.cos(theta) * torch.sin(phi) + + euclidean_tensor = torch.stack((x, y, z), dim=-1) + return euclidean_tensor + + +@torch.jit.script +def euclidean_to_spherical(spherical_tensor: torch.Tensor) -> torch.Tensor: + x = spherical_tensor[..., 0] # Extract polar angle + y = spherical_tensor[..., 1] # Extract azimuthal angle + z = spherical_tensor[..., 2] # Extract radius + # y = r * cos(phi) + # x = r * sin(phi) * sin(theta) + # z = r * sin(phi) * cos(theta) + r = torch.sqrt(x**2 + y**2 + z**2) + theta = torch.atan2(x / r, z / r) + phi = torch.acos(y / r) + + euclidean_tensor = torch.stack((theta, phi, r), dim=-1) + return euclidean_tensor + + +@torch.jit.script +def euclidean_to_spherical_zbuffer(euclidean_tensor: torch.Tensor) -> torch.Tensor: + pitch = torch.asin(euclidean_tensor[..., 1]) + yaw = torch.atan2(euclidean_tensor[..., 0], euclidean_tensor[..., -1]) + z = euclidean_tensor[..., 2] # Extract zbuffer depth + euclidean_tensor = torch.stack((pitch, yaw, z), dim=-1) + return euclidean_tensor + + +@torch.jit.script +def unproject_points( + depth: torch.Tensor, camera_intrinsics: torch.Tensor +) -> torch.Tensor: + """ + Unprojects a batch of depth maps to 3D point clouds using camera intrinsics. + + Args: + depth (torch.Tensor): Batch of depth maps of shape (B, 1, H, W). + camera_intrinsics (torch.Tensor): Camera intrinsic matrix of shape (B, 3, 3). + + Returns: + torch.Tensor: Batch of 3D point clouds of shape (B, 3, H, W). + """ + batch_size, _, height, width = depth.shape + device = depth.device + + # Create pixel grid + y_coords, x_coords = torch.meshgrid( + torch.arange(height, device=device), + torch.arange(width, device=device), + indexing="ij", + ) + pixel_coords = torch.stack((x_coords, y_coords), dim=-1) # (H, W, 2) + + # Get homogeneous coords (u v 1) + pixel_coords_homogeneous = torch.cat( + (pixel_coords, torch.ones((height, width, 1), device=device)), dim=-1 + ) + pixel_coords_homogeneous = pixel_coords_homogeneous.permute(2, 0, 1).flatten( + 1 + ) # (3, H*W) + # Apply K^-1 @ (u v 1): [B, 3, 3] @ [3, H*W] -> [B, 3, H*W] + unprojected_points = torch.matmul( + torch.inverse(camera_intrinsics), pixel_coords_homogeneous + ) # (B, 3, H*W) + unprojected_points = unprojected_points.view( + batch_size, 3, height, width + ) # (B, 3, H, W) + unprojected_points = unprojected_points * depth # (B, 3, H, W) + return unprojected_points + + +@torch.jit.script +def project_points( + points_3d: torch.Tensor, + intrinsic_matrix: torch.Tensor, + image_shape: Tuple[int, int], +) -> torch.Tensor: + # Project 3D points onto the image plane via intrinsics (u v w) = (x y z) @ K^T + points_2d = torch.matmul(points_3d, intrinsic_matrix.transpose(1, 2)) + + # Normalize projected points: (u v w) -> (u / w, v / w, 1) + points_2d = points_2d[..., :2] / points_2d[..., 2:] + + points_2d = points_2d.int() + + # points need to be inside the image (can it diverge onto all points out???) + valid_mask = ( + (points_2d[..., 0] >= 0) + & (points_2d[..., 0] < image_shape[1]) + & (points_2d[..., 1] >= 0) + & (points_2d[..., 1] < image_shape[0]) + ) + + # Calculate the flat indices of the valid pixels + flat_points_2d = points_2d[..., 0] + points_2d[..., 1] * image_shape[1] + flat_indices = flat_points_2d.long() + + # Create depth maps and counts using scatter_add, (B, H, W) + depth_maps = torch.zeros( + [points_3d.shape[0], *image_shape], device=points_3d.device + ) + counts = torch.zeros([points_3d.shape[0], *image_shape], device=points_3d.device) + + # Loop over batches to apply masks and accumulate depth/count values + for i in range(points_3d.shape[0]): + valid_indices = flat_indices[i, valid_mask[i]] + depth_maps[i].view(-1).scatter_add_( + 0, valid_indices, points_3d[i, valid_mask[i], 2] + ) + counts[i].view(-1).scatter_add_( + 0, valid_indices, torch.ones_like(points_3d[i, valid_mask[i], 2]) + ) + + # Calculate mean depth for each pixel in each batch + mean_depth_maps = depth_maps / counts.clamp(min=1.0) + return mean_depth_maps.reshape(-1, 1, *image_shape) # (B, 1, H, W) + + +@torch.jit.script +def downsample(data: torch.Tensor, downsample_factor: int = 2): + N, _, H, W = data.shape + data = data.view( + N, + H // downsample_factor, + downsample_factor, + W // downsample_factor, + downsample_factor, + 1, + ) + data = data.permute(0, 1, 3, 5, 2, 4).contiguous() + data = data.view(-1, downsample_factor * downsample_factor) + data_tmp = torch.where(data == 0.0, 1e5 * torch.ones_like(data), data) + data = torch.min(data_tmp, dim=-1).values + data = data.view(N, 1, H // downsample_factor, W // downsample_factor) + data = torch.where(data > 1000, torch.zeros_like(data), data) + return data + + +@torch.jit.script +def flat_interpolate( + flat_tensor: torch.Tensor, + old: Tuple[int, int], + new: Tuple[int, int], + antialias: bool = True, + mode: str = "bilinear", +) -> torch.Tensor: + if old[0] == new[0] and old[1] == new[1]: + return flat_tensor + tensor = flat_tensor.view(flat_tensor.shape[0], old[0], old[1], -1).permute( + 0, 3, 1, 2 + ) # b c h w + tensor_interp = F.interpolate( + tensor, + size=(new[0], new[1]), + mode=mode, + align_corners=False, + antialias=antialias, + ) + flat_tensor_interp = tensor_interp.view( + flat_tensor.shape[0], -1, new[0] * new[1] + ).permute( + 0, 2, 1 + ) # b (h w) c + return flat_tensor_interp.contiguous() + + +@torch.jit.script +def dilate(image, kernel_size: int | tuple[int, int]): + if isinstance(kernel_size, int): + kernel_size = (kernel_size, kernel_size) + device, dtype = image.device, image.dtype + padding = (kernel_size[0] // 2, kernel_size[1] // 2) + kernel = torch.ones((1, 1, *kernel_size), dtype=torch.float32, device=image.device) + dilated_image = F.conv2d(image.float(), kernel, padding=padding, stride=1) + dilated_image = torch.where( + dilated_image > 0, + torch.tensor(1.0, device=device), + torch.tensor(0.0, device=device), + ) + return dilated_image.to(dtype) + + +@torch.jit.script +def erode(image, kernel_size: int | tuple[int, int]): + if isinstance(kernel_size, int): + kernel_size = (kernel_size, kernel_size) + device, dtype = image.device, image.dtype + padding = (kernel_size[0] // 2, kernel_size[1] // 2) + kernel = torch.ones((1, 1, *kernel_size), dtype=torch.float32, device=image.device) + eroded_image = F.conv2d(image.float(), kernel, padding=padding, stride=1) + eroded_image = torch.where( + eroded_image == (kernel_size[0] * kernel_size[1]), + torch.tensor(1.0, device=device), + torch.tensor(0.0, device=device), + ) + return eroded_image.to(dtype) + + +@torch.jit.script +def iou(mask1: torch.Tensor, mask2: torch.Tensor) -> torch.Tensor: + device = mask1.device + + # Ensure the masks are binary (0 or 1) + mask1 = mask1.to(torch.bool) + mask2 = mask2.to(torch.bool) + + # Compute intersection and union + intersection = torch.sum(mask1 & mask2).to(torch.float32) + union = torch.sum(mask1 | mask2).to(torch.float32) + + # Compute IoU + iou = intersection / union.clip(min=1.0) + + return iou diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/utils/misc.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/utils/misc.py new file mode 100644 index 0000000000000000000000000000000000000000..7346e52e358ddae209ba830eb00dc281aae7ff0f --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/utils/misc.py @@ -0,0 +1,690 @@ +""" +Author: Luigi Piccinelli +Licensed under the CC-BY NC 4.0 license (http://creativecommons.org/licenses/by-nc/4.0/) +""" + +from functools import wraps +from time import time + +import numpy as np +import torch +import torch.nn as nn +import torch.nn.functional as F +from einops import rearrange, reduce, repeat +from scipy import interpolate + + +@torch.jit.script +def max_stack(tensors: list[torch.Tensor]) -> torch.Tensor: + if len(tensors) == 1: + return tensors[0] + return torch.stack(tensors, dim=-1).max(dim=-1).values + + +def last_stack(tensors: list[torch.Tensor]) -> torch.Tensor: + return tensors[-1] + + +def first_stack(tensors: list[torch.Tensor]) -> torch.Tensor: + return tensors[0] + + +@torch.jit.script +def softmax_stack( + tensors: list[torch.Tensor], temperature: float = 1.0 +) -> torch.Tensor: + if len(tensors) == 1: + return tensors[0] + return F.softmax(torch.stack(tensors, dim=-1) / temperature, dim=-1).sum(dim=-1) + + +@torch.jit.script +def mean_stack(tensors: list[torch.Tensor]) -> torch.Tensor: + if len(tensors) == 1: + return tensors[0] + return torch.stack(tensors, dim=-1).mean(dim=-1) + + +@torch.jit.script +def sum_stack(tensors: list[torch.Tensor]) -> torch.Tensor: + if len(tensors) == 1: + return tensors[0] + return torch.stack(tensors, dim=-1).sum(dim=-1) + + +def convert_module_to_f16(l): + """ + Convert primitive modules to float16. + """ + if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Conv3d)): + l.weight.data = l.weight.data.half() + if l.bias is not None: + l.bias.data = l.bias.data.half() + + +def convert_module_to_f32(l): + """ + Convert primitive modules to float32, undoing convert_module_to_f16(). + """ + if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Conv3d)): + l.weight.data = l.weight.data.float() + if l.bias is not None: + l.bias.data = l.bias.data.float() + + +def format_seconds(seconds): + minutes, seconds = divmod(seconds, 60) + hours, minutes = divmod(minutes, 60) + return f"{hours:d}:{minutes:02d}:{seconds:02d}" + + +def get_params(module, lr, wd): + skip_list = {} + skip_keywords = {} + if hasattr(module, "no_weight_decay"): + skip_list = module.no_weight_decay() + if hasattr(module, "no_weight_decay_keywords"): + skip_keywords = module.no_weight_decay_keywords() + has_decay = [] + no_decay = [] + for name, param in module.named_parameters(): + if not param.requires_grad: + continue # frozen weights + if ( + (name in skip_list) + or any((kw in name for kw in skip_keywords)) + or len(param.shape) == 1 + or name.endswith(".gamma") + or name.endswith(".beta") + or name.endswith(".bias") + ): + # if (name in skip_list) or any((kw in name for kw in skip_keywords)) or len(param.shape) == 1: + no_decay.append(param) + else: + has_decay.append(param) + + group1 = { + "params": has_decay, + "weight_decay": wd, + "lr": lr, + "weight_decay_init": wd, + "weight_decay_base": wd, + # "lr_init": lr, + "lr_base": lr, + } + group2 = { + "params": no_decay, + "weight_decay": 0.0, + "lr": lr, + "weight_decay_init": 0.0, + "weight_decay_base": 0.0, + "weight_decay_final": 0.0, + # "lr_init": lr, + "lr_base": lr, + } + return [group1, group2], [lr, lr] + + +def get_num_layer_for_swin(var_name, num_max_layer, layers_per_stage): + if var_name in ("cls_token", "mask_token", "pos_embed", "absolute_pos_embed"): + return 0 + elif var_name.startswith("patch_embed"): + return 0 + elif var_name.startswith("layers"): + if var_name.split(".")[2] == "blocks": + stage_id = int(var_name.split(".")[1]) + layer_id = int(var_name.split(".")[3]) + sum(layers_per_stage[:stage_id]) + return layer_id + 1 + elif var_name.split(".")[2] == "downsample": + stage_id = int(var_name.split(".")[1]) + layer_id = sum(layers_per_stage[: stage_id + 1]) + return layer_id + else: + return num_max_layer - 1 + + +def get_params_layerdecayswin(module, lr, wd, ld): + skip_list = {} + skip_keywords = {} + if hasattr(module, "no_weight_decay"): + skip_list = module.no_weight_decay() + if hasattr(module, "no_weight_decay_keywords"): + skip_keywords = module.no_weight_decay_keywords() + layers_per_stage = module.depths + num_layers = sum(layers_per_stage) + 1 + lrs = [] + params = [] + for name, param in module.named_parameters(): + if not param.requires_grad: + print(f"{name} frozen") + continue # frozen weights + layer_id = get_num_layer_for_swin(name, num_layers, layers_per_stage) + lr_cur = lr * ld ** (num_layers - layer_id - 1) + # if (name in skip_list) or any((kw in name for kw in skip_keywords)) or len(param.shape) == 1 or name.endswith(".bias"): + if (name in skip_list) or any((kw in name for kw in skip_keywords)): + wd_cur = 0.0 + else: + wd_cur = wd + params.append({"params": param, "weight_decay": wd_cur, "lr": lr_cur}) + lrs.append(lr_cur) + return params, lrs + + +def log(t, eps: float = 1e-5): + return torch.log(t.clamp(min=eps)) + + +def l2norm(t): + return F.normalize(t, dim=-1) + + +def exists(val): + return val is not None + + +def identity(t, *args, **kwargs): + return t + + +def divisible_by(numer, denom): + return (numer % denom) == 0 + + +def first(arr, d=None): + if len(arr) == 0: + return d + return arr[0] + + +def default(val, d): + if exists(val): + return val + return d() if callable(d) else d + + +def maybe(fn): + @wraps(fn) + def inner(x): + if not exists(x): + return x + return fn(x) + + return inner + + +def once(fn): + called = False + + @wraps(fn) + def inner(x): + nonlocal called + if called: + return + called = True + return fn(x) + + return inner + + +def _many(fn): + @wraps(fn) + def inner(tensors, pattern, **kwargs): + return (fn(tensor, pattern, **kwargs) for tensor in tensors) + + return inner + + +rearrange_many = _many(rearrange) +repeat_many = _many(repeat) +reduce_many = _many(reduce) + + +def load_pretrained(state_dict, checkpoint): + checkpoint_model = checkpoint["model"] + if any([True if "encoder." in k else False for k in checkpoint_model.keys()]): + checkpoint_model = { + k.replace("encoder.", ""): v + for k, v in checkpoint_model.items() + if k.startswith("encoder.") + } + print("Detect pre-trained model, remove [encoder.] prefix.") + else: + print("Detect non-pre-trained model, pass without doing anything.") + print(f">>>>>>>>>> Remapping pre-trained keys for SWIN ..........") + checkpoint = load_checkpoint_swin(state_dict, checkpoint_model) + + +def load_checkpoint_swin(model, checkpoint_model): + state_dict = model.state_dict() + # Geometric interpolation when pre-trained patch size mismatch with fine-tuned patch size + all_keys = list(checkpoint_model.keys()) + for key in all_keys: + if "relative_position_bias_table" in key: + relative_position_bias_table_pretrained = checkpoint_model[key] + relative_position_bias_table_current = state_dict[key] + L1, nH1 = relative_position_bias_table_pretrained.size() + L2, nH2 = relative_position_bias_table_current.size() + if nH1 != nH2: + print(f"Error in loading {key}, passing......") + else: + if L1 != L2: + print(f"{key}: Interpolate relative_position_bias_table using geo.") + src_size = int(L1**0.5) + dst_size = int(L2**0.5) + + def geometric_progression(a, r, n): + return a * (1.0 - r**n) / (1.0 - r) + + left, right = 1.01, 1.5 + while right - left > 1e-6: + q = (left + right) / 2.0 + gp = geometric_progression(1, q, src_size // 2) + if gp > dst_size // 2: + right = q + else: + left = q + + # if q > 1.090307: + # q = 1.090307 + + dis = [] + cur = 1 + for i in range(src_size // 2): + dis.append(cur) + cur += q ** (i + 1) + + r_ids = [-_ for _ in reversed(dis)] + + x = r_ids + [0] + dis + y = r_ids + [0] + dis + + t = dst_size // 2.0 + dx = np.arange(-t, t + 0.1, 1.0) + dy = np.arange(-t, t + 0.1, 1.0) + + print("Original positions = %s" % str(x)) + print("Target positions = %s" % str(dx)) + + all_rel_pos_bias = [] + + for i in range(nH1): + z = ( + relative_position_bias_table_pretrained[:, i] + .view(src_size, src_size) + .float() + .numpy() + ) + f_cubic = interpolate.interp2d(x, y, z, kind="cubic") + all_rel_pos_bias.append( + torch.Tensor(f_cubic(dx, dy)) + .contiguous() + .view(-1, 1) + .to(relative_position_bias_table_pretrained.device) + ) + + new_rel_pos_bias = torch.cat(all_rel_pos_bias, dim=-1) + checkpoint_model[key] = new_rel_pos_bias + + # delete relative_position_index since we always re-init it + relative_position_index_keys = [ + k for k in checkpoint_model.keys() if "relative_position_index" in k + ] + for k in relative_position_index_keys: + del checkpoint_model[k] + + # delete relative_coords_table since we always re-init it + relative_coords_table_keys = [ + k for k in checkpoint_model.keys() if "relative_coords_table" in k + ] + for k in relative_coords_table_keys: + del checkpoint_model[k] + + # # re-map keys due to name change + rpe_mlp_keys = [k for k in checkpoint_model.keys() if "cpb_mlp" in k] + for k in rpe_mlp_keys: + checkpoint_model[k.replace("cpb_mlp", "rpe_mlp")] = checkpoint_model.pop(k) + + # delete attn_mask since we always re-init it + attn_mask_keys = [k for k in checkpoint_model.keys() if "attn_mask" in k] + for k in attn_mask_keys: + del checkpoint_model[k] + + encoder_keys = [k for k in checkpoint_model.keys() if k.startswith("encoder.")] + for k in encoder_keys: + checkpoint_model[k.replace("encoder.", "")] = checkpoint_model.pop(k) + + return checkpoint_model + + +def add_padding_metas(out, image_metas): + device = out.device + # left, right, top, bottom + paddings = [img_meta.get("paddings", [0] * 4) for img_meta in image_metas] + paddings = torch.stack(paddings).to(device) + outs = [F.pad(o, padding, value=0.0) for padding, o in zip(paddings, out)] + return torch.stack(outs) + + +# left, right, top, bottom +def remove_padding(out, paddings): + H, W = out.shape[-2:] + outs = [ + o[..., padding[2] : H - padding[3], padding[0] : W - padding[1]] + for padding, o in zip(paddings, out) + ] + return torch.stack(outs) + + +def remove_padding_metas(out, image_metas): + B, C, H, W = out.shape + device = out.device + # left, right, top, bottom + paddings = [ + torch.tensor(img_meta.get("paddings", [0] * 4)) for img_meta in image_metas + ] + return remove_padding(out, paddings) + + +def ssi_helper(tensor1, tensor2): + stability_mat = 1e-4 * torch.eye(2, device=tensor1.device) + tensor2_one = torch.stack([tensor2, torch.ones_like(tensor2)], dim=1) + scale_shift = torch.inverse(tensor2_one.T @ tensor2_one + stability_mat) @ ( + tensor2_one.T @ tensor1.unsqueeze(1) + ) + scale, shift = scale_shift.squeeze().chunk(2, dim=0) + return scale, shift + + +def calculate_mean_values(names, values): + # Create a defaultdict to store sum and count for each name + name_values = {name: {} for name in names} + + # Iterate through the lists and accumulate values for each name + for name, value in zip(names, values): + name_values[name]["sum"] = name_values[name].get("sum", 0.0) + value + name_values[name]["count"] = name_values[name].get("count", 0.0) + 1 + + # Calculate mean values and create the output dictionary + output_dict = { + name: name_values[name]["sum"] / name_values[name]["count"] + for name in name_values + } + + return output_dict + + +def remove_leading_dim(infos): + if isinstance(infos, dict): + return {k: remove_leading_dim(v) for k, v in infos.items()} + elif isinstance(infos, torch.Tensor): + return infos.squeeze(0) + else: + return infos + + +def recursive_index(infos, index): + if isinstance(infos, dict): + return {k: recursive_index(v, index) for k, v in infos.items()} + elif isinstance(infos, torch.Tensor): + return infos[index] + else: + return infos + + +def to_cpu(infos): + if isinstance(infos, dict): + return {k: to_cpu(v) for k, v in infos.items()} + elif isinstance(infos, torch.Tensor): + return infos.detach() + else: + return infos + + +def recursive_to(infos, device, non_blocking, cls): + if isinstance(infos, dict): + return {k: recursive_to(v, device, non_blocking, cls) for k, v in infos.items()} + elif isinstance(infos, list): + return [recursive_to(v, device, non_blocking, cls) for v in infos] + elif isinstance(infos, cls): + return infos.to(device, non_blocking=non_blocking) + else: + return infos + + +def masked_mean( + data: torch.Tensor, + mask: torch.Tensor | None = None, + dim: list[int] | None = None, + keepdim: bool = False, +) -> torch.Tensor: + dim = dim if dim is not None else list(range(data.dim())) + if mask is None: + return data.mean(dim=dim, keepdim=keepdim) + mask = mask.float() + mask_sum = torch.sum(mask, dim=dim, keepdim=True) + mask_mean = torch.sum(data * mask, dim=dim, keepdim=True) / torch.clamp( + mask_sum, min=1.0 + ) + return mask_mean.squeeze(dim) if not keepdim else mask_mean + + +class ProfileMethod: + def __init__(self, model, func_name, track_statistics=True, verbose=False): + self.model = model + self.func_name = func_name + self.verbose = verbose + self.track_statistics = track_statistics + self.timings = [] + + def __enter__(self): + # Start timing + if self.verbose: + if torch.cuda.is_available(): + torch.cuda.synchronize() + self.start_time = time() + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + if self.verbose: + if torch.cuda.is_available(): + torch.cuda.synchronize() + + self.end_time = time() + + elapsed_time = self.end_time - self.start_time + + self.timings.append(elapsed_time) + if self.track_statistics and len(self.timings) > 25: + + # Compute statistics if tracking + timings_array = np.array(self.timings) + mean_time = np.mean(timings_array) + std_time = np.std(timings_array) + quantiles = np.percentile(timings_array, [0, 25, 50, 75, 100]) + print( + f"{self.model.__class__.__name__}.{self.func_name} took {elapsed_time:.4f} seconds" + ) + print(f"Mean Time: {mean_time:.4f} seconds") + print(f"Std Time: {std_time:.4f} seconds") + print( + f"Quantiles: Min={quantiles[0]:.4f}, 25%={quantiles[1]:.4f}, Median={quantiles[2]:.4f}, 75%={quantiles[3]:.4f}, Max={quantiles[4]:.4f}" + ) + + else: + print( + f"{self.model.__class__.__name__}.{self.func_name} took {elapsed_time:.4f} seconds" + ) + + +def profile_method(track_statistics=True, verbose=False): + def decorator(func): + @wraps(func) + def wrapper(self, *args, **kwargs): + with ProfileMethod(self, func.__name__, track_statistics, verbose): + return func(self, *args, **kwargs) + + return wrapper + + return decorator + + +class ProfileFunction: + def __init__(self, func_name, track_statistics=True, verbose=False): + self.func_name = func_name + self.verbose = verbose + self.track_statistics = track_statistics + self.timings = [] + + def __enter__(self): + # Start timing + if self.verbose: + if torch.cuda.is_available(): + torch.cuda.synchronize() + self.start_time = time() + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + if self.verbose: + if torch.cuda.is_available(): + torch.cuda.synchronize() + + self.end_time = time() + + elapsed_time = self.end_time - self.start_time + + self.timings.append(elapsed_time) + if self.track_statistics and len(self.timings) > 25: + + # Compute statistics if tracking + timings_array = np.array(self.timings) + mean_time = np.mean(timings_array) + std_time = np.std(timings_array) + quantiles = np.percentile(timings_array, [0, 25, 50, 75, 100]) + print(f"{self.func_name} took {elapsed_time:.4f} seconds") + print(f"Mean Time: {mean_time:.4f} seconds") + print(f"Std Time: {std_time:.4f} seconds") + print( + f"Quantiles: Min={quantiles[0]:.4f}, 25%={quantiles[1]:.4f}, Median={quantiles[2]:.4f}, 75%={quantiles[3]:.4f}, Max={quantiles[4]:.4f}" + ) + + else: + print(f"{self.func_name} took {elapsed_time:.4f} seconds") + + +def profile_function(track_statistics=True, verbose=False): + def decorator(func): + @wraps(func) + def wrapper(self, *args, **kwargs): + with ProfileFunction(func.__name__, track_statistics, verbose): + return func(self, *args, **kwargs) + + return wrapper + + return decorator + + +def squeeze_list(nested_list, dim, current_dim=0): + # If the current dimension is in the list of indices to squeeze + if isinstance(nested_list, list) and len(nested_list) == 1 and current_dim == dim: + return squeeze_list(nested_list[0], dim, current_dim + 1) + elif isinstance(nested_list, list): + return [squeeze_list(item, dim, current_dim + 1) for item in nested_list] + else: + return nested_list + + +def match_gt(tensor1, tensor2, padding1, padding2, mode: str = "bilinear"): + """ + Transform each item in tensor1 batch to match tensor2's dimensions and padding. + + Args: + tensor1 (torch.Tensor): The input tensor to transform, with shape (batch_size, channels, height, width). + tensor2 (torch.Tensor): The target tensor to match, with shape (batch_size, channels, height, width). + padding1 (tuple): Padding applied to tensor1 (pad_left, pad_right, pad_top, pad_bottom). + padding2 (tuple): Desired padding to be applied to match tensor2 (pad_left, pad_right, pad_top, pad_bottom). + + Returns: + torch.Tensor: The batch of transformed tensors matching tensor2's size and padding. + """ + # Get batch size + batch_size = len(tensor1) + src_dtype = tensor1[0].dtype + tgt_dtype = tensor2[0].dtype + + # List to store transformed tensors + transformed_tensors = [] + + for i in range(batch_size): + item1 = tensor1[i] + item2 = tensor2[i] + + h1, w1 = item1.shape[1], item1.shape[2] + pad1_l, pad1_r, pad1_t, pad1_b = ( + padding1[i] if padding1 is not None else (0, 0, 0, 0) + ) + pad2_l, pad2_r, pad2_t, pad2_b = ( + padding2[i] if padding2 is not None else (0, 0, 0, 0) + ) + item1_unpadded = item1[:, pad1_t : h1 - pad1_b, pad1_l : w1 - pad1_r] + + h2, w2 = ( + item2.shape[1] - pad2_t - pad2_b, + item2.shape[2] - pad2_l - pad2_r, + ) + + item1_resized = F.interpolate( + item1_unpadded.unsqueeze(0).to(tgt_dtype), size=(h2, w2), mode=mode + ) + item1_padded = F.pad(item1_resized, (pad2_l, pad2_r, pad2_t, pad2_b)) + transformed_tensors.append(item1_padded) + + transformed_batch = torch.cat(transformed_tensors) + return transformed_batch.to(src_dtype) + + +def match_intrinsics(K1, tensor1, tensor2, padding1, padding2): + """ + Adjust camera intrinsics K1 to match the size and padding transformation applied to tensor1 + so that it corresponds correctly to tensor2. + + Args: + K1 (torch.Tensor): The camera intrinsics matrix for tensor1, shape (batch_size, 3, 3). + tensor1 (torch.Tensor): The original image tensor, shape (batch_size, C, H1, W1). + tensor2 (torch.Tensor): The target image tensor, shape (batch_size, C, H2, W2). + padding1 (list of tuples): List of padding applied to tensor1 (pad_left, pad_right, pad_top, pad_bottom). + padding2 (list of tuples): Desired padding to be applied to match tensor2 (pad_left, pad_right, pad_top, pad_bottom). + + Returns: + torch.Tensor: The adjusted intrinsics matrix of shape (batch_size, 3, 3). + """ + batch_size = K1.shape[0] + K1_new = K1.clone() + + for i in range(batch_size): + h1, w1 = tensor1.shape[2], tensor1.shape[3] + h2, w2 = tensor2.shape[2], tensor2.shape[3] + + # Remove original padding + pad1_l, pad1_r, pad1_t, pad1_b = ( + padding1[i] if padding1 is not None else (0, 0, 0, 0) + ) + w1_unpadded, h1_unpadded = w1 - (pad1_l + pad1_r), h1 - (pad1_t + pad1_b) + + # Compute new image size after removing original padding + pad2_l, pad2_r, pad2_t, pad2_b = ( + padding2[i] if padding2 is not None else (0, 0, 0, 0) + ) + w2_unpadded, h2_unpadded = w2 - (pad2_l + pad2_r), h2 - (pad2_t + pad2_b) + + # Compute scaling factors + scale_x = w2_unpadded / w1_unpadded + scale_y = h2_unpadded / h1_unpadded + + # Update focal length (fx, fy) and principal point (cx, cy) + K1_new[i, 0, 0] *= scale_x # fx + K1_new[i, 1, 1] *= scale_y # fy + + K1_new[i, 0, 2] = (K1[i, 0, 2] - pad1_l) * scale_x + pad2_l # cx + K1_new[i, 1, 2] = (K1[i, 1, 2] - pad1_t) * scale_y + pad2_t # cy + + return K1_new diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/utils/positional_embedding.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/utils/positional_embedding.py new file mode 100644 index 0000000000000000000000000000000000000000..63872de03f672d988f5e7bdec04102d380ce2c08 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/utils/positional_embedding.py @@ -0,0 +1,273 @@ +""" +Author: Luigi Piccinelli +Licensed under the CC-BY NC 4.0 license (http://creativecommons.org/licenses/by-nc/4.0/) +""" + +from math import pi +from typing import Optional + +import torch +import torch.nn as nn +from einops import rearrange, repeat + + +class PositionEmbeddingSine(nn.Module): + def __init__( + self, num_pos_feats=64, temperature=10000, normalize=False, scale=None + ): + super().__init__() + self.num_pos_feats = num_pos_feats + self.temperature = temperature + self.normalize = normalize + if scale is not None and normalize is False: + raise ValueError("normalize should be True if scale is passed") + if scale is None: + scale = 2 * pi + self.scale = scale + + def forward( + self, x: torch.Tensor, mask: Optional[torch.Tensor] = None + ) -> torch.Tensor: + if mask is None: + mask = torch.zeros( + (x.size(0), x.size(2), x.size(3)), device=x.device, dtype=torch.bool + ) + not_mask = ~mask + y_embed = not_mask.cumsum(1, dtype=torch.float32) + x_embed = not_mask.cumsum(2, dtype=torch.float32) + if self.normalize: + eps = 1e-6 + y_embed = y_embed / (y_embed[:, -1:, :] + eps) * self.scale + x_embed = x_embed / (x_embed[:, :, -1:] + eps) * self.scale + + dim_t = torch.arange(self.num_pos_feats, dtype=torch.float32, device=x.device) + dim_t = self.temperature ** ( + 2 * torch.div(dim_t, 2, rounding_mode="floor") / self.num_pos_feats + ) + + pos_x = x_embed[:, :, :, None] / dim_t + pos_y = y_embed[:, :, :, None] / dim_t + pos_x = torch.stack( + (pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()), dim=4 + ).flatten(3) + pos_y = torch.stack( + (pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()), dim=4 + ).flatten(3) + pos = torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2) + return pos + + def __repr__(self, _repr_indent=4): + head = "Positional encoding " + self.__class__.__name__ + body = [ + "num_pos_feats: {}".format(self.num_pos_feats), + "temperature: {}".format(self.temperature), + "normalize: {}".format(self.normalize), + "scale: {}".format(self.scale), + ] + # _repr_indent = 4 + lines = [head] + [" " * _repr_indent + line for line in body] + return "\n".join(lines) + + +class LearnedSinusoidalPosEmb(nn.Module): + def __init__(self, dim): + super().__init__() + assert (dim % 2) == 0 + half_dim = dim // 2 + self.weights = nn.Parameter(torch.randn(half_dim)) + + def forward(self, x): + x = rearrange(x, "b -> b 1") + freqs = x * rearrange(self.weights, "d -> 1 d") * 2 * pi + fouriered = torch.cat((freqs.sin(), freqs.cos()), dim=-1) + fouriered = torch.cat((x, fouriered), dim=-1) + return fouriered + + +def broadcat(tensors, dim=-1): + num_tensors = len(tensors) + shape_lens = set(list(map(lambda t: len(t.shape), tensors))) + assert len(shape_lens) == 1, "tensors must all have the same number of dimensions" + shape_len = list(shape_lens)[0] + dim = (dim + shape_len) if dim < 0 else dim + dims = list(zip(*map(lambda t: list(t.shape), tensors))) + expandable_dims = [(i, val) for i, val in enumerate(dims) if i != dim] + assert all( + [*map(lambda t: len(set(t[1])) <= 2, expandable_dims)] + ), "invalid dimensions for broadcastable concatentation" + max_dims = list(map(lambda t: (t[0], max(t[1])), expandable_dims)) + expanded_dims = list(map(lambda t: (t[0], (t[1],) * num_tensors), max_dims)) + expanded_dims.insert(dim, (dim, dims[dim])) + expandable_shapes = list(zip(*map(lambda t: t[1], expanded_dims))) + tensors = list(map(lambda t: t[0].expand(*t[1]), zip(tensors, expandable_shapes))) + return torch.cat(tensors, dim=dim) + + +def rotate_half(x): + x = rearrange(x, "... (d r) -> ... d r", r=2) + x1, x2 = x.unbind(dim=-1) + x = torch.stack((-x2, x1), dim=-1) + return rearrange(x, "... d r -> ... (d r)") + + +class VisionRotaryEmbedding(nn.Module): + def __init__( + self, + dim, + pt_seq_len, + ft_seq_len=None, + custom_freqs=None, + freqs_for="lang", + theta=10000, + max_freq=10, + num_freqs=1, + ): + super().__init__() + if custom_freqs: + freqs = custom_freqs + elif freqs_for == "lang": + freqs = 1.0 / ( + theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim) + ) + elif freqs_for == "pixel": + freqs = torch.linspace(1.0, max_freq / 2, dim // 2) * pi + elif freqs_for == "constant": + freqs = torch.ones(num_freqs).float() + else: + raise ValueError(f"unknown modality {freqs_for}") + + if ft_seq_len is None: + ft_seq_len = pt_seq_len + t = torch.arange(ft_seq_len) / ft_seq_len * pt_seq_len + + freqs_h = torch.einsum("..., f -> ... f", t, freqs) + freqs_h = repeat(freqs_h, "... n -> ... (n r)", r=2) + + freqs_w = torch.einsum("..., f -> ... f", t, freqs) + freqs_w = repeat(freqs_w, "... n -> ... (n r)", r=2) + + freqs = broadcat((freqs_h[:, None, :], freqs_w[None, :, :]), dim=-1) + + self.register_buffer("freqs_cos", freqs.cos()) + self.register_buffer("freqs_sin", freqs.sin()) + + print("======== shape of rope freq", self.freqs_cos.shape, "========") + + def forward(self, t, start_index=0): + rot_dim = self.freqs_cos.shape[-1] + end_index = start_index + rot_dim + assert ( + rot_dim <= t.shape[-1] + ), f"feature dimension {t.shape[-1]} is not of sufficient size to rotate in all the positions {rot_dim}" + t_left, t, t_right = ( + t[..., :start_index], + t[..., start_index:end_index], + t[..., end_index:], + ) + t = (t * self.freqs_cos) + (rotate_half(t) * self.freqs_sin) + return torch.cat((t_left, t, t_right), dim=-1) + + +class VisionRotaryEmbeddingFast(nn.Module): + def __init__( + self, + dim, + pt_seq_len, + ft_seq_len=None, + custom_freqs=None, + freqs_for="lang", + theta=10000, + max_freq=10, + num_freqs=1, + ): + super().__init__() + if custom_freqs: + freqs = custom_freqs + elif freqs_for == "lang": + freqs = 1.0 / ( + theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim) + ) + elif freqs_for == "pixel": + freqs = torch.linspace(1.0, max_freq / 2, dim // 2) * pi + elif freqs_for == "constant": + freqs = torch.ones(num_freqs).float() + else: + raise ValueError(f"unknown modality {freqs_for}") + + if ft_seq_len is None: + ft_seq_len = pt_seq_len + t = torch.arange(ft_seq_len) / ft_seq_len * pt_seq_len + + freqs = torch.einsum("..., f -> ... f", t, freqs) + freqs = repeat(freqs, "... n -> ... (n r)", r=2) + freqs = broadcat((freqs[:, None, :], freqs[None, :, :]), dim=-1) + + freqs_cos = freqs.cos().view(-1, freqs.shape[-1]) + freqs_sin = freqs.sin().view(-1, freqs.shape[-1]) + + self.register_buffer("freqs_cos", freqs_cos) + self.register_buffer("freqs_sin", freqs_sin) + + def forward(self, t): + return t * self.freqs_cos + rotate_half(t) * self.freqs_sin + + +from math import log2 + + +def generate_fourier_features( + x: torch.Tensor, + dim: int = 512, + max_freq: int = 64, + use_cos: bool = False, + use_log: bool = False, + cat_orig: bool = False, +): + x_orig = x + device, dtype, input_dim = x.device, x.dtype, x.shape[-1] + num_bands = dim // (2 * input_dim) if use_cos else dim // input_dim + + if use_log: + scales = 2.0 ** torch.linspace( + 0.0, log2(max_freq), steps=num_bands, device=device, dtype=dtype + ) + else: + scales = torch.linspace( + 1.0, max_freq / 2, num_bands, device=device, dtype=dtype + ) + + x = x.unsqueeze(-1) + scales = scales[(*((None,) * (len(x.shape) - 1)), Ellipsis)] + + x = x * scales * pi + x = torch.cat( + ( + [x.sin(), x.cos()] + if use_cos + else [ + x.sin(), + ] + ), + dim=-1, + ) + x = x.flatten(-2) + if cat_orig: + return torch.cat((x, x_orig), dim=-1) + return x + + +# from PIL import Image +# from unidepth.utils import image_grid, colorize +# if __name__ == "__main__": +# H, W = 512, 512 +# resolution = 128 +# mesh = torch.meshgrid(torch.linspace(-1, 1, H), torch.linspace(-1, 1, W)) +# mesh = torch.stack(mesh, dim=0).unsqueeze(0) +# mesh = mesh.view(1, 2, -1).permute(0, 2, 1) + +# features = generate_fourier_features(mesh, dim=32, max_freq=resolution, use_log=True) +# channels = features.shape[-1] +# print(features.shape) + +# features = features[0].view(H, W, channels).permute(2, 0, 1).numpy() +# Image.fromarray(image_grid([colorize(1+x, 0.0, 2.0, "viridis") for x in features], rows=8, cols=4)).save(f"tmp_{resolution}.png") diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/utils/sht.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/utils/sht.py new file mode 100644 index 0000000000000000000000000000000000000000..4d6492ad047e6f7656e12f5e68fceda87e248d25 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/utils/sht.py @@ -0,0 +1,1638 @@ +"""Real spherical harmonics in Cartesian form for PyTorch. + +This is an autogenerated file. See +https://github.com/cheind/torch-spherical-harmonics +for more information. +""" + +import torch + + +def rsh_cart_0(xyz: torch.Tensor): + """Computes all real spherical harmonics up to degree 0. + + This is an autogenerated method. See + https://github.com/cheind/torch-spherical-harmonics + for more information. + + Params: + xyz: (N,...,3) tensor of points on the unit sphere + + Returns: + rsh: (N,...,1) real spherical harmonics + projections of input. Ynm is found at index + `n*(n+1) + m`, with `0 <= n <= degree` and + `-n <= m <= n`. + """ + + return torch.stack( + [ + xyz.new_tensor(0.282094791773878).expand(xyz.shape[:-1]), + ], + -1, + ) + + +def rsh_cart_1(xyz: torch.Tensor): + """Computes all real spherical harmonics up to degree 1. + + This is an autogenerated method. See + https://github.com/cheind/torch-spherical-harmonics + for more information. + + Params: + xyz: (N,...,3) tensor of points on the unit sphere + + Returns: + rsh: (N,...,4) real spherical harmonics + projections of input. Ynm is found at index + `n*(n+1) + m`, with `0 <= n <= degree` and + `-n <= m <= n`. + """ + x = xyz[..., 0] + y = xyz[..., 1] + z = xyz[..., 2] + + return torch.stack( + [ + xyz.new_tensor(0.282094791773878).expand(xyz.shape[:-1]), + -0.48860251190292 * y, + 0.48860251190292 * z, + -0.48860251190292 * x, + ], + -1, + ) + + +def rsh_cart_2(xyz: torch.Tensor): + """Computes all real spherical harmonics up to degree 2. + + This is an autogenerated method. See + https://github.com/cheind/torch-spherical-harmonics + for more information. + + Params: + xyz: (N,...,3) tensor of points on the unit sphere + + Returns: + rsh: (N,...,9) real spherical harmonics + projections of input. Ynm is found at index + `n*(n+1) + m`, with `0 <= n <= degree` and + `-n <= m <= n`. + """ + x = xyz[..., 0] + y = xyz[..., 1] + z = xyz[..., 2] + + x2 = x**2 + y2 = y**2 + z2 = z**2 + xy = x * y + xz = x * z + yz = y * z + + return torch.stack( + [ + xyz.new_tensor(0.282094791773878).expand(xyz.shape[:-1]), + -0.48860251190292 * y, + 0.48860251190292 * z, + -0.48860251190292 * x, + 1.09254843059208 * xy, + -1.09254843059208 * yz, + 0.94617469575756 * z2 - 0.31539156525252, + -1.09254843059208 * xz, + 0.54627421529604 * x2 - 0.54627421529604 * y2, + ], + -1, + ) + + +def rsh_cart_3(xyz: torch.Tensor): + """Computes all real spherical harmonics up to degree 3. + + This is an autogenerated method. See + https://github.com/cheind/torch-spherical-harmonics + for more information. + + Params: + xyz: (N,...,3) tensor of points on the unit sphere + + Returns: + rsh: (N,...,16) real spherical harmonics + projections of input. Ynm is found at index + `n*(n+1) + m`, with `0 <= n <= degree` and + `-n <= m <= n`. + """ + x = xyz[..., 0] + y = xyz[..., 1] + z = xyz[..., 2] + + x2 = x**2 + y2 = y**2 + z2 = z**2 + xy = x * y + xz = x * z + yz = y * z + + return torch.stack( + [ + xyz.new_tensor(0.282094791773878).expand(xyz.shape[:-1]), + -0.48860251190292 * y, + 0.48860251190292 * z, + -0.48860251190292 * x, + 1.09254843059208 * xy, + -1.09254843059208 * yz, + 0.94617469575756 * z2 - 0.31539156525252, + -1.09254843059208 * xz, + 0.54627421529604 * x2 - 0.54627421529604 * y2, + -0.590043589926644 * y * (3.0 * x2 - y2), + 2.89061144264055 * xy * z, + 0.304697199642977 * y * (1.5 - 7.5 * z2), + 1.24392110863372 * z * (1.5 * z2 - 0.5) - 0.497568443453487 * z, + 0.304697199642977 * x * (1.5 - 7.5 * z2), + 1.44530572132028 * z * (x2 - y2), + -0.590043589926644 * x * (x2 - 3.0 * y2), + ], + -1, + ) + + +def rsh_cart_4(xyz: torch.Tensor): + """Computes all real spherical harmonics up to degree 4. + + This is an autogenerated method. See + https://github.com/cheind/torch-spherical-harmonics + for more information. + + Params: + xyz: (N,...,3) tensor of points on the unit sphere + + Returns: + rsh: (N,...,25) real spherical harmonics + projections of input. Ynm is found at index + `n*(n+1) + m`, with `0 <= n <= degree` and + `-n <= m <= n`. + """ + x = xyz[..., 0] + y = xyz[..., 1] + z = xyz[..., 2] + + x2 = x**2 + y2 = y**2 + z2 = z**2 + xy = x * y + xz = x * z + yz = y * z + x4 = x2**2 + y4 = y2**2 + z4 = z2**2 + + return torch.stack( + [ + xyz.new_tensor(0.282094791773878).expand(xyz.shape[:-1]), + -0.48860251190292 * y, + 0.48860251190292 * z, + -0.48860251190292 * x, + 1.09254843059208 * xy, + -1.09254843059208 * yz, + 0.94617469575756 * z2 - 0.31539156525252, + -1.09254843059208 * xz, + 0.54627421529604 * x2 - 0.54627421529604 * y2, + -0.590043589926644 * y * (3.0 * x2 - y2), + 2.89061144264055 * xy * z, + 0.304697199642977 * y * (1.5 - 7.5 * z2), + 1.24392110863372 * z * (1.5 * z2 - 0.5) - 0.497568443453487 * z, + 0.304697199642977 * x * (1.5 - 7.5 * z2), + 1.44530572132028 * z * (x2 - y2), + -0.590043589926644 * x * (x2 - 3.0 * y2), + 2.5033429417967 * xy * (x2 - y2), + -1.77013076977993 * yz * (3.0 * x2 - y2), + 0.126156626101008 * xy * (52.5 * z2 - 7.5), + 0.267618617422916 * y * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z), + 1.48099765681286 + * z + * (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z) + - 0.952069922236839 * z2 + + 0.317356640745613, + 0.267618617422916 * x * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z), + 0.063078313050504 * (x2 - y2) * (52.5 * z2 - 7.5), + -1.77013076977993 * xz * (x2 - 3.0 * y2), + -3.75501441269506 * x2 * y2 + + 0.625835735449176 * x4 + + 0.625835735449176 * y4, + ], + -1, + ) + + +def rsh_cart_5(xyz: torch.Tensor): + """Computes all real spherical harmonics up to degree 5. + + This is an autogenerated method. See + https://github.com/cheind/torch-spherical-harmonics + for more information. + + Params: + xyz: (N,...,3) tensor of points on the unit sphere + + Returns: + rsh: (N,...,36) real spherical harmonics + projections of input. Ynm is found at index + `n*(n+1) + m`, with `0 <= n <= degree` and + `-n <= m <= n`. + """ + x = xyz[..., 0] + y = xyz[..., 1] + z = xyz[..., 2] + + x2 = x**2 + y2 = y**2 + z2 = z**2 + xy = x * y + xz = x * z + yz = y * z + x4 = x2**2 + y4 = y2**2 + z4 = z2**2 + + return torch.stack( + [ + xyz.new_tensor(0.282094791773878).expand(xyz.shape[:-1]), + -0.48860251190292 * y, + 0.48860251190292 * z, + -0.48860251190292 * x, + 1.09254843059208 * xy, + -1.09254843059208 * yz, + 0.94617469575756 * z2 - 0.31539156525252, + -1.09254843059208 * xz, + 0.54627421529604 * x2 - 0.54627421529604 * y2, + -0.590043589926644 * y * (3.0 * x2 - y2), + 2.89061144264055 * xy * z, + 0.304697199642977 * y * (1.5 - 7.5 * z2), + 1.24392110863372 * z * (1.5 * z2 - 0.5) - 0.497568443453487 * z, + 0.304697199642977 * x * (1.5 - 7.5 * z2), + 1.44530572132028 * z * (x2 - y2), + -0.590043589926644 * x * (x2 - 3.0 * y2), + 2.5033429417967 * xy * (x2 - y2), + -1.77013076977993 * yz * (3.0 * x2 - y2), + 0.126156626101008 * xy * (52.5 * z2 - 7.5), + 0.267618617422916 * y * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z), + 1.48099765681286 + * z + * (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z) + - 0.952069922236839 * z2 + + 0.317356640745613, + 0.267618617422916 * x * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z), + 0.063078313050504 * (x2 - y2) * (52.5 * z2 - 7.5), + -1.77013076977993 * xz * (x2 - 3.0 * y2), + -3.75501441269506 * x2 * y2 + + 0.625835735449176 * x4 + + 0.625835735449176 * y4, + -0.65638205684017 * y * (-10.0 * x2 * y2 + 5.0 * x4 + y4), + 8.30264925952416 * xy * z * (x2 - y2), + 0.00931882475114763 * y * (52.5 - 472.5 * z2) * (3.0 * x2 - y2), + 0.0913054625709205 * xy * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z), + 0.241571547304372 + * y + * ( + 2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z) + + 9.375 * z2 + - 1.875 + ), + -1.24747010616985 * z * (1.5 * z2 - 0.5) + + 1.6840846433293 + * z + * ( + 1.75 + * z + * (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z) + - 1.125 * z2 + + 0.375 + ) + + 0.498988042467941 * z, + 0.241571547304372 + * x + * ( + 2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z) + + 9.375 * z2 + - 1.875 + ), + 0.0456527312854602 * (x2 - y2) * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z), + 0.00931882475114763 * x * (52.5 - 472.5 * z2) * (x2 - 3.0 * y2), + 2.07566231488104 * z * (-6.0 * x2 * y2 + x4 + y4), + -0.65638205684017 * x * (-10.0 * x2 * y2 + x4 + 5.0 * y4), + ], + -1, + ) + + +def rsh_cart_6(xyz: torch.Tensor): + """Computes all real spherical harmonics up to degree 6. + + This is an autogenerated method. See + https://github.com/cheind/torch-spherical-harmonics + for more information. + + Params: + xyz: (N,...,3) tensor of points on the unit sphere + + Returns: + rsh: (N,...,49) real spherical harmonics + projections of input. Ynm is found at index + `n*(n+1) + m`, with `0 <= n <= degree` and + `-n <= m <= n`. + """ + x = xyz[..., 0] + y = xyz[..., 1] + z = xyz[..., 2] + + x2 = x**2 + y2 = y**2 + z2 = z**2 + xy = x * y + xz = x * z + yz = y * z + x4 = x2**2 + y4 = y2**2 + z4 = z2**2 + + return torch.stack( + [ + xyz.new_tensor(0.282094791773878).expand(xyz.shape[:-1]), + -0.48860251190292 * y, + 0.48860251190292 * z, + -0.48860251190292 * x, + 1.09254843059208 * xy, + -1.09254843059208 * yz, + 0.94617469575756 * z2 - 0.31539156525252, + -1.09254843059208 * xz, + 0.54627421529604 * x2 - 0.54627421529604 * y2, + -0.590043589926644 * y * (3.0 * x2 - y2), + 2.89061144264055 * xy * z, + 0.304697199642977 * y * (1.5 - 7.5 * z2), + 1.24392110863372 * z * (1.5 * z2 - 0.5) - 0.497568443453487 * z, + 0.304697199642977 * x * (1.5 - 7.5 * z2), + 1.44530572132028 * z * (x2 - y2), + -0.590043589926644 * x * (x2 - 3.0 * y2), + 2.5033429417967 * xy * (x2 - y2), + -1.77013076977993 * yz * (3.0 * x2 - y2), + 0.126156626101008 * xy * (52.5 * z2 - 7.5), + 0.267618617422916 * y * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z), + 1.48099765681286 + * z + * (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z) + - 0.952069922236839 * z2 + + 0.317356640745613, + 0.267618617422916 * x * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z), + 0.063078313050504 * (x2 - y2) * (52.5 * z2 - 7.5), + -1.77013076977993 * xz * (x2 - 3.0 * y2), + -3.75501441269506 * x2 * y2 + + 0.625835735449176 * x4 + + 0.625835735449176 * y4, + -0.65638205684017 * y * (-10.0 * x2 * y2 + 5.0 * x4 + y4), + 8.30264925952416 * xy * z * (x2 - y2), + 0.00931882475114763 * y * (52.5 - 472.5 * z2) * (3.0 * x2 - y2), + 0.0913054625709205 * xy * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z), + 0.241571547304372 + * y + * ( + 2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z) + + 9.375 * z2 + - 1.875 + ), + -1.24747010616985 * z * (1.5 * z2 - 0.5) + + 1.6840846433293 + * z + * ( + 1.75 + * z + * (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z) + - 1.125 * z2 + + 0.375 + ) + + 0.498988042467941 * z, + 0.241571547304372 + * x + * ( + 2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z) + + 9.375 * z2 + - 1.875 + ), + 0.0456527312854602 * (x2 - y2) * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z), + 0.00931882475114763 * x * (52.5 - 472.5 * z2) * (x2 - 3.0 * y2), + 2.07566231488104 * z * (-6.0 * x2 * y2 + x4 + y4), + -0.65638205684017 * x * (-10.0 * x2 * y2 + x4 + 5.0 * y4), + 4.09910463115149 * x**4 * xy + - 13.6636821038383 * xy**3 + + 4.09910463115149 * xy * y**4, + -2.36661916223175 * yz * (-10.0 * x2 * y2 + 5.0 * x4 + y4), + 0.00427144889505798 * xy * (x2 - y2) * (5197.5 * z2 - 472.5), + 0.00584892228263444 + * y + * (3.0 * x2 - y2) + * (3.66666666666667 * z * (52.5 - 472.5 * z2) + 280.0 * z), + 0.0701870673916132 + * xy + * ( + 2.75 * z * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z) + - 91.875 * z2 + + 13.125 + ), + 0.221950995245231 + * y + * ( + -2.8 * z * (1.5 - 7.5 * z2) + + 2.2 + * z + * ( + 2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z) + + 9.375 * z2 + - 1.875 + ) + - 4.8 * z + ), + -1.48328138624466 + * z + * (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z) + + 1.86469659985043 + * z + * ( + -1.33333333333333 * z * (1.5 * z2 - 0.5) + + 1.8 + * z + * ( + 1.75 + * z + * (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z) + - 1.125 * z2 + + 0.375 + ) + + 0.533333333333333 * z + ) + + 0.953538034014426 * z2 + - 0.317846011338142, + 0.221950995245231 + * x + * ( + -2.8 * z * (1.5 - 7.5 * z2) + + 2.2 + * z + * ( + 2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z) + + 9.375 * z2 + - 1.875 + ) + - 4.8 * z + ), + 0.0350935336958066 + * (x2 - y2) + * ( + 2.75 * z * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z) + - 91.875 * z2 + + 13.125 + ), + 0.00584892228263444 + * x + * (x2 - 3.0 * y2) + * (3.66666666666667 * z * (52.5 - 472.5 * z2) + 280.0 * z), + 0.0010678622237645 * (5197.5 * z2 - 472.5) * (-6.0 * x2 * y2 + x4 + y4), + -2.36661916223175 * xz * (-10.0 * x2 * y2 + x4 + 5.0 * y4), + 0.683184105191914 * x2**3 + + 10.2477615778787 * x2 * y4 + - 10.2477615778787 * x4 * y2 + - 0.683184105191914 * y2**3, + ], + -1, + ) + + +def rsh_cart_7(xyz: torch.Tensor): + """Computes all real spherical harmonics up to degree 7. + + This is an autogenerated method. See + https://github.com/cheind/torch-spherical-harmonics + for more information. + + Params: + xyz: (N,...,3) tensor of points on the unit sphere + + Returns: + rsh: (N,...,64) real spherical harmonics + projections of input. Ynm is found at index + `n*(n+1) + m`, with `0 <= n <= degree` and + `-n <= m <= n`. + """ + x = xyz[..., 0] + y = xyz[..., 1] + z = xyz[..., 2] + + x2 = x**2 + y2 = y**2 + z2 = z**2 + xy = x * y + xz = x * z + yz = y * z + x4 = x2**2 + y4 = y2**2 + z4 = z2**2 + + return torch.stack( + [ + xyz.new_tensor(0.282094791773878).expand(xyz.shape[:-1]), + -0.48860251190292 * y, + 0.48860251190292 * z, + -0.48860251190292 * x, + 1.09254843059208 * xy, + -1.09254843059208 * yz, + 0.94617469575756 * z2 - 0.31539156525252, + -1.09254843059208 * xz, + 0.54627421529604 * x2 - 0.54627421529604 * y2, + -0.590043589926644 * y * (3.0 * x2 - y2), + 2.89061144264055 * xy * z, + 0.304697199642977 * y * (1.5 - 7.5 * z2), + 1.24392110863372 * z * (1.5 * z2 - 0.5) - 0.497568443453487 * z, + 0.304697199642977 * x * (1.5 - 7.5 * z2), + 1.44530572132028 * z * (x2 - y2), + -0.590043589926644 * x * (x2 - 3.0 * y2), + 2.5033429417967 * xy * (x2 - y2), + -1.77013076977993 * yz * (3.0 * x2 - y2), + 0.126156626101008 * xy * (52.5 * z2 - 7.5), + 0.267618617422916 * y * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z), + 1.48099765681286 + * z + * (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z) + - 0.952069922236839 * z2 + + 0.317356640745613, + 0.267618617422916 * x * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z), + 0.063078313050504 * (x2 - y2) * (52.5 * z2 - 7.5), + -1.77013076977993 * xz * (x2 - 3.0 * y2), + -3.75501441269506 * x2 * y2 + + 0.625835735449176 * x4 + + 0.625835735449176 * y4, + -0.65638205684017 * y * (-10.0 * x2 * y2 + 5.0 * x4 + y4), + 8.30264925952416 * xy * z * (x2 - y2), + 0.00931882475114763 * y * (52.5 - 472.5 * z2) * (3.0 * x2 - y2), + 0.0913054625709205 * xy * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z), + 0.241571547304372 + * y + * ( + 2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z) + + 9.375 * z2 + - 1.875 + ), + -1.24747010616985 * z * (1.5 * z2 - 0.5) + + 1.6840846433293 + * z + * ( + 1.75 + * z + * (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z) + - 1.125 * z2 + + 0.375 + ) + + 0.498988042467941 * z, + 0.241571547304372 + * x + * ( + 2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z) + + 9.375 * z2 + - 1.875 + ), + 0.0456527312854602 * (x2 - y2) * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z), + 0.00931882475114763 * x * (52.5 - 472.5 * z2) * (x2 - 3.0 * y2), + 2.07566231488104 * z * (-6.0 * x2 * y2 + x4 + y4), + -0.65638205684017 * x * (-10.0 * x2 * y2 + x4 + 5.0 * y4), + 4.09910463115149 * x**4 * xy + - 13.6636821038383 * xy**3 + + 4.09910463115149 * xy * y**4, + -2.36661916223175 * yz * (-10.0 * x2 * y2 + 5.0 * x4 + y4), + 0.00427144889505798 * xy * (x2 - y2) * (5197.5 * z2 - 472.5), + 0.00584892228263444 + * y + * (3.0 * x2 - y2) + * (3.66666666666667 * z * (52.5 - 472.5 * z2) + 280.0 * z), + 0.0701870673916132 + * xy + * ( + 2.75 * z * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z) + - 91.875 * z2 + + 13.125 + ), + 0.221950995245231 + * y + * ( + -2.8 * z * (1.5 - 7.5 * z2) + + 2.2 + * z + * ( + 2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z) + + 9.375 * z2 + - 1.875 + ) + - 4.8 * z + ), + -1.48328138624466 + * z + * (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z) + + 1.86469659985043 + * z + * ( + -1.33333333333333 * z * (1.5 * z2 - 0.5) + + 1.8 + * z + * ( + 1.75 + * z + * (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z) + - 1.125 * z2 + + 0.375 + ) + + 0.533333333333333 * z + ) + + 0.953538034014426 * z2 + - 0.317846011338142, + 0.221950995245231 + * x + * ( + -2.8 * z * (1.5 - 7.5 * z2) + + 2.2 + * z + * ( + 2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z) + + 9.375 * z2 + - 1.875 + ) + - 4.8 * z + ), + 0.0350935336958066 + * (x2 - y2) + * ( + 2.75 * z * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z) + - 91.875 * z2 + + 13.125 + ), + 0.00584892228263444 + * x + * (x2 - 3.0 * y2) + * (3.66666666666667 * z * (52.5 - 472.5 * z2) + 280.0 * z), + 0.0010678622237645 * (5197.5 * z2 - 472.5) * (-6.0 * x2 * y2 + x4 + y4), + -2.36661916223175 * xz * (-10.0 * x2 * y2 + x4 + 5.0 * y4), + 0.683184105191914 * x2**3 + + 10.2477615778787 * x2 * y4 + - 10.2477615778787 * x4 * y2 + - 0.683184105191914 * y2**3, + -0.707162732524596 + * y + * (7.0 * x2**3 + 21.0 * x2 * y4 - 35.0 * x4 * y2 - y2**3), + 2.6459606618019 * z * (6.0 * x**4 * xy - 20.0 * xy**3 + 6.0 * xy * y**4), + 9.98394571852353e-5 + * y + * (5197.5 - 67567.5 * z2) + * (-10.0 * x2 * y2 + 5.0 * x4 + y4), + 0.00239614697244565 + * xy + * (x2 - y2) + * (4.33333333333333 * z * (5197.5 * z2 - 472.5) - 3150.0 * z), + 0.00397356022507413 + * y + * (3.0 * x2 - y2) + * ( + 3.25 * z * (3.66666666666667 * z * (52.5 - 472.5 * z2) + 280.0 * z) + + 1063.125 * z2 + - 118.125 + ), + 0.0561946276120613 + * xy + * ( + -4.8 * z * (52.5 * z2 - 7.5) + + 2.6 + * z + * ( + 2.75 * z * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z) + - 91.875 * z2 + + 13.125 + ) + + 48.0 * z + ), + 0.206472245902897 + * y + * ( + -2.625 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z) + + 2.16666666666667 + * z + * ( + -2.8 * z * (1.5 - 7.5 * z2) + + 2.2 + * z + * ( + 2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z) + + 9.375 * z2 + - 1.875 + ) + - 4.8 * z + ) + - 10.9375 * z2 + + 2.1875 + ), + 1.24862677781952 * z * (1.5 * z2 - 0.5) + - 1.68564615005635 + * z + * ( + 1.75 + * z + * (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z) + - 1.125 * z2 + + 0.375 + ) + + 2.02901851395672 + * z + * ( + -1.45833333333333 + * z + * (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z) + + 1.83333333333333 + * z + * ( + -1.33333333333333 * z * (1.5 * z2 - 0.5) + + 1.8 + * z + * ( + 1.75 + * z + * ( + 1.66666666666667 * z * (1.5 * z2 - 0.5) + - 0.666666666666667 * z + ) + - 1.125 * z2 + + 0.375 + ) + + 0.533333333333333 * z + ) + + 0.9375 * z2 + - 0.3125 + ) + - 0.499450711127808 * z, + 0.206472245902897 + * x + * ( + -2.625 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z) + + 2.16666666666667 + * z + * ( + -2.8 * z * (1.5 - 7.5 * z2) + + 2.2 + * z + * ( + 2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z) + + 9.375 * z2 + - 1.875 + ) + - 4.8 * z + ) + - 10.9375 * z2 + + 2.1875 + ), + 0.0280973138060306 + * (x2 - y2) + * ( + -4.8 * z * (52.5 * z2 - 7.5) + + 2.6 + * z + * ( + 2.75 * z * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z) + - 91.875 * z2 + + 13.125 + ) + + 48.0 * z + ), + 0.00397356022507413 + * x + * (x2 - 3.0 * y2) + * ( + 3.25 * z * (3.66666666666667 * z * (52.5 - 472.5 * z2) + 280.0 * z) + + 1063.125 * z2 + - 118.125 + ), + 0.000599036743111412 + * (4.33333333333333 * z * (5197.5 * z2 - 472.5) - 3150.0 * z) + * (-6.0 * x2 * y2 + x4 + y4), + 9.98394571852353e-5 + * x + * (5197.5 - 67567.5 * z2) + * (-10.0 * x2 * y2 + x4 + 5.0 * y4), + 2.6459606618019 * z * (x2**3 + 15.0 * x2 * y4 - 15.0 * x4 * y2 - y2**3), + -0.707162732524596 + * x + * (x2**3 + 35.0 * x2 * y4 - 21.0 * x4 * y2 - 7.0 * y2**3), + ], + -1, + ) + + +# @torch.jit.script +def rsh_cart_8(xyz: torch.Tensor): + """Computes all real spherical harmonics up to degree 8. + + This is an autogenerated method. See + https://github.com/cheind/torch-spherical-harmonics + for more information. + + Params: + xyz: (N,...,3) tensor of points on the unit sphere + + Returns: + rsh: (N,...,81) real spherical harmonics + projections of input. Ynm is found at index + `n*(n+1) + m`, with `0 <= n <= degree` and + `-n <= m <= n`. + """ + x = xyz[..., 0] + y = xyz[..., 1] + z = xyz[..., 2] + + x2 = x**2 + y2 = y**2 + z2 = z**2 + xy = x * y + xz = x * z + yz = y * z + x4 = x2**2 + y4 = y2**2 + # z4 = z2**2 + return torch.stack( + [ + 0.282094791773878 * torch.ones(1, device=xyz.device).expand(xyz.shape[:-1]), + -0.48860251190292 * y, + 0.48860251190292 * z, + -0.48860251190292 * x, + 1.09254843059208 * xy, + -1.09254843059208 * yz, + 0.94617469575756 * z2 - 0.31539156525252, + -1.09254843059208 * xz, + 0.54627421529604 * x2 - 0.54627421529604 * y2, + -0.590043589926644 * y * (3.0 * x2 - y2), + 2.89061144264055 * xy * z, + 0.304697199642977 * y * (1.5 - 7.5 * z2), + 1.24392110863372 * z * (1.5 * z2 - 0.5) - 0.497568443453487 * z, + 0.304697199642977 * x * (1.5 - 7.5 * z2), + 1.44530572132028 * z * (x2 - y2), + -0.590043589926644 * x * (x2 - 3.0 * y2), + 2.5033429417967 * xy * (x2 - y2), + -1.77013076977993 * yz * (3.0 * x2 - y2), + 0.126156626101008 * xy * (52.5 * z2 - 7.5), + 0.267618617422916 * y * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z), + 1.48099765681286 + * z + * (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z) + - 0.952069922236839 * z2 + + 0.317356640745613, + 0.267618617422916 * x * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z), + 0.063078313050504 * (x2 - y2) * (52.5 * z2 - 7.5), + -1.77013076977993 * xz * (x2 - 3.0 * y2), + -3.75501441269506 * x2 * y2 + + 0.625835735449176 * x4 + + 0.625835735449176 * y4, + -0.65638205684017 * y * (-10.0 * x2 * y2 + 5.0 * x4 + y4), + 8.30264925952416 * xy * z * (x2 - y2), + 0.00931882475114763 * y * (52.5 - 472.5 * z2) * (3.0 * x2 - y2), + 0.0913054625709205 * xy * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z), + 0.241571547304372 + * y + * ( + 2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z) + + 9.375 * z2 + - 1.875 + ), + -1.24747010616985 * z * (1.5 * z2 - 0.5) + + 1.6840846433293 + * z + * ( + 1.75 + * z + * (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z) + - 1.125 * z2 + + 0.375 + ) + + 0.498988042467941 * z, + 0.241571547304372 + * x + * ( + 2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z) + + 9.375 * z2 + - 1.875 + ), + 0.0456527312854602 * (x2 - y2) * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z), + 0.00931882475114763 * x * (52.5 - 472.5 * z2) * (x2 - 3.0 * y2), + 2.07566231488104 * z * (-6.0 * x2 * y2 + x4 + y4), + -0.65638205684017 * x * (-10.0 * x2 * y2 + x4 + 5.0 * y4), + 4.09910463115149 * x**4 * xy + - 13.6636821038383 * xy**3 + + 4.09910463115149 * xy * y**4, + -2.36661916223175 * yz * (-10.0 * x2 * y2 + 5.0 * x4 + y4), + 0.00427144889505798 * xy * (x2 - y2) * (5197.5 * z2 - 472.5), + 0.00584892228263444 + * y + * (3.0 * x2 - y2) + * (3.66666666666667 * z * (52.5 - 472.5 * z2) + 280.0 * z), + 0.0701870673916132 + * xy + * ( + 2.75 * z * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z) + - 91.875 * z2 + + 13.125 + ), + 0.221950995245231 + * y + * ( + -2.8 * z * (1.5 - 7.5 * z2) + + 2.2 + * z + * ( + 2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z) + + 9.375 * z2 + - 1.875 + ) + - 4.8 * z + ), + -1.48328138624466 + * z + * (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z) + + 1.86469659985043 + * z + * ( + -1.33333333333333 * z * (1.5 * z2 - 0.5) + + 1.8 + * z + * ( + 1.75 + * z + * (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z) + - 1.125 * z2 + + 0.375 + ) + + 0.533333333333333 * z + ) + + 0.953538034014426 * z2 + - 0.317846011338142, + 0.221950995245231 + * x + * ( + -2.8 * z * (1.5 - 7.5 * z2) + + 2.2 + * z + * ( + 2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z) + + 9.375 * z2 + - 1.875 + ) + - 4.8 * z + ), + 0.0350935336958066 + * (x2 - y2) + * ( + 2.75 * z * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z) + - 91.875 * z2 + + 13.125 + ), + 0.00584892228263444 + * x + * (x2 - 3.0 * y2) + * (3.66666666666667 * z * (52.5 - 472.5 * z2) + 280.0 * z), + 0.0010678622237645 * (5197.5 * z2 - 472.5) * (-6.0 * x2 * y2 + x4 + y4), + -2.36661916223175 * xz * (-10.0 * x2 * y2 + x4 + 5.0 * y4), + 0.683184105191914 * x2**3 + + 10.2477615778787 * x2 * y4 + - 10.2477615778787 * x4 * y2 + - 0.683184105191914 * y2**3, + -0.707162732524596 + * y + * (7.0 * x2**3 + 21.0 * x2 * y4 - 35.0 * x4 * y2 - y2**3), + 2.6459606618019 * z * (6.0 * x**4 * xy - 20.0 * xy**3 + 6.0 * xy * y**4), + 9.98394571852353e-5 + * y + * (5197.5 - 67567.5 * z2) + * (-10.0 * x2 * y2 + 5.0 * x4 + y4), + 0.00239614697244565 + * xy + * (x2 - y2) + * (4.33333333333333 * z * (5197.5 * z2 - 472.5) - 3150.0 * z), + 0.00397356022507413 + * y + * (3.0 * x2 - y2) + * ( + 3.25 * z * (3.66666666666667 * z * (52.5 - 472.5 * z2) + 280.0 * z) + + 1063.125 * z2 + - 118.125 + ), + 0.0561946276120613 + * xy + * ( + -4.8 * z * (52.5 * z2 - 7.5) + + 2.6 + * z + * ( + 2.75 * z * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z) + - 91.875 * z2 + + 13.125 + ) + + 48.0 * z + ), + 0.206472245902897 + * y + * ( + -2.625 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z) + + 2.16666666666667 + * z + * ( + -2.8 * z * (1.5 - 7.5 * z2) + + 2.2 + * z + * ( + 2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z) + + 9.375 * z2 + - 1.875 + ) + - 4.8 * z + ) + - 10.9375 * z2 + + 2.1875 + ), + 1.24862677781952 * z * (1.5 * z2 - 0.5) + - 1.68564615005635 + * z + * ( + 1.75 + * z + * (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z) + - 1.125 * z2 + + 0.375 + ) + + 2.02901851395672 + * z + * ( + -1.45833333333333 + * z + * (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z) + + 1.83333333333333 + * z + * ( + -1.33333333333333 * z * (1.5 * z2 - 0.5) + + 1.8 + * z + * ( + 1.75 + * z + * ( + 1.66666666666667 * z * (1.5 * z2 - 0.5) + - 0.666666666666667 * z + ) + - 1.125 * z2 + + 0.375 + ) + + 0.533333333333333 * z + ) + + 0.9375 * z2 + - 0.3125 + ) + - 0.499450711127808 * z, + 0.206472245902897 + * x + * ( + -2.625 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z) + + 2.16666666666667 + * z + * ( + -2.8 * z * (1.5 - 7.5 * z2) + + 2.2 + * z + * ( + 2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z) + + 9.375 * z2 + - 1.875 + ) + - 4.8 * z + ) + - 10.9375 * z2 + + 2.1875 + ), + 0.0280973138060306 + * (x2 - y2) + * ( + -4.8 * z * (52.5 * z2 - 7.5) + + 2.6 + * z + * ( + 2.75 * z * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z) + - 91.875 * z2 + + 13.125 + ) + + 48.0 * z + ), + 0.00397356022507413 + * x + * (x2 - 3.0 * y2) + * ( + 3.25 * z * (3.66666666666667 * z * (52.5 - 472.5 * z2) + 280.0 * z) + + 1063.125 * z2 + - 118.125 + ), + 0.000599036743111412 + * (4.33333333333333 * z * (5197.5 * z2 - 472.5) - 3150.0 * z) + * (-6.0 * x2 * y2 + x4 + y4), + 9.98394571852353e-5 + * x + * (5197.5 - 67567.5 * z2) + * (-10.0 * x2 * y2 + x4 + 5.0 * y4), + 2.6459606618019 * z * (x2**3 + 15.0 * x2 * y4 - 15.0 * x4 * y2 - y2**3), + -0.707162732524596 + * x + * (x2**3 + 35.0 * x2 * y4 - 21.0 * x4 * y2 - 7.0 * y2**3), + 5.83141328139864 * xy * (x2**3 + 7.0 * x2 * y4 - 7.0 * x4 * y2 - y2**3), + -2.91570664069932 + * yz + * (7.0 * x2**3 + 21.0 * x2 * y4 - 35.0 * x4 * y2 - y2**3), + 7.87853281621404e-6 + * (1013512.5 * z2 - 67567.5) + * (6.0 * x**4 * xy - 20.0 * xy**3 + 6.0 * xy * y**4), + 5.10587282657803e-5 + * y + * (5.0 * z * (5197.5 - 67567.5 * z2) + 41580.0 * z) + * (-10.0 * x2 * y2 + 5.0 * x4 + y4), + 0.00147275890257803 + * xy + * (x2 - y2) + * ( + 3.75 * z * (4.33333333333333 * z * (5197.5 * z2 - 472.5) - 3150.0 * z) + - 14293.125 * z2 + + 1299.375 + ), + 0.0028519853513317 + * y + * (3.0 * x2 - y2) + * ( + -7.33333333333333 * z * (52.5 - 472.5 * z2) + + 3.0 + * z + * ( + 3.25 * z * (3.66666666666667 * z * (52.5 - 472.5 * z2) + 280.0 * z) + + 1063.125 * z2 + - 118.125 + ) + - 560.0 * z + ), + 0.0463392770473559 + * xy + * ( + -4.125 * z * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z) + + 2.5 + * z + * ( + -4.8 * z * (52.5 * z2 - 7.5) + + 2.6 + * z + * ( + 2.75 * z * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z) + - 91.875 * z2 + + 13.125 + ) + + 48.0 * z + ) + + 137.8125 * z2 + - 19.6875 + ), + 0.193851103820053 + * y + * ( + 3.2 * z * (1.5 - 7.5 * z2) + - 2.51428571428571 + * z + * ( + 2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z) + + 9.375 * z2 + - 1.875 + ) + + 2.14285714285714 + * z + * ( + -2.625 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z) + + 2.16666666666667 + * z + * ( + -2.8 * z * (1.5 - 7.5 * z2) + + 2.2 + * z + * ( + 2.25 + * z + * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z) + + 9.375 * z2 + - 1.875 + ) + - 4.8 * z + ) + - 10.9375 * z2 + + 2.1875 + ) + + 5.48571428571429 * z + ), + 1.48417251362228 + * z + * (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z) + - 1.86581687426801 + * z + * ( + -1.33333333333333 * z * (1.5 * z2 - 0.5) + + 1.8 + * z + * ( + 1.75 + * z + * (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z) + - 1.125 * z2 + + 0.375 + ) + + 0.533333333333333 * z + ) + + 2.1808249179756 + * z + * ( + 1.14285714285714 * z * (1.5 * z2 - 0.5) + - 1.54285714285714 + * z + * ( + 1.75 + * z + * (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z) + - 1.125 * z2 + + 0.375 + ) + + 1.85714285714286 + * z + * ( + -1.45833333333333 + * z + * (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z) + + 1.83333333333333 + * z + * ( + -1.33333333333333 * z * (1.5 * z2 - 0.5) + + 1.8 + * z + * ( + 1.75 + * z + * ( + 1.66666666666667 * z * (1.5 * z2 - 0.5) + - 0.666666666666667 * z + ) + - 1.125 * z2 + + 0.375 + ) + + 0.533333333333333 * z + ) + + 0.9375 * z2 + - 0.3125 + ) + - 0.457142857142857 * z + ) + - 0.954110901614325 * z2 + + 0.318036967204775, + 0.193851103820053 + * x + * ( + 3.2 * z * (1.5 - 7.5 * z2) + - 2.51428571428571 + * z + * ( + 2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z) + + 9.375 * z2 + - 1.875 + ) + + 2.14285714285714 + * z + * ( + -2.625 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z) + + 2.16666666666667 + * z + * ( + -2.8 * z * (1.5 - 7.5 * z2) + + 2.2 + * z + * ( + 2.25 + * z + * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z) + + 9.375 * z2 + - 1.875 + ) + - 4.8 * z + ) + - 10.9375 * z2 + + 2.1875 + ) + + 5.48571428571429 * z + ), + 0.0231696385236779 + * (x2 - y2) + * ( + -4.125 * z * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z) + + 2.5 + * z + * ( + -4.8 * z * (52.5 * z2 - 7.5) + + 2.6 + * z + * ( + 2.75 * z * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z) + - 91.875 * z2 + + 13.125 + ) + + 48.0 * z + ) + + 137.8125 * z2 + - 19.6875 + ), + 0.0028519853513317 + * x + * (x2 - 3.0 * y2) + * ( + -7.33333333333333 * z * (52.5 - 472.5 * z2) + + 3.0 + * z + * ( + 3.25 * z * (3.66666666666667 * z * (52.5 - 472.5 * z2) + 280.0 * z) + + 1063.125 * z2 + - 118.125 + ) + - 560.0 * z + ), + 0.000368189725644507 + * (-6.0 * x2 * y2 + x4 + y4) + * ( + 3.75 * z * (4.33333333333333 * z * (5197.5 * z2 - 472.5) - 3150.0 * z) + - 14293.125 * z2 + + 1299.375 + ), + 5.10587282657803e-5 + * x + * (5.0 * z * (5197.5 - 67567.5 * z2) + 41580.0 * z) + * (-10.0 * x2 * y2 + x4 + 5.0 * y4), + 7.87853281621404e-6 + * (1013512.5 * z2 - 67567.5) + * (x2**3 + 15.0 * x2 * y4 - 15.0 * x4 * y2 - y2**3), + -2.91570664069932 + * xz + * (x2**3 + 35.0 * x2 * y4 - 21.0 * x4 * y2 - 7.0 * y2**3), + -20.4099464848952 * x2**3 * y2 + - 20.4099464848952 * x2 * y2**3 + + 0.72892666017483 * x4**2 + + 51.0248662122381 * x4 * y4 + + 0.72892666017483 * y4**2, + ], + -1, + ) + + +__all__ = [ + "rsh_cart_0", + "rsh_cart_1", + "rsh_cart_2", + "rsh_cart_3", + "rsh_cart_4", + "rsh_cart_5", + "rsh_cart_6", + "rsh_cart_7", + "rsh_cart_8", +] + + +from typing import Optional + +import torch + + +class SphHarm(torch.nn.Module): + def __init__(self, m, n, dtype=torch.float32) -> None: + super().__init__() + self.dtype = dtype + m = torch.tensor(list(range(-m + 1, m))) + n = torch.tensor(list(range(n))) + self.is_normalized = False + vals = torch.cartesian_prod(m, n).T + vals = vals[:, vals[0] <= vals[1]] + m, n = vals.unbind(0) + + self.register_buffer("m", tensor=m) + self.register_buffer("n", tensor=n) + self.register_buffer("l_max", tensor=torch.max(self.n)) + + f_a, f_b, initial_value, d0_mask_3d, d1_mask_3d = self._init_legendre() + self.register_buffer("f_a", tensor=f_a) + self.register_buffer("f_b", tensor=f_b) + self.register_buffer("d0_mask_3d", tensor=d0_mask_3d) + self.register_buffer("d1_mask_3d", tensor=d1_mask_3d) + self.register_buffer("initial_value", tensor=initial_value) + + @property + def device(self): + return next(self.buffers()).device + + def forward(self, points: torch.Tensor) -> torch.Tensor: + """Computes the spherical harmonics.""" + # Y_l^m = (-1) ^ m c_l^m P_l^m(cos(theta)) exp(i m phi) + B, N, D = points.shape + dtype = points.dtype + theta, phi = points.view(-1, D).to(self.dtype).unbind(-1) + cos_colatitude = torch.cos(phi) + legendre = self._gen_associated_legendre(cos_colatitude) + vals = torch.stack([self.m.abs(), self.n], dim=0) + vals = torch.cat( + [ + vals.repeat(1, theta.shape[0]), + torch.arange(theta.shape[0], device=theta.device) + .unsqueeze(0) + .repeat_interleave(vals.shape[1], dim=1), + ], + dim=0, + ) + legendre_vals = legendre[vals[0], vals[1], vals[2]] + legendre_vals = legendre_vals.reshape(-1, theta.shape[0]) + angle = torch.outer(self.m.abs(), theta) + vandermonde = torch.complex(torch.cos(angle), torch.sin(angle)) + harmonics = torch.complex( + legendre_vals * torch.real(vandermonde), + legendre_vals * torch.imag(vandermonde), + ) + + # Negative order. + m = self.m.unsqueeze(-1) + harmonics = torch.where( + m < 0, (-1.0) ** m.abs() * torch.conj(harmonics), harmonics + ) + harmonics = harmonics.permute(1, 0).reshape(B, N, -1).to(dtype) + return harmonics + + def _gen_recurrence_mask(self) -> tuple[torch.Tensor, torch.Tensor]: + """Generates mask for recurrence relation on the remaining entries. + + The remaining entries are with respect to the diagonal and offdiagonal + entries. + + Args: + l_max: see `gen_normalized_legendre`. + Returns: + torch.Tensors representing the mask used by the recurrence relations. + """ + + # Computes all coefficients. + m_mat, l_mat = torch.meshgrid( + torch.arange(0, self.l_max + 1, device=self.device, dtype=self.dtype), + torch.arange(0, self.l_max + 1, device=self.device, dtype=self.dtype), + indexing="ij", + ) + if self.is_normalized: + c0 = l_mat * l_mat + c1 = m_mat * m_mat + c2 = 2.0 * l_mat + c3 = (l_mat - 1.0) * (l_mat - 1.0) + d0 = torch.sqrt((4.0 * c0 - 1.0) / (c0 - c1)) + d1 = torch.sqrt(((c2 + 1.0) * (c3 - c1)) / ((c2 - 3.0) * (c0 - c1))) + else: + d0 = (2.0 * l_mat - 1.0) / (l_mat - m_mat) + d1 = (l_mat + m_mat - 1.0) / (l_mat - m_mat) + + d0_mask_indices = torch.triu_indices(self.l_max + 1, 1) + d1_mask_indices = torch.triu_indices(self.l_max + 1, 2) + + d_zeros = torch.zeros( + (self.l_max + 1, self.l_max + 1), dtype=self.dtype, device=self.device + ) + d_zeros[d0_mask_indices] = d0[d0_mask_indices] + d0_mask = d_zeros + + d_zeros = torch.zeros( + (self.l_max + 1, self.l_max + 1), dtype=self.dtype, device=self.device + ) + d_zeros[d1_mask_indices] = d1[d1_mask_indices] + d1_mask = d_zeros + + # Creates a 3D mask that contains 1s on the diagonal plane and 0s elsewhere. + i = torch.arange(self.l_max + 1, device=self.device)[:, None, None] + j = torch.arange(self.l_max + 1, device=self.device)[None, :, None] + k = torch.arange(self.l_max + 1, device=self.device)[None, None, :] + mask = (i + j - k == 0).to(self.dtype) + d0_mask_3d = torch.einsum("jk,ijk->ijk", d0_mask, mask) + d1_mask_3d = torch.einsum("jk,ijk->ijk", d1_mask, mask) + return (d0_mask_3d, d1_mask_3d) + + def _recursive(self, i: int, p_val: torch.Tensor, x: torch.Tensor) -> torch.Tensor: + coeff_0 = self.d0_mask_3d[i] + coeff_1 = self.d1_mask_3d[i] + h = torch.einsum( + "ij,ijk->ijk", + coeff_0, + torch.einsum("ijk,k->ijk", torch.roll(p_val, shifts=1, dims=1), x), + ) - torch.einsum("ij,ijk->ijk", coeff_1, torch.roll(p_val, shifts=2, dims=1)) + p_val = p_val + h + return p_val + + def _init_legendre(self): + a_idx = torch.arange(1, self.l_max + 1, dtype=self.dtype, device=self.device) + b_idx = torch.arange(self.l_max, dtype=self.dtype, device=self.device) + if self.is_normalized: + # The initial value p(0,0). + initial_value: torch.Tensor = torch.tensor( + 0.5 / (torch.pi**0.5), device=self.device + ) + f_a = torch.cumprod(-1 * torch.sqrt(1.0 + 0.5 / a_idx), dim=0) + f_b = torch.sqrt(2.0 * b_idx + 3.0) + else: + # The initial value p(0,0). + initial_value = torch.tensor(1.0, device=self.device) + f_a = torch.cumprod(1.0 - 2.0 * a_idx, dim=0) + f_b = 2.0 * b_idx + 1.0 + + d0_mask_3d, d1_mask_3d = self._gen_recurrence_mask() + return f_a, f_b, initial_value, d0_mask_3d, d1_mask_3d + + def _gen_associated_legendre(self, x: torch.Tensor) -> torch.Tensor: + r"""Computes associated Legendre functions (ALFs) of the first kind. + + The ALFs of the first kind are used in spherical harmonics. The spherical + harmonic of degree `l` and order `m` can be written as + `Y_l^m(θ, φ) = N_l^m * P_l^m(cos(θ)) * exp(i m φ)`, where `N_l^m` is the + normalization factor and θ and φ are the colatitude and longitude, + repectively. `N_l^m` is chosen in the way that the spherical harmonics form + a set of orthonormal basis function of L^2(S^2). For the computational + efficiency of spherical harmonics transform, the normalization factor is + used in the computation of the ALFs. In addition, normalizing `P_l^m` + avoids overflow/underflow and achieves better numerical stability. Three + recurrence relations are used in the computation. + + Args: + l_max: The maximum degree of the associated Legendre function. Both the + degrees and orders are `[0, 1, 2, ..., l_max]`. + x: A vector of type `float32`, `float64` containing the sampled points in + spherical coordinates, at which the ALFs are computed; `x` is essentially + `cos(θ)`. For the numerical integration used by the spherical harmonics + transforms, `x` contains the quadrature points in the interval of + `[-1, 1]`. There are several approaches to provide the quadrature points: + Gauss-Legendre method (`scipy.special.roots_legendre`), Gauss-Chebyshev + method (`scipy.special.roots_chebyu`), and Driscoll & Healy + method (Driscoll, James R., and Dennis M. Healy. "Computing Fourier + transforms and convolutions on the 2-sphere." Advances in applied + mathematics 15, no. 2 (1994): 202-250.). The Gauss-Legendre quadrature + points are nearly equal-spaced along θ and provide exact discrete + orthogonality, (P^m)^T W P_m = I, where `T` represents the transpose + operation, `W` is a diagonal matrix containing the quadrature weights, + and `I` is the identity matrix. The Gauss-Chebyshev points are equally + spaced, which only provide approximate discrete orthogonality. The + Driscoll & Healy qudarture points are equally spaced and provide the + exact discrete orthogonality. The number of sampling points is required to + be twice as the number of frequency points (modes) in the Driscoll & Healy + approach, which enables FFT and achieves a fast spherical harmonics + transform. + is_normalized: True if the associated Legendre functions are normalized. + With normalization, `N_l^m` is applied such that the spherical harmonics + form a set of orthonormal basis functions of L^2(S^2). + + Returns: + The 3D array of shape `(l_max + 1, l_max + 1, len(x))` containing the values + of the ALFs at `x`; the dimensions in the sequence of order, degree, and + evalution points. + """ + p = torch.zeros( + (self.l_max + 1, self.l_max + 1, x.shape[0]), dtype=x.dtype, device=x.device + ) + p[0, 0] = self.initial_value + + # Compute the diagonal entries p(l,l) with recurrence. + y = torch.cumprod( + torch.broadcast_to(torch.sqrt(1.0 - x * x), (self.l_max, x.shape[0])), dim=0 + ) + p_diag = self.initial_value * torch.einsum("i,ij->ij", self.f_a, y) + # torch.diag_indices(l_max + 1) + diag_indices = torch.stack( + [torch.arange(0, self.l_max + 1, device=x.device)] * 2, dim=0 + ) + p[(diag_indices[0][1:], diag_indices[1][1:])] = p_diag + + diag_indices = torch.stack( + [torch.arange(0, self.l_max, device=x.device)] * 2, dim=0 + ) + + # Compute the off-diagonal entries with recurrence. + p_offdiag = torch.einsum( + "ij,ij->ij", + torch.einsum("i,j->ij", self.f_b, x), + p[(diag_indices[0], diag_indices[1])], + ) # p[torch.diag_indices(l_max)]) + p[(diag_indices[0][: self.l_max], diag_indices[1][: self.l_max] + 1)] = ( + p_offdiag + ) + + # Compute the remaining entries with recurrence. + if self.l_max > 1: + for i in range(2, self.l_max + 1): + p = self._recursive(i, p, x) + return p diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/utils/validation.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/utils/validation.py new file mode 100644 index 0000000000000000000000000000000000000000..c2f4076fe9239623a9c98fec8cb660216f815198 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/utils/validation.py @@ -0,0 +1,94 @@ +""" +Author: Luigi Piccinelli +Licensed under the CC-BY NC 4.0 license (http://creativecommons.org/licenses/by-nc/4.0/) +""" + +import torch +import torch.utils.data.distributed +import wandb +from torch.nn import functional as F + +from unidepth.utils import barrier, is_main_process +from unidepth.utils.misc import remove_padding + + +def original_image(batch, preds=None): + paddings = [ + torch.tensor(pads) + for img_meta in batch["img_metas"] + for pads in img_meta.get("paddings", [[0] * 4]) + ] + paddings = torch.stack(paddings).to(batch["data"]["image"].device)[ + ..., [0, 2, 1, 3] + ] # lrtb + + T, _, H, W = batch["data"]["depth"].shape + batch["data"]["image"] = F.interpolate( + batch["data"]["image"], + (H + paddings[2] + paddings[3], W + paddings[1] + paddings[2]), + mode="bilinear", + align_corners=False, + antialias=True, + ) + batch["data"]["image"] = remove_padding( + batch["data"]["image"], paddings.repeat(T, 1) + ) + + if preds is not None: + for key in ["depth"]: + if key in preds: + preds[key] = F.interpolate( + preds[key], + (H + paddings[2] + paddings[3], W + paddings[1] + paddings[2]), + mode="bilinear", + align_corners=False, + antialias=True, + ) + preds[key] = remove_padding(preds[key], paddings.repeat(T, 1)) + + return batch, preds + + +def log_metrics(metrics_all, step): + for name_ds, metrics in metrics_all.items(): + for metrics_name, metrics_value in metrics.items(): + try: + print(f"Metrics/{name_ds}/{metrics_name} {round(metrics_value, 4)}") + wandb.log( + {f"Metrics/{name_ds}/{metrics_name}": metrics_value}, step=step + ) + except: + pass + + +def validate(model, test_loaders, step, context): + metrics_all = {} + for name_ds, test_loader in test_loaders.items(): + for i, batch in enumerate(test_loader): + with context: + batch["data"] = { + k: v.to(model.device) for k, v in batch["data"].items() + } + # remove temporal dimension of the dataloder, here is always 1! + batch["data"] = {k: v.squeeze(1) for k, v in batch["data"].items()} + batch["img_metas"] = [ + {k: v[0] for k, v in meta.items() if isinstance(v, list)} + for meta in batch["img_metas"] + ] + + preds = model(batch["data"], batch["img_metas"]) + + batch, _ = original_image(batch, preds=None) + test_loader.dataset.accumulate_metrics( + inputs=batch["data"], + preds=preds, + keyframe_idx=batch["img_metas"][0].get("keyframe_idx"), + ) + + barrier() + metrics_all[name_ds] = test_loader.dataset.get_evaluation() + + barrier() + if is_main_process(): + log_metrics(metrics_all=metrics_all, step=step) + return metrics_all diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/utils/visualization.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/utils/visualization.py new file mode 100644 index 0000000000000000000000000000000000000000..85beba496af2bd1f178d63b801e86a2abe011185 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/data_preprocessing/unidepth/utils/visualization.py @@ -0,0 +1,201 @@ +""" +Author: Luigi Piccinelli +Licensed under the CC-BY NC 4.0 license (http://creativecommons.org/licenses/by-nc/4.0/) +""" + +import os + +import matplotlib.pyplot as plt +import numpy as np +import torch +import wandb +from PIL import Image + +from unidepth.utils.misc import ssi_helper + + +def colorize( + value: np.ndarray, vmin: float = None, vmax: float = None, cmap: str = "magma_r" +): + # if already RGB, do nothing + if value.ndim > 2: + if value.shape[-1] > 1: + return value + value = value[..., 0] + invalid_mask = value < 0.0001 + # normalize + vmin = value.min() if vmin is None else vmin + vmax = value.max() if vmax is None else vmax + value = (value - vmin) / (vmax - vmin) # vmin..vmax + + # set color + cmapper = plt.get_cmap(cmap) + value = cmapper(value, bytes=True) # (nxmx4) + value[invalid_mask] = 0 + img = value[..., :3] + return img + + +def image_grid(imgs: list[np.ndarray], rows: int, cols: int) -> np.ndarray: + if not len(imgs): + return None + assert len(imgs) == rows * cols + h, w = imgs[0].shape[:2] + grid = Image.new("RGB", size=(cols * w, rows * h)) + + for i, img in enumerate(imgs): + grid.paste( + Image.fromarray(img.astype(np.uint8)).resize( + (w, h), resample=Image.BILINEAR + ), + box=(i % cols * w, i // cols * h), + ) + + return np.array(grid) + + +def get_pointcloud_from_rgbd( + image: np.array, + depth: np.array, + mask: np.ndarray, + intrinsic_matrix: np.array, + extrinsic_matrix: np.array = None, +): + depth = np.array(depth).squeeze() + mask = np.array(mask).squeeze() + # Mask the depth array + masked_depth = np.ma.masked_where(mask == False, depth) + # masked_depth = np.ma.masked_greater(masked_depth, 8000) + # Create idx array + idxs = np.indices(masked_depth.shape) + u_idxs = idxs[1] + v_idxs = idxs[0] + # Get only non-masked depth and idxs + z = masked_depth[~masked_depth.mask] + compressed_u_idxs = u_idxs[~masked_depth.mask] + compressed_v_idxs = v_idxs[~masked_depth.mask] + image = np.stack( + [image[..., i][~masked_depth.mask] for i in range(image.shape[-1])], axis=-1 + ) + + # Calculate local position of each point + # Apply vectorized math to depth using compressed arrays + cx = intrinsic_matrix[0, 2] + fx = intrinsic_matrix[0, 0] + x = (compressed_u_idxs - cx) * z / fx + cy = intrinsic_matrix[1, 2] + fy = intrinsic_matrix[1, 1] + # Flip y as we want +y pointing up not down + y = -((compressed_v_idxs - cy) * z / fy) + + # # Apply camera_matrix to pointcloud as to get the pointcloud in world coords + # if extrinsic_matrix is not None: + # # Calculate camera pose from extrinsic matrix + # camera_matrix = np.linalg.inv(extrinsic_matrix) + # # Create homogenous array of vectors by adding 4th entry of 1 + # # At the same time flip z as for eye space the camera is looking down the -z axis + # w = np.ones(z.shape) + # x_y_z_eye_hom = np.vstack((x, y, -z, w)) + # # Transform the points from eye space to world space + # x_y_z_world = np.dot(camera_matrix, x_y_z_eye_hom)[:3] + # return x_y_z_world.T + # else: + x_y_z_local = np.stack((x, y, z), axis=-1) + return np.concatenate([x_y_z_local, image], axis=-1) + + +def save_file_ply(xyz, rgb, pc_file): + if rgb.max() < 1.001: + rgb = rgb * 255.0 + rgb = rgb.astype(np.uint8) + # print(rgb) + with open(pc_file, "w") as f: + # headers + f.writelines( + [ + "ply\n" "format ascii 1.0\n", + "element vertex {}\n".format(xyz.shape[0]), + "property float x\n", + "property float y\n", + "property float z\n", + "property uchar red\n", + "property uchar green\n", + "property uchar blue\n", + "end_header\n", + ] + ) + + for i in range(xyz.shape[0]): + str_v = "{:10.6f} {:10.6f} {:10.6f} {:d} {:d} {:d}\n".format( + xyz[i, 0], xyz[i, 1], xyz[i, 2], rgb[i, 0], rgb[i, 1], rgb[i, 2] + ) + f.write(str_v) + + +# really awful fct... FIXME +def log_train_artifacts(rgbs, gts, preds, ds_name, step, infos={}): + rgbs = [ + (127.5 * (rgb + 1)) + .clip(0, 255) + .to(torch.uint8) + .cpu() + .detach() + .permute(1, 2, 0) + .numpy() + for rgb in rgbs + ] + + new_gts, new_preds = [], [] + if len(gts) > 0: + for i, gt in enumerate(gts): + scale, shift = ssi_helper( + gts[i][gts[i] > 0].cpu().detach(), preds[i][gts[i] > 0].cpu().detach() + ) + gt = gts[i].cpu().detach().squeeze().numpy() + pred = (preds[i].cpu().detach() * scale + shift).squeeze().numpy() + vmin = gt[gt > 0].min() if (gt > 0).any() else 0.0 + vmax = gt.max() if (gt > 0).any() else 0.1 + new_gts.append(colorize(gt, vmin=vmin, vmax=vmax)) + new_preds.append(colorize(pred, vmin=vmin, vmax=vmax)) + gts, preds = new_gts, new_preds + else: + preds = [ + colorize(pred.cpu().detach().squeeze().numpy(), 0.0, 80.0) + for i, pred in enumerate(preds) + ] + + num_additional, additionals = 0, [] + for name, info in infos.items(): + num_additional += 1 + if info.shape[1] == 3: + additionals.extend( + [ + (127.5 * (x + 1)) + .clip(0, 255) + .to(torch.uint8) + .cpu() + .detach() + .permute(1, 2, 0) + .numpy() + for x in info[:4] + ] + ) + else: + additionals.extend( + [ + colorize(x.cpu().detach().squeeze().numpy()) + for i, x in enumerate(info[:4]) + ] + ) + + num_rows = 2 + int(len(gts) > 0) + num_additional + artifacts_grid = image_grid( + [*rgbs, *gts, *preds, *additionals], num_rows, len(rgbs) + ) + try: + wandb.log({f"{ds_name}_training": [wandb.Image(artifacts_grid)]}, step=step) + except: + Image.fromarray(artifacts_grid).save( + os.path.join(os.environ["HOME"], "Workspace", f"art_grid{step}.png") + ) + print("Logging training images failed") diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/foundationpose_preprocess.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/foundationpose_preprocess.py new file mode 100644 index 0000000000000000000000000000000000000000..6104415e9e9ca5bf72e488bd805c125868abbee7 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/foundationpose_preprocess.py @@ -0,0 +1,35 @@ +import os +import cv2 +import numpy as np +import rembg +import kiui +import argparse +from rembg import remove + +def parse_args(): + parser = argparse.ArgumentParser() + parser.add_argument("--image_path", type=str, default="/path/to/oa3d/pose_inputs/test/elephant_rotated.png") + parser.add_argument("--output_dir", type=str, default="/path/to/oa3d/pose_inputs/test/") + return parser.parse_args() + + +if __name__ == "__main__": + args = parse_args() + image_path = args.image_path + output_dir = args.output_dir + output_dir = os.path.join(output_dir, "foundationpose_inputs") + + image = cv2.imread(image_path) + + mask_dir = os.path.join(output_dir, "masks") + rgb_dir = os.path.join(output_dir, "rgb") + os.makedirs(mask_dir, exist_ok=True) + os.makedirs(rgb_dir, exist_ok=True) + + rm_pred = remove(image) + mask_pred = rm_pred[..., -1] + mask_pred = np.stack((mask_pred, mask_pred, mask_pred), axis=-1) + cv2.imwrite(os.path.join(mask_dir, os.path.basename(image_path)), mask_pred) + + image = image * (mask_pred/255) + cv2.imwrite(os.path.join(rgb_dir, os.path.basename(image_path)), image) diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/.gitignore b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..cc59bdd934c1ca5e79be63449e4790c20fd31d36 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/.gitignore @@ -0,0 +1,158 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +.history +exp/ +*.py[cod] +*$py.class +# C extensions +*.so +BundleTrack/build +# Distribution / packaging +.Python +foundationpose/ +build/ +develop-eggs/ +*.zip +demo_data/* +dist/ +# *.png +# *.jpg +debug/ +weights/* +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +.vscode/ +wheels/ +wandb/ +*.blend1 +*.tar.* +*.zip +*.svg +sacred/ +artifacts/ +pip-wheel-metadata/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +demo_data/ +debug/ +coverage.xml +*.cover +demo_data/ +debug/ +weights/ +*.py,cover +.hypothesis/ +.pytest_cache/ +*.pth +weights/ +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache +cosypose/experiments + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# Datasets +data/ +logs/ +!BundleTrack/XMem/inference/data +run_used.yml \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/LICENSE b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..6704932cd8979da01a39360783279b9c4b506305 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/LICENSE @@ -0,0 +1,94 @@ +Copyright (c) 2022-Present, NVIDIA Corporation & affiliates. All rights reserved. + + +======================================================================= + +1. Definitions + +"Licensor" means any person or entity that distributes its Work. + +"Software" means the original work of authorship made available under +this License. + +"Work" means the Software and any additions to or derivative works of +the Software that are made available under this License. + +The terms "reproduce," "reproduction," "derivative works," and +"distribution" have the meaning as provided under U.S. copyright law; +provided, however, that for the purposes of this License, derivative +works shall not include works that remain separable from, or merely +link (or bind by name) to the interfaces of, the Work. + +Works, including the Software, are "made available" under this License +by including in or with the Work either (a) a copyright notice +referencing the applicability of this License to the Work, or (b) a +copy of this License. + +2. License Grants + + 2.1 Copyright Grant. Subject to the terms and conditions of this + License, each Licensor grants to you a perpetual, worldwide, + non-exclusive, royalty-free, copyright license to reproduce, + prepare derivative works of, publicly display, publicly perform, + sublicense and distribute its Work and any resulting derivative + works in any form. + +3. Limitations + + 3.1 Redistribution. You may reproduce or distribute the Work only + if (a) you do so under this License, (b) you include a complete + copy of this License with your distribution, and (c) you retain + without modification any copyright, patent, trademark, or + attribution notices that are present in the Work. + + 3.2 Derivative Works. You may specify that additional or different + terms apply to the use, reproduction, and distribution of your + derivative works of the Work ("Your Terms") only if (a) Your Terms + provide that the use limitation in Section 3.3 applies to your + derivative works, and (b) you identify the specific derivative + works that are subject to Your Terms. Notwithstanding Your Terms, + this License (including the redistribution requirements in Section + 3.1) will continue to apply to the Work itself. + + 3.3 Use Limitation. The Work and any derivative works thereof only + may be used or intended for use non-commercially. Notwithstanding + the foregoing, NVIDIA and its affiliates may use the Work and any + derivative works commercially. As used herein, "non-commercially" + means for research or evaluation purposes only. + + 3.4 Patent Claims. If you bring or threaten to bring a patent claim + against any Licensor (including any claim, cross-claim or + counterclaim in a lawsuit) to enforce any patents that you allege + are infringed by any Work, then your rights under this License from + such Licensor (including the grant in Section 2.1) will terminate + immediately. + + 3.5 Trademarks. This License does not grant any rights to use any + Licensor�s or its affiliates� names, logos, or trademarks, except + as necessary to reproduce the notices described in this License. + + 3.6 Termination. If you violate any term of this License, then your + rights under this License (including the grant in Section 2.1) will + terminate immediately. + +4. Disclaimer of Warranty. + +THE WORK IS PROVIDED "AS IS" WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WARRANTIES OR CONDITIONS OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE OR +NON-INFRINGEMENT. YOU BEAR THE RISK OF UNDERTAKING ANY ACTIVITIES UNDER +THIS LICENSE. + +5. Limitation of Liability. + +EXCEPT AS PROHIBITED BY APPLICABLE LAW, IN NO EVENT AND UNDER NO LEGAL +THEORY, WHETHER IN TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE +SHALL ANY LICENSOR BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY DIRECT, +INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF +OR RELATED TO THIS LICENSE, THE USE OR INABILITY TO USE THE WORK +(INCLUDING BUT NOT LIMITED TO LOSS OF GOODWILL, BUSINESS INTERRUPTION, +LOST PROFITS OR DATA, COMPUTER FAILURE OR MALFUNCTION, OR ANY OTHER +COMMERCIAL DAMAGES OR LOSSES), EVEN IF THE LICENSOR HAS BEEN ADVISED OF +THE POSSIBILITY OF SUCH DAMAGES. + +======================================================================= diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/Utils.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/Utils.py new file mode 100644 index 0000000000000000000000000000000000000000..47807fdba837ad9ef4bbd3cf6d6425e649ed5b64 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/Utils.py @@ -0,0 +1,1029 @@ +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. + + +import os, sys, time,torch,pickle,trimesh,itertools,pdb,zipfile,datetime,imageio,gzip,logging,joblib,importlib,uuid,signal,multiprocessing,psutil,subprocess,tarfile,scipy,argparse +from pytorch3d.transforms import so3_log_map,so3_exp_map,se3_exp_map,se3_log_map,matrix_to_axis_angle,matrix_to_euler_angles,euler_angles_to_matrix, rotation_6d_to_matrix +from pytorch3d.renderer import FoVPerspectiveCameras, PerspectiveCameras, look_at_view_transform, look_at_rotation, RasterizationSettings, MeshRenderer, MeshRasterizer, BlendParams, SoftSilhouetteShader, HardPhongShader, PointLights, TexturesVertex +from pytorch3d.renderer.mesh.rasterize_meshes import barycentric_coordinates +from pytorch3d.renderer.mesh.shader import SoftDepthShader, HardFlatShader +from pytorch3d.renderer.mesh.textures import Textures +from pytorch3d.structures import Meshes +from scipy.interpolate import griddata +import nvdiffrast.torch as dr +import torch.nn.functional as F +import torchvision +import torch.nn as nn +from functools import partial +import pandas as pd +import open3d as o3d +from uuid import uuid4 +import cv2 +from PIL import Image +import numpy as np +from collections import defaultdict +import multiprocessing as mp +import matplotlib.pyplot as plt +import math,glob,re,copy +from transformations import * +from scipy.spatial import cKDTree +from collections import OrderedDict +import ruamel.yaml +yaml = ruamel.yaml.YAML() +code_dir = os.path.dirname(os.path.realpath(__file__)) +sys.path.append(code_dir) +# sys.path.append(f"{code_dir}/mycpp/build") +try: + import kornia +except: + kornia = None +try: + import mycpp.build.mycpp as mycpp +except: + mycpp = None +try: + from bundlesdf.mycuda import common +except: + common = None +try: + import warp as wp + wp.init() +except: + wp = None +enable_timer = 0 + +def NestDict(): + return defaultdict(NestDict) + +to8b = lambda x : (255*np.clip(x,0,1)).astype(np.uint8) + +BAD_DEPTH = 99 +BAD_COLOR = 0 + +glcam_in_cvcam = np.array([[1,0,0,0], + [0,-1,0,0], + [0,0,-1,0], + [0,0,0,1]]).astype(float) + +COLOR_MAP=np.array([[0, 0, 0], #Ignore + [128,0,0], #Background + [0,128,0], #Wall + [128,128,0], #Floor + [0,0,128], #Ceiling + [128,0,128], #Table + [0,128,128], #Chair + [128,128,128], #Window + [64,0,0], #Door + [192,0,0], #Monitor + [64, 128, 0], # 11th + [192, 0, 128], + [64, 128, 128], + [192, 128, 128], + [0, 64, 0], + [128, 64, 0], + [0, 192, 0], + [128, 192, 0], + ]) + + +def set_logging_format(level=logging.INFO): + importlib.reload(logging) + FORMAT = '[%(funcName)s()] %(message)s' + logging.basicConfig(level=level, format=FORMAT) + +set_logging_format() + + + + +def make_mesh_tensors(mesh, device='cuda', max_tex_size=None): + mesh_tensors = {} + if isinstance(mesh.visual, trimesh.visual.texture.TextureVisuals): + # img = np.array(mesh.visual.material.image.convert('RGB')) + img = np.array(mesh.visual.material.baseColorTexture.convert('RGB')) + img = img[...,:3] + if max_tex_size is not None: + max_size = max(img.shape[0], img.shape[1]) + if max_size>max_tex_size: + scale = 1/max_size * max_tex_size + img = cv2.resize(img, fx=scale, fy=scale, dsize=None) + mesh_tensors['tex'] = torch.as_tensor(img, device=device, dtype=torch.float)[None]/255.0 + mesh_tensors['uv_idx'] = torch.as_tensor(mesh.faces, device=device, dtype=torch.int) + uv = torch.as_tensor(mesh.visual.uv, device=device, dtype=torch.float) + uv[:,1] = 1 - uv[:,1] + mesh_tensors['uv'] = uv + else: + if mesh.visual.vertex_colors is None: + logging.info(f"WARN: mesh doesn't have vertex_colors, assigning a pure color") + mesh.visual.vertex_colors = np.tile(np.array([128,128,128]).reshape(1,3), (len(mesh.vertices), 1)) + mesh_tensors['vertex_color'] = torch.as_tensor(mesh.visual.vertex_colors[...,:3], device=device, dtype=torch.float)/255.0 + + mesh_tensors.update({ + 'pos': torch.tensor(mesh.vertices, device=device, dtype=torch.float), + 'faces': torch.tensor(mesh.faces, device=device, dtype=torch.int), + 'vnormals': torch.tensor(mesh.vertex_normals, device=device, dtype=torch.float), + }) + return mesh_tensors + + +def nvdiffrast_render(K=None, H=None, W=None, ob_in_cams=None, glctx=None, context='cuda', get_normal=False, mesh_tensors=None, mesh=None, projection_mat=None, bbox2d=None, output_size=None, use_light=False, light_color=None, light_dir=np.array([0,0,1]), light_pos=np.array([0,0,0]), w_ambient=0.8, w_diffuse=0.5, extra={}): + '''Just plain rendering, not support any gradient + @K: (3,3) np array + @ob_in_cams: (N,4,4) torch tensor, openCV camera + @projection_mat: np array (4,4) + @output_size: (height, width) + @bbox2d: (N,4) (umin,vmin,umax,vmax) if only roi need to render. + @light_dir: in cam space + @light_pos: in cam space + ''' + if glctx is None: + if context == 'gl': + glctx = dr.RasterizeGLContext() + elif context=='cuda': + glctx = dr.RasterizeCudaContext() + else: + raise NotImplementedError + logging.info("created context") + + if mesh_tensors is None: + mesh_tensors = make_mesh_tensors(mesh) + pos = mesh_tensors['pos'] + vnormals = mesh_tensors['vnormals'] + pos_idx = mesh_tensors['faces'] + has_tex = 'tex' in mesh_tensors + + ob_in_glcams = torch.tensor(glcam_in_cvcam, device='cuda', dtype=torch.float)[None]@ob_in_cams + if projection_mat is None: + projection_mat = projection_matrix_from_intrinsics(K, height=H, width=W, znear=0.001, zfar=100) + projection_mat = torch.as_tensor(projection_mat.reshape(-1,4,4), device='cuda', dtype=torch.float) + mtx = projection_mat@ob_in_glcams + + if output_size is None: + output_size = np.asarray([H,W]) + + pts_cam = transform_pts(pos, ob_in_cams) + pos_homo = to_homo_torch(pos) + pos_clip = (mtx[:,None]@pos_homo[None,...,None])[...,0] + if bbox2d is not None: + l = bbox2d[:,0] + t = H-bbox2d[:,1] + r = bbox2d[:,2] + b = H-bbox2d[:,3] + tf = torch.eye(4, dtype=torch.float, device='cuda').reshape(1,4,4).expand(len(ob_in_cams),4,4).contiguous() + tf[:,0,0] = W/(r-l) + tf[:,1,1] = H/(t-b) + tf[:,3,0] = (W-r-l)/(r-l) + tf[:,3,1] = (H-t-b)/(t-b) + pos_clip = pos_clip@tf + rast_out, _ = dr.rasterize(glctx, pos_clip, pos_idx, resolution=np.asarray(output_size)) + xyz_map, _ = dr.interpolate(pts_cam, rast_out, pos_idx) + depth = xyz_map[...,2] + if has_tex: + texc, _ = dr.interpolate(mesh_tensors['uv'], rast_out, mesh_tensors['uv_idx']) + color = dr.texture(mesh_tensors['tex'], texc, filter_mode='linear') + else: + color, _ = dr.interpolate(mesh_tensors['vertex_color'], rast_out, pos_idx) + + if use_light: + get_normal = True + if get_normal: + vnormals_cam = transform_dirs(vnormals, ob_in_cams) + normal_map, _ = dr.interpolate(vnormals_cam, rast_out, pos_idx) + normal_map = F.normalize(normal_map, dim=-1) + normal_map = torch.flip(normal_map, dims=[1]) + else: + normal_map = None + + if use_light: + if light_dir is not None: + light_dir_neg = -torch.as_tensor(light_dir, dtype=torch.float, device='cuda') + else: + light_dir_neg = torch.as_tensor(light_pos, dtype=torch.float, device='cuda').reshape(1,1,3) - pts_cam + diffuse_intensity = (F.normalize(vnormals_cam, dim=-1) * F.normalize(light_dir_neg, dim=-1)).sum(dim=-1).clip(0, 1)[...,None] + diffuse_intensity_map, _ = dr.interpolate(diffuse_intensity, rast_out, pos_idx) # (N_pose, H, W, 1) + if light_color is None: + light_color = color + else: + light_color = torch.as_tensor(light_color, device='cuda', dtype=torch.float) + color = color*w_ambient + diffuse_intensity_map*light_color*w_diffuse + + color = color.clip(0,1) + color = color * torch.clamp(rast_out[..., -1:], 0, 1) # Mask out background using alpha + color = torch.flip(color, dims=[1]) # Flip Y coordinates + depth = torch.flip(depth, dims=[1]) + extra['xyz_map'] = torch.flip(xyz_map, dims=[1]) + return color, depth, normal_map + + +def set_seed(random_seed): + import torch,random + np.random.seed(random_seed) + random.seed(random_seed) + torch.manual_seed(random_seed) + torch.cuda.manual_seed_all(random_seed) + torch.backends.cudnn.deterministic = True + torch.backends.cudnn.benchmark = False + + +def add_err(pred,gt,model_pts,symetry_tfs=np.eye(4)[None]): + """ + Average Distance of Model Points for objects with no indistinguishable views + - by Hinterstoisser et al. (ACCV 2012). + """ + pred_pts = transform_pts(model_pts, pred) + gt_pts = transform_pts(model_pts, gt) + e = np.linalg.norm(pred_pts - gt_pts, axis=-1).mean() + return e + +def adds_err(pred,gt,model_pts): + """ + @pred: 4x4 mat + @gt: + @model: (N,3) + """ + pred_pts = transform_pts(model_pts, pred) + gt_pts = transform_pts(model_pts, gt) + nn_index = cKDTree(pred_pts) + nn_dists, _ = nn_index.query(gt_pts, k=1, workers=-1) + e = nn_dists.mean() + return e + +def compute_auc_sklearn(errs, max_val=0.1, step=0.001): + from sklearn import metrics + errs = np.sort(np.array(errs)) + X = np.arange(0, max_val+step, step) + Y = np.ones(len(X)) + for i,x in enumerate(X): + y = (errs<=x).sum()/len(errs) + Y[i] = y + if y>=1: + break + auc = metrics.auc(X, Y) / (max_val*1) + return auc + + + +def normalizeRotation(pose): + '''Assume no shear case + ''' + new_pose = pose.copy() + scales = np.linalg.norm(pose[:3,:3],axis=0) + new_pose[:3,:3] /= scales.reshape(1,3) + return new_pose + + + +def toOpen3dCloud(points,colors=None,normals=None): + cloud = o3d.geometry.PointCloud() + cloud.points = o3d.utility.Vector3dVector(points.astype(np.float64)) + if colors is not None: + if colors.max()>1: + colors = colors/255.0 + cloud.colors = o3d.utility.Vector3dVector(colors.astype(np.float64)) + if normals is not None: + cloud.normals = o3d.utility.Vector3dVector(normals.astype(np.float64)) + return cloud + + + +def make_grid_image(imgs, nrow, padding=5, pad_value=255): + ''' + @imgs: (B,H,W,C) np array + @nrow: num of images per row + ''' + grid = torchvision.utils.make_grid(torch.as_tensor(np.asarray(imgs)).permute(0,3,1,2), nrow=nrow, padding=padding, pad_value=pad_value) + grid = grid.permute(1,2,0).contiguous().data.cpu().numpy().astype(np.uint8) + return grid + + +if wp is not None: + @wp.kernel(enable_backward=False) + def bilateral_filter_depth_kernel(depth:wp.array(dtype=float, ndim=2), out:wp.array(dtype=float, ndim=2), radius:int, zfar:float, sigmaD:float, sigmaR:float): + h,w = wp.tid() + H = depth.shape[0] + W = depth.shape[1] + if w>=W or h>=H: + return + out[h,w] = 0.0 + mean_depth = float(0.0) + num_valid = int(0) + for u in range(w-radius, w+radius+1): + if u<0 or u>=W: + continue + for v in range(h-radius, h+radius+1): + if v<0 or v>=H: + continue + cur_depth = depth[v,u] + if cur_depth>=0.001 and cur_depth=W: + continue + for v in range(h-radius, h+radius+1): + if v<0 or v>=H: + continue + cur_depth = depth[v,u] + if cur_depth>=0.001 and cur_depth0 and num_valid>0: + out[h,w] = sum/sum_weight + + def bilateral_filter_depth(depth, radius=2, zfar=100, sigmaD=2, sigmaR=100000, device='cuda'): + if isinstance(depth, np.ndarray): + depth_wp = wp.array(depth, dtype=float, device=device) + else: + depth_wp = wp.from_torch(depth) + out_wp = wp.zeros(depth.shape, dtype=float, device=device) + wp.launch(kernel=bilateral_filter_depth_kernel, device=device, dim=[depth.shape[0], depth.shape[1]], inputs=[depth_wp, out_wp, radius, zfar, sigmaD, sigmaR]) + depth_out = wp.to_torch(out_wp) + + if isinstance(depth, np.ndarray): + depth_out = depth_out.data.cpu().numpy() + return depth_out + + + @wp.kernel(enable_backward=False) + def erode_depth_kernel(depth:wp.array(dtype=float, ndim=2), out:wp.array(dtype=float, ndim=2), radius:int, depth_diff_thres:float, ratio_thres:float, zfar:float): + h,w = wp.tid() + H = depth.shape[0] + W = depth.shape[1] + if w>=W or h>=H: + return + d_ori = depth[h,w] + if d_ori<0.001 or d_ori>=zfar: + out[h,w] = 0.0 + bad_cnt = float(0) + total = float(0) + for u in range(w-radius, w+radius+1): + if u<0 or u>=W: + continue + for v in range(h-radius, h+radius+1): + if v<0 or v>=H: + continue + cur_depth = depth[v,u] + total += 1.0 + if cur_depth<0.001 or cur_depth>=zfar or abs(cur_depth-d_ori)>depth_diff_thres: + bad_cnt += 1.0 + if bad_cnt/total>ratio_thres: + out[h,w] = 0.0 + else: + out[h,w] = d_ori + + + def erode_depth(depth, radius=2, depth_diff_thres=0.001, ratio_thres=0.8, zfar=100, device='cuda'): + depth_wp = wp.from_torch(torch.as_tensor(depth, dtype=torch.float, device=device)) + out_wp = wp.zeros(depth.shape, dtype=float, device=device) + wp.launch(kernel=erode_depth_kernel, device=device, dim=[depth.shape[0], depth.shape[1]], inputs=[depth_wp, out_wp, radius, depth_diff_thres, ratio_thres, zfar],) + depth_out = wp.to_torch(out_wp) + + if isinstance(depth, np.ndarray): + depth_out = depth_out.data.cpu().numpy() + return depth_out + + + +def depth2xyzmap(depth, K, uvs=None): + invalid_mask = (depth<0.001) + H,W = depth.shape[:2] + if uvs is None: + vs,us = np.meshgrid(np.arange(0,H),np.arange(0,W), sparse=False, indexing='ij') + vs = vs.reshape(-1) + us = us.reshape(-1) + else: + uvs = uvs.round().astype(int) + us = uvs[:,0] + vs = uvs[:,1] + zs = depth[vs,us] + xs = (us-K[0,2])*zs/K[0,0] + ys = (vs-K[1,2])*zs/K[1,1] + pts = np.stack((xs.reshape(-1),ys.reshape(-1),zs.reshape(-1)), 1) #(N,3) + xyz_map = np.zeros((H,W,3), dtype=np.float32) + # xyz_map = np.zeros((H,W,3), dtype=np.int16) + # for v in range(depth.shape[0]): + # for u in range(depth.shape[1]): + # z = depth[v, u] + # if z > 0: # Check if depth is valid + # x = (u - K[0, 2]) * z / K[0, 0] + # y = (v - K[1, 2]) * z / K[1, 1] + # xyz_map[v, u] = (x, y, z) + xyz_map[vs,us] = pts + xyz_map[invalid_mask] = 0 + return xyz_map + + +def depth2xyzmap_batch(depths, Ks, zfar): + ''' + @depths: torch tensor (B,H,W) + @Ks: torch tensor (B,3,3) + ''' + bs = depths.shape[0] + invalid_mask = (depths<0.001) | (depths>zfar) + H,W = depths.shape[-2:] + vs,us = torch.meshgrid(torch.arange(0,H),torch.arange(0,W), indexing='ij') + vs = vs.reshape(-1).float().cuda()[None].expand(bs,-1) + us = us.reshape(-1).float().cuda()[None].expand(bs,-1) + zs = depths.reshape(bs,-1) + Ks = Ks[:,None].expand(bs,zs.shape[-1],3,3) + xs = (us-Ks[...,0,2])*zs/Ks[...,0,0] #(B,N) + ys = (vs-Ks[...,1,2])*zs/Ks[...,1,1] + pts = torch.stack([xs,ys,zs], dim=-1) #(B,N,3) + xyz_maps = pts.reshape(bs,H,W,3) + xyz_maps[invalid_mask] = 0 + return xyz_maps + + + +def rle_to_mask(rle: dict) -> np.ndarray: + """Compute a binary mask from an uncompressed RLE.""" + h, w = rle["size"] + mask = np.empty(h * w, dtype=bool) + idx = 0 + parity = False + for count in rle["counts"]: + mask[idx : idx + count] = parity + idx += count + parity ^= True + mask = mask.reshape(w, h) + return mask.transpose() # Put in C order + + +def depth_to_vis(depth, zmin=None, zmax=None, mode='rgb', inverse=True): + if zmin is None: + zmin = depth.min() + if zmax is None: + zmax = depth.max() + + if inverse: + invalid = depth<0.001 + vis = zmin/(depth+1e-8) + vis[invalid] = 0 + else: + depth = depth.clip(zmin, zmax) + invalid = (depth==zmin) | (depth==zmax) + vis = (depth-zmin)/(zmax-zmin) + vis[invalid] = 1 + + if mode=='gray': + vis = (vis*255).clip(0, 255).astype(np.uint8) + elif mode=='rgb': + vis = cv2.applyColorMap((vis*255).astype(np.uint8), cv2.COLORMAP_JET)[...,::-1] + else: + raise RuntimeError + + return vis + + + +def sample_views_icosphere(n_views, subdivisions=None, radius=1): + if subdivisions is not None: + mesh = trimesh.creation.icosphere(subdivisions=subdivisions, radius=radius) + else: + subdivision = 1 + while 1: + mesh = trimesh.creation.icosphere(subdivisions=subdivision, radius=radius) + if mesh.vertices.shape[0]>=n_views: + break + subdivision += 1 + cam_in_obs = np.tile(np.eye(4)[None], (len(mesh.vertices),1,1)) + cam_in_obs[:,:3,3] = mesh.vertices + up = np.array([0,0,1]) + z_axis = -cam_in_obs[:,:3,3] #(N,3) + z_axis /= np.linalg.norm(z_axis, axis=-1).reshape(-1,1) + x_axis = np.cross(up.reshape(1,3), z_axis) + invalid = (x_axis==0).all(axis=-1) + x_axis[invalid] = [1,0,0] + x_axis /= np.linalg.norm(x_axis, axis=-1).reshape(-1,1) + y_axis = np.cross(z_axis, x_axis) + y_axis /= np.linalg.norm(y_axis, axis=-1).reshape(-1,1) + cam_in_obs[:,:3,0] = x_axis + cam_in_obs[:,:3,1] = y_axis + cam_in_obs[:,:3,2] = z_axis + return cam_in_obs + + + +def to_homo(pts): + ''' + @pts: (N,3 or 2) will homogeneliaze the last dimension + ''' + assert len(pts.shape)==2, f'pts.shape: {pts.shape}' + homo = np.concatenate((pts, np.ones((pts.shape[0],1))),axis=-1) + return homo + + +def to_homo_torch(pts): + ''' + @pts: shape can be (...,N,3 or 2) or (N,3) will homogeneliaze the last dimension + ''' + ones = torch.ones((*pts.shape[:-1],1), dtype=torch.float, device=pts.device) + homo = torch.cat((pts, ones),dim=-1) + return homo + + +def transform_pts(pts,tf): + """Transform 2d or 3d points + @pts: (...,N_pts,3) + @tf: (...,4,4) + """ + if len(tf.shape)>=3 and tf.shape[-3]!=pts.shape[-2]: + tf = tf[...,None,:,:] + return (tf[...,:-1,:-1]@pts[...,None] + tf[...,:-1,-1:])[...,0] + + +def transform_dirs(dirs,tf): + """ + @dirs: (...,3) + @tf: (...,4,4) + """ + if len(tf.shape)>=3 and tf.shape[-3]!=dirs.shape[-2]: + tf = tf[...,None,:,:] + return (tf[...,:3,:3]@dirs[...,None])[...,0] + + + +def random_direction(): + '''https://stackoverflow.com/questions/33976911/generate-a-random-sample-of-points-distributed-on-the-surface-of-a-unit-sphere + ''' + vec = np.random.randn(3).reshape(3) + vec /= np.linalg.norm(vec) + return vec + + + +def compute_mesh_diameter(model_pts=None, mesh=None, n_sample=1000): + from sklearn.decomposition import TruncatedSVD + if mesh is not None: + u, s, vh = scipy.linalg.svd(mesh.vertices, full_matrices=False) + pts = u@s + diameter = np.linalg.norm(pts.max(axis=0)-pts.min(axis=0)) + return float(diameter) + + if n_sample is None: + pts = model_pts + else: + ids = np.random.choice(len(model_pts), size=min(n_sample, len(model_pts)), replace=False) + pts = model_pts[ids] + dists = np.linalg.norm(pts[None]-pts[:,None], axis=-1) + diameter = dists.max() + return diameter + + +def compute_crop_window_tf_batch(pts=None, H=None, W=None, poses=None, K=None, crop_ratio=1.4, out_size=None, rgb=None, uvs=None, method='min_box', mesh_diameter=None): + '''Project the points and find the cropping transform + @pts: (N,3) + @poses: (B,4,4) tensor + @min_box: min_box/min_circle + @scale: scale to apply to the tightly enclosing roi + ''' + def compute_tf_batch(left, right, top, bottom): + B = len(left) + left = left.round() + right = right.round() + top = top.round() + bottom = bottom.round() + + tf = torch.eye(3)[None].expand(B,-1,-1).contiguous() + tf[:,0,2] = -left + tf[:,1,2] = -top + new_tf = torch.eye(3)[None].expand(B,-1,-1).contiguous() + new_tf[:,0,0] = out_size[0]/(right-left) + new_tf[:,1,1] = out_size[1]/(bottom-top) + tf = new_tf@tf + return tf + + B = len(poses) + torch.set_default_tensor_type('torch.cuda.FloatTensor') + if method=='box_3d': + radius = mesh_diameter*crop_ratio/2 + offsets = torch.tensor([0,0,0, + radius,0,0, + -radius,0,0, + 0,radius,0, + 0,-radius,0]).reshape(-1,3) + pts = poses[:,:3,3].reshape(-1,1,3)+offsets.reshape(1,-1,3) + K = torch.as_tensor(K) + projected = (K@pts.reshape(-1,3).T).T + uvs = projected[:,:2]/projected[:,2:3] + uvs = uvs.reshape(B, -1, 2) + center = uvs[:,0] #(B,2) + radius = torch.abs(uvs-center.reshape(-1,1,2)).reshape(B,-1).max(axis=-1)[0].reshape(-1) #(B) + left = center[:,0]-radius + right = center[:,0]+radius + top = center[:,1]-radius + bottom = center[:,1]+radius + tfs = compute_tf_batch(left, right, top, bottom) + return tfs + + else: + raise RuntimeError + + return tf + + + +def cv_draw_text(img,text,uv_top_left,color=(255, 255, 255),fontScale=0.5,thickness=1,fontFace=cv2.FONT_HERSHEY_SIMPLEX,outline_color=None,line_spacing=1.5): + H,W = img.shape[:2] + uv_top_left = np.array(uv_top_left, dtype=float) + assert uv_top_left.shape == (2,) + + for line in text.splitlines(): + (w, h), _ = cv2.getTextSize(text=line,fontFace=fontFace,fontScale=fontScale,thickness=thickness,) + uv_bottom_left_i = uv_top_left + [0, h] + + ############# Ensure inside image + while uv_bottom_left_i[0]<0: + uv_bottom_left_i[0] += 1 + while uv_bottom_left_i[0]+w>=W: + uv_bottom_left_i[0] -= 1 + while uv_bottom_left_i[1]>=H: + uv_bottom_left_i[1] -= 1 + while uv_bottom_left_i[1]-h<0: + uv_bottom_left_i[1] += 1 + + org = tuple(uv_bottom_left_i.astype(int)) + + if outline_color is not None: + cv2.putText(img,text=line,org=org,fontFace=fontFace,fontScale=fontScale,color=outline_color,thickness=thickness,lineType=cv2.LINE_AA,) + cv2.putText(img,text=line,org=org,fontFace=fontFace,fontScale=fontScale,color=color,thickness=thickness,lineType=cv2.LINE_AA,) + uv_top_left[1] = uv_bottom_left_i[1]-h+h*line_spacing + return img + + +def trimesh_add_pure_colored_texture(mesh, color=np.array([255,255,255]), resolution=5): + tex_img = np.tile(color.reshape(1,1,3), (resolution, resolution, 1)).astype(np.uint8) + mesh = mesh.unwrap() + mesh.visual = trimesh.visual.texture.TextureVisuals(uv=mesh.visual.uv,image=Image.fromarray(tex_img)) + return mesh + + + + +def project_3d_to_2d(pt,K,ob_in_cam): + pt = pt.reshape(4,1) + projected = K @ ((ob_in_cam@pt)[:3,:]) + projected = projected.reshape(-1) + projected = projected/projected[2] + return projected.reshape(-1)[:2].round().astype(int) + + +def draw_xyz_axis(color, ob_in_cam, scale=0.1, K=np.eye(3), thickness=3, transparency=0,is_input_rgb=False): + ''' + @color: BGR + ''' + if is_input_rgb: + color = cv2.cvtColor(color,cv2.COLOR_RGB2BGR) + xx = np.array([1,0,0,1]).astype(float) + yy = np.array([0,1,0,1]).astype(float) + zz = np.array([0,0,1,1]).astype(float) + xx[:3] = xx[:3]*scale + yy[:3] = yy[:3]*scale + zz[:3] = zz[:3]*scale + origin = tuple(project_3d_to_2d(np.array([0,0,0,1]), K, ob_in_cam)) + xx = tuple(project_3d_to_2d(xx, K, ob_in_cam)) + yy = tuple(project_3d_to_2d(yy, K, ob_in_cam)) + zz = tuple(project_3d_to_2d(zz, K, ob_in_cam)) + line_type = cv2.LINE_AA + arrow_len = 0 + tmp = color.copy() + tmp1 = tmp.copy() + tmp1 = cv2.arrowedLine(tmp1, origin, xx, color=(0,0,255), thickness=thickness,line_type=line_type, tipLength=arrow_len) + mask = np.linalg.norm(tmp1-tmp, axis=-1)>0 + tmp[mask] = tmp[mask]*transparency + tmp1[mask]*(1-transparency) + tmp1 = tmp.copy() + tmp1 = cv2.arrowedLine(tmp1, origin, yy, color=(0,255,0), thickness=thickness,line_type=line_type, tipLength=arrow_len) + mask = np.linalg.norm(tmp1-tmp, axis=-1)>0 + tmp[mask] = tmp[mask]*transparency + tmp1[mask]*(1-transparency) + tmp1 = tmp.copy() + tmp1 = cv2.arrowedLine(tmp1, origin, zz, color=(255,0,0), thickness=thickness,line_type=line_type, tipLength=arrow_len) + mask = np.linalg.norm(tmp1-tmp, axis=-1)>0 + tmp[mask] = tmp[mask]*transparency + tmp1[mask]*(1-transparency) + tmp = tmp.astype(np.uint8) + if is_input_rgb: + tmp = cv2.cvtColor(tmp,cv2.COLOR_BGR2RGB) + + return tmp + + +def draw_posed_3d_box(K, img, ob_in_cam, bbox, line_color=(0,255,0), linewidth=2): + '''Revised from 6pack dataset/inference_dataset_nocs.py::projection + @bbox: (2,3) min/max + @line_color: RGB + ''' + min_xyz = bbox.min(axis=0) + xmin, ymin, zmin = min_xyz + max_xyz = bbox.max(axis=0) + xmax, ymax, zmax = max_xyz + + def draw_line3d(start,end,img): + pts = np.stack((start,end),axis=0).reshape(-1,3) + pts = (ob_in_cam@to_homo(pts).T).T[:,:3] #(2,3) + projected = (K@pts.T).T + uv = np.round(projected[:,:2]/projected[:,2].reshape(-1,1)).astype(int) #(2,2) + img = cv2.line(img, uv[0].tolist(), uv[1].tolist(), color=line_color, thickness=linewidth, lineType=cv2.LINE_AA) + return img + + for y in [ymin,ymax]: + for z in [zmin,zmax]: + start = np.array([xmin,y,z]) + end = start+np.array([xmax-xmin,0,0]) + img = draw_line3d(start,end,img) + + for x in [xmin,xmax]: + for z in [zmin,zmax]: + start = np.array([x,ymin,z]) + end = start+np.array([0,ymax-ymin,0]) + img = draw_line3d(start,end,img) + + for x in [xmin,xmax]: + for y in [ymin,ymax]: + start = np.array([x,y,zmin]) + end = start+np.array([0,0,zmax-zmin]) + img = draw_line3d(start,end,img) + + return img + + +def projection_matrix_from_intrinsics(K, height, width, znear, zfar, window_coords='y_down'): + """Conversion of Hartley-Zisserman intrinsic matrix to OpenGL proj. matrix. + + Ref: + 1) https://strawlab.org/2011/11/05/augmented-reality-with-OpenGL + 2) https://github.com/strawlab/opengl-hz/blob/master/src/calib_test_utils.py + + :param K: 3x3 ndarray with the intrinsic camera matrix. + :param x0 The X coordinate of the camera image origin (typically 0). + :param y0: The Y coordinate of the camera image origin (typically 0). + :param w: Image width. + :param h: Image height. + :param nc: Near clipping plane. + :param fc: Far clipping plane. + :param window_coords: 'y_up' or 'y_down'. + :return: 4x4 ndarray with the OpenGL projection matrix. + """ + x0 = 0 + y0 = 0 + w = width + h = height + nc = znear + fc = zfar + + depth = float(fc - nc) + q = -(fc + nc) / depth + qn = -2 * (fc * nc) / depth + + # Draw our images upside down, so that all the pixel-based coordinate + # systems are the same. + if window_coords == 'y_up': + proj = np.array([ + [2 * K[0, 0] / w, -2 * K[0, 1] / w, (-2 * K[0, 2] + w + 2 * x0) / w, 0], + [0, -2 * K[1, 1] / h, (-2 * K[1, 2] + h + 2 * y0) / h, 0], + [0, 0, q, qn], # Sets near and far planes (glPerspective). + [0, 0, -1, 0] + ]) + + # Draw the images upright and modify the projection matrix so that OpenGL + # will generate window coords that compensate for the flipped image coords. + elif window_coords == 'y_down': + proj = np.array([ + [2 * K[0, 0] / w, -2 * K[0, 1] / w, (-2 * K[0, 2] + w + 2 * x0) / w, 0], + [0, 2 * K[1, 1] / h, (2 * K[1, 2] - h + 2 * y0) / h, 0], + [0, 0, q, qn], # Sets near and far planes (glPerspective). + [0, 0, -1, 0] + ]) + else: + raise NotImplementedError + + return proj + + + +def symmetry_tfs_from_info(info, rot_angle_discrete=5): + symmetry_tfs = [np.eye(4)] + if 'symmetries_discrete' in info: + tfs = np.array(info['symmetries_discrete']).reshape(-1,4,4) + tfs[...,:3,3] *= 0.001 + symmetry_tfs = [np.eye(4)] + symmetry_tfs += list(tfs) + if 'symmetries_continuous' in info: + axis = np.array(info['symmetries_continuous'][0]['axis']).reshape(3) + offset = info['symmetries_continuous'][0]['offset'] + rxs = [0] + rys = [0] + rzs = [0] + if axis[0]>0: + rxs = np.arange(0,360,rot_angle_discrete)/180.0*np.pi + elif axis[1]>0: + rys = np.arange(0,360,rot_angle_discrete)/180.0*np.pi + elif axis[2]>0: + rzs = np.arange(0,360,rot_angle_discrete)/180.0*np.pi + for rx in rxs: + for ry in rys: + for rz in rzs: + tf = euler_matrix(rx, ry, rz) + tf[:3,3] = offset + symmetry_tfs.append(tf) + if len(symmetry_tfs)==0: + symmetry_tfs = [np.eye(4)] + symmetry_tfs = np.array(symmetry_tfs) + return symmetry_tfs + + + +def pose_to_egocentric_delta_pose(A_in_cam, B_in_cam): + '''Used for Pose Refinement. Given the object's two poses in camera, convert them to relative poses in camera's egocentric view + @A_in_cam: (B,4,4) torch tensor + ''' + trans_delta = B_in_cam[:,:3,3] - A_in_cam[:,:3,3] + rot_mat_delta = B_in_cam[:,:3,:3]@A_in_cam[:,:3,:3].permute(0,2,1) + return trans_delta, rot_mat_delta + + + +def egocentric_delta_pose_to_pose(A_in_cam, trans_delta, rot_mat_delta): + '''Used for Pose Refinement. Given the object's two poses in camera, convert them to relative poses in camera's egocentric view + @A_in_cam: (B,4,4) torch tensor + ''' + B_in_cam = torch.eye(4, dtype=torch.float, device=A_in_cam.device)[None].expand(len(A_in_cam),-1,-1).contiguous() + B_in_cam[:,:3,3] = A_in_cam[:,:3,3]+trans_delta + B_in_cam[:,:3,:3] = rot_mat_delta@A_in_cam[:,:3,:3] + return B_in_cam + + +def sdg_load_bounding_box(file_path: str): + """Load bounding boxes. + Args: + file_path: Path of the bounding box. + + Returns: + A dictionary of the bounding boxes. + """ + bbox_dict = {} + bbox_array = np.load(file_path) + for id, x_min, y_min, x_max, y_max, occlusion_ratio in zip( + bbox_array["semanticId"], + bbox_array["x_min"], + bbox_array["y_min"], + bbox_array["x_max"], + bbox_array["y_max"], + bbox_array["occlusionRatio"], + ): + bbox_dict[id] = { + "x_min": x_min, + "y_min": y_min, + "x_max": x_max, + "y_max": y_max, + "occlusion_ratio": occlusion_ratio, + } + return bbox_dict + + +def texture_map_interpolation(tex_image_numpy): + all_channels = [] + mask = np.all(tex_image_numpy == 0, axis=2) + x = np.arange(0, tex_image_numpy.shape[1]) + y = np.arange(0, tex_image_numpy.shape[0]) + xx, yy = np.meshgrid(x, y) + for each_channel in range(tex_image_numpy.shape[2]): + curr_channel = tex_image_numpy[:,:,each_channel] + x1 = xx[~mask] + y1 = yy[~mask] + newarr = curr_channel[~mask] + GD1 = griddata((x1, y1), newarr.ravel(), (xx, yy), method='nearest') + all_channels.append(GD1[:,:,np.newaxis].round().astype(np.uint8)) + final_image = np.concatenate(all_channels, axis =-1) + return final_image + + + +class OctreeManager: + def __init__(self,pts=None,max_level=None,octree=None): + import kaolin + if octree is None: + pts_quantized = kaolin.ops.spc.quantize_points(pts.contiguous(), level=max_level) + self.octree = kaolin.ops.spc.unbatched_points_to_octree(pts_quantized, max_level, sorted=False) + else: + self.octree = octree + lengths = torch.tensor([len(self.octree)], dtype=torch.int32).cpu() + self.max_level, self.pyramids, self.exsum = kaolin.ops.spc.scan_octrees(self.octree,lengths) + self.finest_vox_size = 2.0/(2**self.max_level) + self.n_level = self.max_level+1 + self.vox_point_all_levels = kaolin.ops.spc.generate_points(self.octree, self.pyramids, self.exsum) + self.point_hierarchy_dual, self.pyramid_dual = kaolin.ops.spc.unbatched_make_dual(self.vox_point_all_levels, self.pyramids[0]) + self.trinkets, self.pointers_to_parent = kaolin.ops.spc.unbatched_make_trinkets(self.vox_point_all_levels, self.pyramids[0], self.point_hierarchy_dual, self.pyramid_dual) + self.n_vox = len(self.vox_point_all_levels) + self.n_corners = len(self.point_hierarchy_dual) + + for level in range(self.n_level): + vox_pts = self.get_level_quantized_points(level) + corner_pts = self.get_level_corner_quantized_points(level) + logging.info(f'level:{level}, vox_pts:{vox_pts.shape}, corner_pts:{corner_pts.shape}') + + def get_level_corner_quantized_points(self,level): + start = self.pyramid_dual[...,1,level] + num = self.pyramid_dual[...,0,level] + return self.point_hierarchy_dual[start:start+num] + + def get_level_quantized_points(self,level): + start = self.pyramids[...,1,level] + num = self.pyramids[...,0,level] + return self.vox_point_all_levels[start:start+num] + + + def get_center_ids(self,x,level): + '''Get ids with 0 starting from current level's first point + ''' + import kaolin + pidx = kaolin.ops.spc.unbatched_query(self.octree, self.exsum, x.float(), level, with_parents=False) + return pidx + + + def get_vox_size_at_level(self, level): + return 2.0/(2**level) + + + def draw(self,level, method='point'): + import kaolin + logging.info(f"level:{level}") + vox_size = self.get_vox_size_at_level(level) + + if method=='point': + corner_coords = self.get_level_corner_quantized_points(level) + pts = corner_coords*vox_size - 1 + mesh = trimesh.points.PointCloud(pts.data.cpu().numpy().reshape(-1,3)) + return mesh + + + def ray_trace(self,rays_o,rays_d,level,debug=False): + """Octree is in normalized [-1,1] world coordinate frame + 'rays_o': ray origin in normalized world coordinate system + 'rays_d': (N,3) unit length ray direction in normalized world coordinate system + 'octree': spc + @voxel_size: in the scale of [-1,1] space + Return: + ray_depths_in_out: traveling times, NOT the Z value; invalid will be zeros + """ + from mycuda import common + import kaolin + + ray_index, rays_pid, depth_in_out = kaolin.render.spc.unbatched_raytrace(self.octree,self.vox_point_all_levels,self.pyramids[0],self.exsum,rays_o,rays_d,level=level,return_depth=True,with_exit=True) + if ray_index.size()[0] == 0: + pdb.set_trace() + print("[WARNING] batch has 0 intersections!!") + ray_depths_in_out = torch.zeros((rays_o.shape[0],1,2)) + rays_pid = -torch.ones_like(rays_o[:, :1]) + rays_near = torch.zeros_like(rays_o[:, :1]) + rays_far = torch.zeros_like(rays_o[:, :1]) + return rays_near, rays_far, rays_pid, ray_depths_in_out + + intersected_ray_ids,counts = torch.unique_consecutive(ray_index,return_counts=True) + max_intersections = counts.max().item() + start_poss = torch.cat([torch.tensor([0], device=counts.device),torch.cumsum(counts[:-1],dim=0)],dim=0) + + ray_depths_in_out = common.postprocessOctreeRayTracing(ray_index.long().contiguous(),depth_in_out.contiguous(),intersected_ray_ids.long().contiguous(),start_poss.long().contiguous(), max_intersections, rays_o.shape[0]) + + rays_far = ray_depths_in_out[:,:,1].max(dim=-1)[0].reshape(-1,1) + rays_near = ray_depths_in_out[:,0,0].reshape(-1,1) + + return rays_near, rays_far, rays_pid, ray_depths_in_out + + +def make_yaml_dumpable(D): + if isinstance(D, np.ndarray): + return D.tolist() + for d in D: + if isinstance(D[d], dict) or isinstance(D[d], OrderedDict) or isinstance(D[d], defaultdict): + D[d] = dict(D[d]) + D[d] = make_yaml_dumpable(D[d]) + continue + if isinstance(D[d], np.ndarray): + D[d] = D[d].tolist() + continue + if np.issubdtype(type(D[d]), int): + D[d] = int(D[d]) + continue + if np.issubdtype(type(D[d]), float): + D[d] = float(D[d]) + continue + if np.issubdtype(type(D[d]), str): + D[d] = str(D[d]) + continue + if isinstance(D[d], list): + for i in range(len(D[d])): + D[d][i] = make_yaml_dumpable(D[d][i]) + continue + return dict(D) diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/build_all.sh b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/build_all.sh new file mode 100644 index 0000000000000000000000000000000000000000..90937574a06a56189cae6adbdc4d45a1875fe498 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/build_all.sh @@ -0,0 +1,7 @@ +DIR=$(pwd) + +cd $DIR/mycpp/ && mkdir -p build && cd build && cmake .. -DPYTHON_EXECUTABLE=$(which python) && make -j11 +cd /kaolin && rm -rf build *egg* && pip install -e . +cd $DIR/bundlesdf/mycuda && rm -rf build *egg* && pip install -e . + +cd ${DIR} diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/build_all_conda.sh b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/build_all_conda.sh new file mode 100644 index 0000000000000000000000000000000000000000..9f88fde15c18d8f99c2ecc477ff6451a205c9e22 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/build_all_conda.sh @@ -0,0 +1,14 @@ +PROJ_ROOT=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd ) + +# Install mycpp +cd ${PROJ_ROOT}/mycpp/ && \ +rm -rf build && mkdir -p build && cd build && \ +cmake .. && \ +make -j$(nproc) + +# Install mycuda +cd ${PROJ_ROOT}/bundlesdf/mycuda && \ +rm -rf build *egg* *.so && \ +python -m pip install -e . + +cd ${PROJ_ROOT} diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/bundlesdf/config_linemod.yml b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/bundlesdf/config_linemod.yml new file mode 100644 index 0000000000000000000000000000000000000000..477faa88f2830fae95b8edaa8e8cdf773bf23073 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/bundlesdf/config_linemod.yml @@ -0,0 +1,105 @@ +notes: '' +n_step: 1000 +netdepth: 8 +netwidth: 256 +netdepth_fine: 8 +netwidth_fine: 256 +N_rand: 2048 # Batch number of rays +first_frame_ray_in_batch: 0 +lrate: 0.01 +lrate_pose: 0.01 +pose_optimize_start: 0 +decay_rate: 0.1 +chunk: 99999999999 +netchunk: 6553600 +no_batching: 0 +amp: true + +N_samples: 128 #number of coarse samples per ray +N_samples_around_depth: 128 +N_importance: 0 +N_importance_iter: 1 +perturb: 1 +use_viewdirs: 1 +i_embed: 1 #set 1 for hashed embedding, 0 for default positional encoding, 2 for spherical; 3 for octree grid +i_embed_views: 2 #set 1 for hashed embedding, 0 for default positional encoding, 2 for spherical +multires: 8 #log2 of max freq for positional encoding (3D location) +multires_views: 3 #log2 of max freq for positional encoding (2D direction) +feature_grid_dim: 2 +raw_noise_std: 0 +white_bkgd: 0 +gradient_max_norm: 0.1 +gradient_pose_max_norm: 0.1 + +# logging/saving options +i_print: 500 +i_img: 500 +i_weights: 500 +i_mesh: 500 +i_nerf_normals: 500 +i_save_ray: 500 +i_pose: 500 +save_octree_clouds: True + +finest_res: 256 +base_res: 32 +num_levels: 16 +log2_hashmap_size: 22 +datadir: /path/to/github/HashNeRF-pytorch/data/bundlesdf_bundlesdf_e03000196 +n_train_image: 300 +use_octree: 1 +first_frame_weight: 1 +denoise_depth_use_octree_cloud: true +octree_embed_base_voxel_size: 0.02 +octree_smallest_voxel_size: 0.02 # This determines the smallest feature vox size +octree_raytracing_voxel_size: 0.02 +octree_dilate_size: 0.02 # meters +down_scale_ratio: 1 +bounding_box: [[-1,-1,-1], [1,1,1]] +farthest_pose_sampling: 0 # Sampling train images. This replace uniform skip +use_mask: 1 +dilate_mask_size: 0 +rays_valid_depth_only: true +near: 0.1 +far: 2 +rgb_weight: 1 +depth_weight: 0 +trunc: 0.01 #length of the truncation region in meters +trunc_start: 0.01 +sdf_lambda: 5 +neg_trunc_ratio: 1 # -trunc distance ratio compared to +trunc +trunc_decay_type: '' +sdf_loss_type: l2 +fs_weight: 1000 +empty_weight: 1 +fs_rgb_weight: 0 +trunc_weight: 6000 +sparse_loss_weight: 0 +tv_loss_weight: 0 +frame_features: 2 #number of channels of the learnable per-frame features +optimize_poses: 1 #optimize a pose refinement for the initial poses +pose_reg_weight: 0 +point_cloud_loss_weight: 0 +point_cloud_loss_normal_weight: 0 +eikonal_weight: 0 +normal_loss_weight: 0 +feature_reg_weight: 0.1 +deformation_reg_weight: 0 +use_deformation_field: 0 #use a deformation field to account for inaccuracies in intrinsic parameters +max_pix_shift: 0.02 # Pixel shift ratio relative to image size +share_coarse_fine: 1 +mode: sdf +fs_sdf: 1 # Uncertain free space +crop: 0 +mesh_resolution: 0.003 +max_trans: 0.02 # meters +max_rot: 10 # deg + +continual: True + +######### dbscan +dbscan_eps: 0.01 +dbscan_eps_min_samples: 1 + +####### bundlenerf +sync_max_delay: 0 # 0 for strict sync \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/bundlesdf/config_ycbv.yml b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/bundlesdf/config_ycbv.yml new file mode 100644 index 0000000000000000000000000000000000000000..8044598ed778df4aee4ab3f9a21dcaf6214f0fa9 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/bundlesdf/config_ycbv.yml @@ -0,0 +1,105 @@ +notes: '' +n_step: 1000 +netdepth: 8 +netwidth: 256 +netdepth_fine: 8 +netwidth_fine: 256 +N_rand: 2048 # Batch number of rays +first_frame_ray_in_batch: 0 +lrate: 0.01 +lrate_pose: 0.01 +pose_optimize_start: 0 +decay_rate: 0.1 +chunk: 99999999999 +netchunk: 6553600 +no_batching: 0 +amp: true + +N_samples: 128 #number of coarse samples per ray +N_samples_around_depth: 128 +N_importance: 0 +N_importance_iter: 1 +perturb: 1 +use_viewdirs: 1 +i_embed: 1 #set 1 for hashed embedding, 0 for default positional encoding, 2 for spherical; 3 for octree grid +i_embed_views: 2 #set 1 for hashed embedding, 0 for default positional encoding, 2 for spherical +multires: 8 #log2 of max freq for positional encoding (3D location) +multires_views: 3 #log2 of max freq for positional encoding (2D direction) +feature_grid_dim: 2 +raw_noise_std: 0 +white_bkgd: 0 +gradient_max_norm: 0.1 +gradient_pose_max_norm: 0.1 + +# logging/saving options +i_print: 500 +i_img: 500 +i_weights: 500 +i_mesh: 500 +i_nerf_normals: 500 +i_save_ray: 500 +i_pose: 500 +save_octree_clouds: True + +finest_res: 512 +base_res: 32 +num_levels: 16 +log2_hashmap_size: 22 +datadir: /path/to/github/HashNeRF-pytorch/data/bundlesdf_bundlesdf_e03000196 +n_train_image: 300 +use_octree: 1 +first_frame_weight: 1 +denoise_depth_use_octree_cloud: true +octree_embed_base_voxel_size: 0.02 +octree_smallest_voxel_size: 0.02 # This determines the smallest feature vox size +octree_raytracing_voxel_size: 0.02 +octree_dilate_size: 0.02 # meters +down_scale_ratio: 1 +bounding_box: [[-1,-1,-1], [1,1,1]] +farthest_pose_sampling: 0 # Sampling train images. This replace uniform skip +use_mask: 1 +dilate_mask_size: 0 +rays_valid_depth_only: true +near: 0.1 +far: 2 +rgb_weight: 100 +depth_weight: 0 +trunc: 0.01 #length of the truncation region in meters +trunc_start: 0.01 +sdf_lambda: 5 +neg_trunc_ratio: 1 # -trunc distance ratio compared to +trunc +trunc_decay_type: '' +sdf_loss_type: l2 +fs_weight: 100 +empty_weight: 1 +fs_rgb_weight: 0 +trunc_weight: 6000 +sparse_loss_weight: 0 +tv_loss_weight: 0 +frame_features: 2 #number of channels of the learnable per-frame features +optimize_poses: 1 #optimize a pose refinement for the initial poses +pose_reg_weight: 0 +point_cloud_loss_weight: 0 +point_cloud_loss_normal_weight: 0 +eikonal_weight: 0 +normal_loss_weight: 0 +feature_reg_weight: 0.1 +deformation_reg_weight: 0 +use_deformation_field: 0 #use a deformation field to account for inaccuracies in intrinsic parameters +max_pix_shift: 0.02 # Pixel shift ratio relative to image size +share_coarse_fine: 1 +mode: sdf +fs_sdf: 1 # Uncertain free space +crop: 0 +mesh_resolution: 0.003 +max_trans: 0.02 # meters +max_rot: 10 # deg + +continual: True + +######### dbscan +dbscan_eps: 0.01 +dbscan_eps_min_samples: 1 + +####### bundlenerf +sync_max_delay: 0 # 0 for strict sync \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/bundlesdf/mycuda/__init__.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/bundlesdf/mycuda/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/bundlesdf/mycuda/bindings.cpp b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/bundlesdf/mycuda/bindings.cpp new file mode 100644 index 0000000000000000000000000000000000000000..605ffb44af1ac7a26a1c5a58dfea7e56431b1125 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/bundlesdf/mycuda/bindings.cpp @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#include +#include "common.h" + +PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { + m.def("sampleRaysUniformOccupiedVoxels", &sampleRaysUniformOccupiedVoxels); + m.def("postprocessOctreeRayTracing", &postprocessOctreeRayTracing); + m.def("rayColorToTextureImageCUDA", &rayColorToTextureImageCUDA); + +} \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/bundlesdf/mycuda/common.cu b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/bundlesdf/mycuda/common.cu new file mode 100644 index 0000000000000000000000000000000000000000..97974d2d1766bd01d059499fa3f71e3fb12794c4 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/bundlesdf/mycuda/common.cu @@ -0,0 +1,313 @@ +/* + * Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "common.h" +#include "Eigen/Dense" + + + + + +/** + * @brief + * + * @tparam scalar_t + * @param z_sampled + * @param z_in_out + * @param z_vals + * @return __global__ + */ +template +__global__ void sample_rays_uniform_occupied_voxels_kernel(const torch::PackedTensorAccessor32 z_sampled, const torch::PackedTensorAccessor32 z_in_out, torch::PackedTensorAccessor32 z_vals) +{ + const int i_ray = blockIdx.x * blockDim.x + threadIdx.x; + const int i_sample = blockIdx.y * blockDim.y + threadIdx.y; + if (i_ray>=z_sampled.size(0)) return; + if (i_sample>=z_sampled.size(1)) return; + + int i_box = 0; + float z_remain = z_sampled[i_ray][i_sample]; + auto z_in_out_cur_ray = z_in_out[i_ray]; + const float eps = 1e-4; + const int max_n_box = z_in_out.size(1); + + if (z_in_out_cur_ray[0][0]==0) return; + + while (1) + { + if (i_box>=max_n_box) + { + if (z_remain<=eps) + { + z_vals[i_ray][i_sample] = z_in_out_cur_ray[max_n_box-1][1]; + } + else + { + printf("ERROR sample_rays_uniform_occupied_voxels_kernel: z_remain=%f, i_ray=%d, i_sample=%d, i_box=%d, z_in_out_cur_ray=(%f,%f)\n",z_remain,i_ray,i_sample,i_box,z_in_out_cur_ray[i_box][0],z_in_out_cur_ray[i_box][1]); + for (int i=0;i=1) + { + z_vals[i_ray][i_sample] = z_in_out_cur_ray[i_box-1][1]; + return; + } + else + { + printf("ERROR sample_rays_uniform_occupied_voxels_kernel: z_remain=%f, i_ray=%d, i_sample=%d, i_box=%d, z_in_out_cur_ray=(%f,%f)\n",z_remain,i_ray,i_sample,i_box,z_in_out_cur_ray[i_box][0],z_in_out_cur_ray[i_box][1]); + for (int i=0;i<<<{divCeil(N_rays,threadx),divCeil(N_samples,thready)}, {threadx,thready}>>>(z_sampled.packed_accessor32(),z_in_out.packed_accessor32(),z_vals.packed_accessor32()); + })); + + return z_vals; +} + +template +__global__ void postprocessOctreeRayTracingKernel(const torch::PackedTensorAccessor32 ray_index, const torch::PackedTensorAccessor32 depth_in_out, const torch::PackedTensorAccessor32 unique_intersect_ray_ids, const torch::PackedTensorAccessor32 start_poss, torch::PackedTensorAccessor32 depths_in_out_padded) +{ + const int unique_id_pos = blockIdx.x * blockDim.x + threadIdx.x; + if (unique_id_pos>=unique_intersect_ray_ids.size(0)) return; + const int i_ray = unique_intersect_ray_ids[unique_id_pos]; + + int i_intersect = 0; + auto cur_depths_in_out_padded = depths_in_out_padded[i_ray]; + for (int i=start_poss[unique_id_pos];idepth_in_out[i][1]) continue; + if (abs(depth_in_out[i][1]-depth_in_out[i][0])<1e-4) continue; + + cur_depths_in_out_padded[i_intersect][0] = depth_in_out[i][0]; + cur_depths_in_out_padded[i_intersect][1] = depth_in_out[i][1]; + + i_intersect++; + + } +} + +at::Tensor postprocessOctreeRayTracing(const at::Tensor ray_index, const at::Tensor depth_in_out, const at::Tensor unique_intersect_ray_ids, const at::Tensor start_poss, const int max_intersections, const int N_rays) +{ + CHECK_INPUT(ray_index); + CHECK_INPUT(depth_in_out); + CHECK_INPUT(start_poss); + + const int n_unique_ids = unique_intersect_ray_ids.sizes()[0]; + at::Tensor depths_in_out_padded = at::zeros({N_rays,max_intersections,2}, torch::TensorOptions().dtype(torch::kFloat32).device(torch::kCUDA, 0).requires_grad(false)); + dim3 threads = {256}; + dim3 blocks = {divCeil(n_unique_ids,threads.x)}; + AT_DISPATCH_FLOATING_TYPES(depth_in_out.type(), "postprocessOctreeRayTracingKernel", ([&] + { + postprocessOctreeRayTracingKernel<<>>(ray_index.packed_accessor32(), depth_in_out.packed_accessor32(), unique_intersect_ray_ids.packed_accessor32(), start_poss.packed_accessor32(), depths_in_out_padded.packed_accessor32()); + })); + + return depths_in_out_padded; +} + + +at::Tensor calculateBarycentricCoordinate3D(const at::Tensor &triangle, const at::Tensor &p) +{ + auto vector_A = triangle[1]-triangle[2]; + auto vector_B = triangle[1]-triangle[0]; + auto normal = vector_A.cross(vector_B); + auto areaABC = (normal * at::cross(triangle[1]-triangle[0], triangle[2]-triangle[0])).sum(); + auto areaPBC = (normal * at::cross(triangle[1]-p, triangle[2]-p)).sum(); + auto areaPCA = (normal * at::cross(triangle[2]-p, triangle[0]-p)).sum(); + at::Tensor ws = at::zeros({3}).to(torch::kFloat32); + ws[0] = areaPBC / areaABC; + ws[1] = areaPCA / areaABC; + ws[2] = 1-ws[0]-ws[1]; + return ws; +} + + +__device__ Eigen::Vector3f calculateBarycentricCoordinate3DKernel(const Eigen::Matrix &triangle, const Eigen::Vector3f &p) +{ + Eigen::Vector3f vector_A = triangle.row(1)-triangle.row(2); + Eigen::Vector3f vector_B = triangle.row(1)-triangle.row(0); + Eigen::Vector3f normal = vector_A.cross(vector_B); + float areaABC = (normal.array() * (triangle.row(1)-triangle.row(0)).cross(triangle.row(2)-triangle.row(0)).transpose().array()).sum(); + float areaPBC = (normal.array() * (triangle.row(1).transpose()-p).cross(triangle.row(2).transpose()-p).array()).sum(); + float areaPCA = (normal.array() * (triangle.row(2).transpose()-p).cross(triangle.row(0).transpose()-p).array()).sum(); + Eigen::Vector3f w; + w[0] = areaPBC / areaABC; + w[1] = areaPCA / areaABC; + w[2] = 1-w[0]-w[1]; + return w; + +} + + +__device__ void calculateBarycentricCoordinate2DKernel(const Eigen::Matrix &triangle, const Eigen::Vector2f &p, Eigen::Vector3f &w) +{ + Eigen::Vector2f CA = triangle.row(0)-triangle.row(2); + Eigen::Vector2f AC = -CA; + Eigen::Vector2f CP = p-triangle.row(2).transpose(); + Eigen::Vector2f AB = triangle.row(1)-triangle.row(0); + Eigen::Vector2f AP = p-triangle.row(0).transpose(); + Eigen::Matrix2f numerator, denominator; + numerator << CA, CP; + denominator< +__global__ void rayColorToTextureImageKernel(const torch::PackedTensorAccessor32 F, const torch::PackedTensorAccessor32 V, const torch::PackedTensorAccessor32 hit_locations, const torch::PackedTensorAccessor32 hit_face_ids, const torch::PackedTensorAccessor32 uvs_tex, torch::PackedTensorAccessor32 uvs) +{ + const int i_hit = blockIdx.x*blockDim.x + threadIdx.x; + if (i_hit>=hit_locations.size(0)) return; + + auto face = F[hit_face_ids[i_hit]]; + Eigen::Matrix3f tri_v = Eigen::Matrix3f::Zero(); + for (int r=0;r<3;r++) + { + for (int c=0;c<3;c++) + { + tri_v(r,c) = V[face[r]][c]; + } + } + auto location = hit_locations[i_hit]; + Eigen::Vector3f p(location[0], location[1], location[2]); + auto w = calculateBarycentricCoordinate3DKernel(tri_v, p); + + Eigen::Matrix tri_uvs; + for (int i=0;i<3;i++) + { + for (int j=0;j<2;j++) + { + tri_uvs(i,j) = uvs_tex[face[i]][j]; + } + } + + Eigen::Vector2f cur_uv = tri_uvs.transpose() * w; + uvs[i_hit][0] = cur_uv(0); + uvs[i_hit][1] = cur_uv(1); +} + + + +void rayColorToTextureImageCUDA(const at::Tensor &F, const at::Tensor &V, const at::Tensor &hit_locations, const at::Tensor &hit_face_ids, const at::Tensor &uvs_tex, at::Tensor &uvs) +{ + CHECK_CONTIGUOUS(F); + CHECK_CONTIGUOUS(V); + CHECK_CONTIGUOUS(hit_locations); + CHECK_CONTIGUOUS(hit_face_ids); + CHECK_CONTIGUOUS(uvs_tex); + + dim3 threads = {512}; + dim3 blocks = {divCeil(int(hit_locations.sizes()[0]),threads.x)}; + + AT_DISPATCH_FLOATING_TYPES(V.type(), "rayColorToTextureImageKernel", ([&] + { + rayColorToTextureImageKernel<<>>(F.packed_accessor32(), V.packed_accessor32(), hit_locations.packed_accessor32(), hit_face_ids.packed_accessor32(), uvs_tex.packed_accessor32(), uvs.packed_accessor32()); + })); +} + + + +__device__ bool isLineIntersectLine(Eigen::Vector2f l1p1, Eigen::Vector2f l1p2, Eigen::Vector2f l2p1, Eigen::Vector2f l2p2) +{ + float q = (l1p1(1) - l2p1(1)) * (l2p2(0) - l2p1(0)) - (l1p1(0) - l2p1(0)) * (l2p2(1) - l2p1(1)); + float d = (l1p2(0) - l1p1(0)) * (l2p2(1) - l2p1(1)) - (l1p2(1) - l1p1(1)) * (l2p2(0) - l2p1(0)); + + if ( d == 0 ) + { + return false; + } + + float r = q / d; + + q = (l1p1(1) - l2p1(1)) * (l1p2(0) - l1p1(0)) - (l1p1(0) - l2p1(0)) * (l1p2(1) - l1p1(1)); + float s = q / d; + + if( r < 0 || r > 1 || s < 0 || s > 1 ) + { + return false; + } + + return true; +} + +__device__ bool isLineIntersectSquare(const Eigen::Vector2f &la, const Eigen::Vector2f &lb, const Eigen::Vector2f &p0, const Eigen::Vector2f &p1, const Eigen::Vector2f &p2, const Eigen::Vector2f &p3) +{ + return isLineIntersectLine(la, lb, p0, p1) || isLineIntersectLine(la, lb, p1, p2) || isLineIntersectLine(la, lb, p2, p3) || isLineIntersectLine(la, lb, p3, p0); +} + + +__device__ bool isPixelInsideTriangle(const Eigen::Matrix &triangle, Eigen::Vector2f p, Eigen::Vector3f &w) +{ + calculateBarycentricCoordinate2DKernel(triangle, p, w); + for (int j=0;j<3;j++) + { + if (w(j)<0) return false; + } + return true; +} diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/bundlesdf/mycuda/common.h b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/bundlesdf/mycuda/common.h new file mode 100644 index 0000000000000000000000000000000000000000..77d98cb166588a80f8bdde52bb9de3588bf69f71 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/bundlesdf/mycuda/common.h @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#pragma once + +#include +#include + +#define CHECK_CUDA(x) AT_ASSERTM(x.is_cuda(), #x " must be a CUDA tensor") +#define CHECK_CONTIGUOUS(x) AT_ASSERTM(x.is_contiguous(), #x " must be contiguous") +#define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x) + + +inline int divCeil(int a, int b) +{ + return (a+b-1)/b; +}; + + +at::Tensor sampleRaysUniformOccupiedVoxels(const at::Tensor z_in_out, const at::Tensor z_sampled, at::Tensor z_vals); +at::Tensor postprocessOctreeRayTracing(const at::Tensor ray_index, const at::Tensor depth_in_out, const at::Tensor unique_intersect_ray_ids, const at::Tensor start_poss, const int max_intersections, const int N_rays); +void rayColorToTextureImageCUDA(const at::Tensor &F, const at::Tensor &V, const at::Tensor &hit_locations, const at::Tensor &hit_face_ids, const at::Tensor &uvs_tex, at::Tensor &uvs); \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/bundlesdf/mycuda/setup.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/bundlesdf/mycuda/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..f3fb2417172dd6e028a7464297ed2c36de2b960a --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/bundlesdf/mycuda/setup.py @@ -0,0 +1,45 @@ +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. + + +from setuptools import setup +import os,sys +from torch.utils.cpp_extension import BuildExtension, CUDAExtension +from torch.utils.cpp_extension import load + +code_dir = os.path.dirname(os.path.realpath(__file__)) + + +nvcc_flags = ['-Xcompiler', '-O3', '-std=c++17', '-U__CUDA_NO_HALF_OPERATORS__', '-U__CUDA_NO_HALF_CONVERSIONS__', '-U__CUDA_NO_HALF2_OPERATORS__'] +c_flags = ['-O3', '-std=c++17'] + +conda_prefix = os.environ['CONDA_PREFIX'] + +setup( + name='common', + extra_cflags=c_flags, + extra_cuda_cflags=nvcc_flags, + ext_modules=[ + CUDAExtension('common', [ + 'bindings.cpp', + 'common.cu', + ],extra_compile_args={'gcc': c_flags, 'nvcc': nvcc_flags}), + CUDAExtension('gridencoder', [ + f"{code_dir}/torch_ngp_grid_encoder/gridencoder.cu", + f"{code_dir}/torch_ngp_grid_encoder/bindings.cpp", + ],extra_compile_args={'gcc': c_flags, 'nvcc': nvcc_flags}), + ], + # important: use eigen3 from conda + include_dirs=[ + # "/usr/local/include/eigen3", + # "/usr/include/eigen3", + f"{conda_prefix}/include/eigen3" + ], + cmdclass={ + 'build_ext': BuildExtension.with_options(use_ninja=False), +}) diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/bundlesdf/mycuda/torch_ngp_grid_encoder/LICENSE b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/bundlesdf/mycuda/torch_ngp_grid_encoder/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..56f524a263863d139bce3bef0f9c71a2c37a36ad --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/bundlesdf/mycuda/torch_ngp_grid_encoder/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 hawkey + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/bundlesdf/mycuda/torch_ngp_grid_encoder/bindings.cpp b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/bundlesdf/mycuda/torch_ngp_grid_encoder/bindings.cpp new file mode 100644 index 0000000000000000000000000000000000000000..afa6f64fd7d7d1efc0380e279aad3ae3ca66c36f --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/bundlesdf/mycuda/torch_ngp_grid_encoder/bindings.cpp @@ -0,0 +1,8 @@ +#include + +#include "gridencoder.h" + +PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { + m.def("grid_encode_forward", &grid_encode_forward, "grid_encode_forward (CUDA)"); + m.def("grid_encode_backward", &grid_encode_backward, "grid_encode_backward (CUDA)"); +} \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/bundlesdf/mycuda/torch_ngp_grid_encoder/grid.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/bundlesdf/mycuda/torch_ngp_grid_encoder/grid.py new file mode 100644 index 0000000000000000000000000000000000000000..6573ce498c282b9aacaf76254b22d2e1a96bb63d --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/bundlesdf/mycuda/torch_ngp_grid_encoder/grid.py @@ -0,0 +1,158 @@ +import numpy as np +import os,sys,pdb +code_dir = os.path.dirname(os.path.realpath(__file__)) +sys.path.append(code_dir) +import torch +import torch.nn as nn +from torch.autograd import Function +from torch.autograd.function import once_differentiable +from torch.cuda.amp import custom_bwd, custom_fwd +from setuptools import setup +from torch.utils.cpp_extension import BuildExtension, CUDAExtension +from torch.utils.cpp_extension import load +import os,sys +import gridencoder + + +_gridtype_to_id = { + 'hash': 0, + 'tiled': 1, +} + +class _grid_encode(Function): + @staticmethod + @custom_fwd + def forward(ctx, inputs, embeddings, offsets, per_level_scale, base_resolution, calc_grad_inputs=False, gridtype=0, align_corners=False): + # inputs: [B, D], float in [0, 1] + # embeddings: [sO, C], float + # offsets: [L + 1], int + # RETURN: [B, F], float + + inputs = inputs.contiguous() + + B, D = inputs.shape + L = offsets.shape[0] - 1 + C = embeddings.shape[1] + S = np.log2(per_level_scale) + H = base_resolution + + if torch.is_autocast_enabled() and C % 2 == 0: + embeddings = embeddings.to(torch.half) + + outputs = torch.empty(L, B, C, device=inputs.device, dtype=embeddings.dtype) + + if calc_grad_inputs: + dy_dx = torch.empty(B, L * D * C, device=inputs.device, dtype=embeddings.dtype) + else: + dy_dx = torch.empty(1, device=inputs.device, dtype=embeddings.dtype) # placeholder... TODO: a better way? + + gridencoder.grid_encode_forward(inputs, embeddings, offsets, outputs, B, D, C, L, S, H, calc_grad_inputs, dy_dx, gridtype, align_corners) + + outputs = outputs.permute(1, 0, 2).reshape(B, L * C) + + ctx.save_for_backward(inputs, embeddings, offsets, dy_dx) + ctx.dims = [B, D, C, L, S, H, gridtype] + ctx.calc_grad_inputs = calc_grad_inputs + ctx.align_corners = align_corners + + return outputs + + @staticmethod + @custom_bwd + def backward(ctx, grad): + + inputs, embeddings, offsets, dy_dx = ctx.saved_tensors + B, D, C, L, S, H, gridtype = ctx.dims + calc_grad_inputs = ctx.calc_grad_inputs + align_corners = ctx.align_corners + + # grad: [B, L * C] --> [L, B, C] + grad = grad.view(B, L, C).permute(1, 0, 2).contiguous() + + grad_embeddings = torch.zeros_like(embeddings) + + if calc_grad_inputs: + grad_inputs = torch.zeros_like(inputs, dtype=embeddings.dtype) + else: + grad_inputs = torch.zeros(1, device=inputs.device, dtype=embeddings.dtype) + + gridencoder.grid_encode_backward(grad, inputs, embeddings, offsets, grad_embeddings, B, D, C, L, S, H, calc_grad_inputs, dy_dx, grad_inputs, gridtype, align_corners) + + if calc_grad_inputs: + grad_inputs = grad_inputs.to(inputs.dtype) + return grad_inputs, grad_embeddings, None, None, None, None, None, None + else: + return None, grad_embeddings, None, None, None, None, None, None + + +grid_encode = _grid_encode.apply + + +# https://github.com/ashawkey/torch-ngp/blob/main/gridencoder/grid.py +class GridEncoder(nn.Module): + def __init__(self, input_dim=3, n_levels=16, level_dim=2, base_resolution=16, log2_hashmap_size=19, desired_resolution=None, gridtype='hash', align_corners=False): + super().__init__() + + per_level_scale = np.exp2(np.log2(desired_resolution / base_resolution) / (n_levels - 1)) + + self.input_dim = input_dim # coord dims, 2 or 3 + self.n_levels = n_levels # num levels, each level multiply resolution by 2 + self.level_dim = level_dim # encode channels per level + self.per_level_scale = per_level_scale # multiply resolution by this scale at each level. + self.log2_hashmap_size = log2_hashmap_size + self.base_resolution = base_resolution + self.out_dim = n_levels * level_dim + self.gridtype = gridtype + self.gridtype_id = _gridtype_to_id[gridtype] # "tiled" or "hash" + self.align_corners = align_corners + + # allocate parameters + offsets = [] + offset = 0 + self.max_params = 2 ** log2_hashmap_size + for i in range(n_levels): + resolution = int(np.ceil(base_resolution * per_level_scale ** i)) + params_in_level = min(self.max_params, (resolution if align_corners else resolution + 1) ** input_dim) # limit max number + params_in_level = int(np.ceil(params_in_level / 8) * 8) # make divisible + print(f"level {i}, resolution: {resolution}") + offsets.append(offset) + offset += params_in_level + offsets.append(offset) + offsets = torch.from_numpy(np.array(offsets, dtype=np.int32)) + self.register_buffer('offsets', offsets) + + self.n_params = offsets[-1] * level_dim + + # parameters + self.embeddings = nn.Parameter(torch.empty(offset, level_dim)) + # self.embeddings = nn.Embedding(offset, level_dim, sparse=True) + + self.reset_parameters() + + def reset_parameters(self): + std = 1e-4 + self.embeddings.data.uniform_(-std, std) + # self.embeddings.weight.data.uniform_(-std, std) + + + def __repr__(self): + return f"GridEncoder: input_dim={self.input_dim} n_levels={self.n_levels} level_dim={self.level_dim} resolution={self.base_resolution} -> {int(round(self.base_resolution * self.per_level_scale ** (self.n_levels - 1)))} per_level_scale={self.per_level_scale:.4f} params={tuple(self.embeddings.shape)} gridtype={self.gridtype} align_corners={self.align_corners}" + + + def forward(self, inputs, bound=1): + # inputs: [..., input_dim], normalized real world positions in [-bound, bound] + # return: [..., num_levels * level_dim] + + inputs = (inputs + bound) / (2 * bound) # map to [0, 1] + + #print('inputs', inputs.shape, inputs.dtype, inputs.min().item(), inputs.max().item()) + + prefix_shape = list(inputs.shape[:-1]) + inputs = inputs.view(-1, self.input_dim) + + outputs = grid_encode(inputs, self.embeddings, self.offsets, self.per_level_scale, self.base_resolution, inputs.requires_grad, self.gridtype_id, self.align_corners) + outputs = outputs.view(prefix_shape + [self.out_dim]) + + #print('outputs', outputs.shape, outputs.dtype, outputs.min().item(), outputs.max().item()) + + return outputs \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/bundlesdf/mycuda/torch_ngp_grid_encoder/gridencoder.cu b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/bundlesdf/mycuda/torch_ngp_grid_encoder/gridencoder.cu new file mode 100644 index 0000000000000000000000000000000000000000..6bb45c7133f2d9a6d577c74137d5c28a6c27f868 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/bundlesdf/mycuda/torch_ngp_grid_encoder/gridencoder.cu @@ -0,0 +1,500 @@ +#include +#include +#include + +#include +#include + +#include +#include + +#include +#include + + +#define CHECK_CUDA(x) TORCH_CHECK(x.device().is_cuda(), #x " must be a CUDA tensor") +#define CHECK_CONTIGUOUS(x) TORCH_CHECK(x.is_contiguous(), #x " must be a contiguous tensor") +#define CHECK_IS_INT(x) TORCH_CHECK(x.scalar_type() == at::ScalarType::Int, #x " must be an int tensor") +#define CHECK_IS_FLOATING(x) TORCH_CHECK(x.scalar_type() == at::ScalarType::Float || x.scalar_type() == at::ScalarType::Half || x.scalar_type() == at::ScalarType::Double, #x " must be a floating tensor") + + +// just for compatability of half precision in AT_DISPATCH_FLOATING_TYPES_AND_HALF... +static inline __device__ at::Half atomicAdd(at::Half *address, at::Half val) { + // requires CUDA >= 10 and ARCH >= 70 + // this is very slow compared to float or __half2, and never used. + //return atomicAdd(reinterpret_cast<__half*>(address), val); +} + + +template +static inline __host__ __device__ T div_round_up(T val, T divisor) { + return (val + divisor - 1) / divisor; +} + + +template +__device__ uint32_t fast_hash(const uint32_t pos_grid[D]) { + static_assert(D <= 7, "fast_hash can only hash up to 7 dimensions."); + + // While 1 is technically not a good prime for hashing (or a prime at all), it helps memory coherence + // and is sufficient for our use case of obtaining a uniformly colliding index from high-dimensional + // coordinates. + constexpr uint32_t primes[7] = { 1, 2654435761, 805459861, 3674653429, 2097192037, 1434869437, 2165219737 }; + + uint32_t result = 0; + #pragma unroll + for (uint32_t i = 0; i < D; ++i) { + result ^= pos_grid[i] * primes[i]; + } + + return result; +} + + +template +__device__ uint32_t get_grid_index(const uint32_t gridtype, const bool align_corners, const uint32_t ch, const uint32_t hashmap_size, const uint32_t resolution, const uint32_t pos_grid[D]) { + uint32_t stride = 1; + uint32_t index = 0; + + #pragma unroll + for (uint32_t d = 0; d < D && stride <= hashmap_size; d++) { + index += pos_grid[d] * stride; + stride *= align_corners ? resolution: (resolution + 1); + } + + // NOTE: for NeRF, the hash is in fact not necessary. Check https://github.com/NVlabs/instant-ngp/issues/97. + // gridtype: 0 == hash, 1 == tiled + if (gridtype == 0 && stride > hashmap_size) { + index = fast_hash(pos_grid); + } + + return (index % hashmap_size) * C + ch; +} + + +/** + * @brief + * + * @tparam scalar_t + * @tparam D : point dimension usually 3D + * @tparam C : embedding dim 1/2/4 + * @param inputs + * @param grid + * @param offsets + * @param outputs + * @param B + * @param L + * @param S + * @param H + * @param calc_grad_inputs + * @param dy_dx + * @param gridtype + * @param align_corners + * @return __global__ + */ +template +__global__ void kernel_grid( + const float * __restrict__ inputs, + const scalar_t * __restrict__ grid, + const int * __restrict__ offsets, + scalar_t * __restrict__ outputs, + const uint32_t B, const uint32_t L, const float S, const uint32_t H, + const bool calc_grad_inputs, + scalar_t * __restrict__ dy_dx, + const uint32_t gridtype, + const bool align_corners +) { + const uint32_t b = blockIdx.x * blockDim.x + threadIdx.x; // batch id + + if (b >= B) return; + + const uint32_t level = blockIdx.y; + + // locate + grid += (uint32_t)offsets[level] * C; + inputs += b * D; + outputs += level * B * C + b * C; + + // check input range (should be in [0, 1]) + bool flag_oob = false; + #pragma unroll + for (uint32_t d = 0; d < D; d++) { + if (inputs[d] < 0 || inputs[d] > 1) { + flag_oob = true; + } + } + // if input out of bound, just set output to 0 + if (flag_oob) { + #pragma unroll + for (uint32_t ch = 0; ch < C; ch++) { + outputs[ch] = 0; + } + if (calc_grad_inputs) { + dy_dx += b * D * L * C + level * D * C; // B L D C + #pragma unroll + for (uint32_t d = 0; d < D; d++) { + #pragma unroll + for (uint32_t ch = 0; ch < C; ch++) { + dy_dx[d * C + ch] = 0; + } + } + } + return; + } + + const uint32_t hashmap_size = offsets[level + 1] - offsets[level]; + const float scale = exp2f(level * S) * H - 1.0f; + const uint32_t resolution = (uint32_t)ceil(scale) + 1; + + // calculate coordinate + float pos[D]; + uint32_t pos_grid[D]; + + #pragma unroll + for (uint32_t d = 0; d < D; d++) { + pos[d] = inputs[d] * scale + (align_corners ? 0.0f : 0.5f); + pos_grid[d] = floorf(pos[d]); + pos[d] -= (float)pos_grid[d]; + } + + //printf("[b=%d, l=%d] pos=(%f, %f)+(%d, %d)\n", b, level, pos[0], pos[1], pos_grid[0], pos_grid[1]); + + // interpolate + scalar_t results[C] = {0}; // temp results in register + + #pragma unroll + for (uint32_t idx = 0; idx < (1 << D); idx++) { + float w = 1; + uint32_t pos_grid_local[D]; + + #pragma unroll + for (uint32_t d = 0; d < D; d++) { + if ((idx & (1 << d)) == 0) { + w *= 1 - pos[d]; + pos_grid_local[d] = pos_grid[d]; + } else { + w *= pos[d]; + pos_grid_local[d] = pos_grid[d] + 1; + } + } + + uint32_t index = get_grid_index(gridtype, align_corners, 0, hashmap_size, resolution, pos_grid_local); // Hashing + + // writing to register (fast) + #pragma unroll + for (uint32_t ch = 0; ch < C; ch++) { + results[ch] += w * grid[index + ch]; + } + + //printf("[b=%d, l=%d] int %d, idx %d, w %f, val %f\n", b, level, idx, index, w, grid[index]); + } + + // writing to global memory (slow) + #pragma unroll + for (uint32_t ch = 0; ch < C; ch++) { + outputs[ch] = results[ch]; + } + + // prepare dy_dx for calc_grad_inputs + // differentiable (soft) indexing: https://discuss.pytorch.org/t/differentiable-indexing/17647/9 + if (calc_grad_inputs) { + + dy_dx += b * D * L * C + level * D * C; // B L D C + + #pragma unroll + for (uint32_t gd = 0; gd < D; gd++) { + + scalar_t results_grad[C] = {0}; + + #pragma unroll + for (uint32_t idx = 0; idx < (1 << (D - 1)); idx++) { + float w = scale; + uint32_t pos_grid_local[D]; + + #pragma unroll + for (uint32_t nd = 0; nd < D - 1; nd++) { + const uint32_t d = (nd >= gd) ? (nd + 1) : nd; + + if ((idx & (1 << nd)) == 0) { + w *= 1 - pos[d]; + pos_grid_local[d] = pos_grid[d]; + } else { + w *= pos[d]; + pos_grid_local[d] = pos_grid[d] + 1; + } + } + + pos_grid_local[gd] = pos_grid[gd]; + uint32_t index_left = get_grid_index(gridtype, align_corners, 0, hashmap_size, resolution, pos_grid_local); + pos_grid_local[gd] = pos_grid[gd] + 1; + uint32_t index_right = get_grid_index(gridtype, align_corners, 0, hashmap_size, resolution, pos_grid_local); + + #pragma unroll + for (uint32_t ch = 0; ch < C; ch++) { + results_grad[ch] += w * (grid[index_right + ch] - grid[index_left + ch]); + } + } + + #pragma unroll + for (uint32_t ch = 0; ch < C; ch++) { + dy_dx[gd * C + ch] = results_grad[ch]; + } + } + } +} + + +template +__global__ void kernel_grid_backward( + const scalar_t * __restrict__ grad, + const float * __restrict__ inputs, + const scalar_t * __restrict__ grid, + const int * __restrict__ offsets, + scalar_t * __restrict__ grad_grid, + const uint32_t B, const uint32_t L, const float S, const uint32_t H, + const uint32_t gridtype, + const bool align_corners +) { + const uint32_t b = (blockIdx.x * blockDim.x + threadIdx.x) * N_C / C; + if (b >= B) return; + + const uint32_t level = blockIdx.y; + const uint32_t ch = (blockIdx.x * blockDim.x + threadIdx.x) * N_C - b * C; + + // locate + grad_grid += offsets[level] * C; + inputs += b * D; + grad += level * B * C + b * C + ch; // L, B, C + + const uint32_t hashmap_size = offsets[level + 1] - offsets[level]; + const float scale = exp2f(level * S) * H - 1.0f; + const uint32_t resolution = (uint32_t)ceil(scale) + 1; + + // check input range (should be in [0, 1]) + #pragma unroll + for (uint32_t d = 0; d < D; d++) { + if (inputs[d] < 0 || inputs[d] > 1) { + return; // grad is init as 0, so we simply return. + } + } + + // calculate coordinate + float pos[D]; + uint32_t pos_grid[D]; + + #pragma unroll + for (uint32_t d = 0; d < D; d++) { + pos[d] = inputs[d] * scale + (align_corners ? 0.0f : 0.5f); + pos_grid[d] = floorf(pos[d]); + pos[d] -= (float)pos_grid[d]; + } + + scalar_t grad_cur[N_C] = {0}; // fetch to register + #pragma unroll + for (uint32_t c = 0; c < N_C; c++) { + grad_cur[c] = grad[c]; + } + + // interpolate + #pragma unroll + for (uint32_t idx = 0; idx < (1 << D); idx++) { + float w = 1; + uint32_t pos_grid_local[D]; + + #pragma unroll + for (uint32_t d = 0; d < D; d++) { + if ((idx & (1 << d)) == 0) { + w *= 1 - pos[d]; + pos_grid_local[d] = pos_grid[d]; + } else { + w *= pos[d]; + pos_grid_local[d] = pos_grid[d] + 1; + } + } + + uint32_t index = get_grid_index(gridtype, align_corners, ch, hashmap_size, resolution, pos_grid_local); + + // atomicAdd for __half is slow (especially for large values), so we use __half2 if N_C % 2 == 0 + // TODO: use float which is better than __half, if N_C % 2 != 0 + if (std::is_same::value && N_C % 2 == 0) { + #pragma unroll + for (uint32_t c = 0; c < N_C; c += 2) { + // process two __half at once (by interpreting as a __half2) + __half2 v = {(__half)(w * grad_cur[c]), (__half)(w * grad_cur[c + 1])}; + atomicAdd((__half2*)&grad_grid[index + c], v); + } + // float, or __half when N_C % 2 != 0 (which means C == 1) + } else { + #pragma unroll + for (uint32_t c = 0; c < N_C; c++) { + atomicAdd(&grad_grid[index + c], w * grad_cur[c]); + } + } + } +} + + +template +__global__ void kernel_input_backward( + const scalar_t * __restrict__ grad, + const scalar_t * __restrict__ dy_dx, + scalar_t * __restrict__ grad_inputs, + uint32_t B, uint32_t L +) { + const uint32_t t = threadIdx.x + blockIdx.x * blockDim.x; + if (t >= B * D) return; + + const uint32_t b = t / D; + const uint32_t d = t - b * D; + + dy_dx += b * L * D * C; + + scalar_t result = 0; + + # pragma unroll + for (int l = 0; l < L; l++) { + # pragma unroll + for (int ch = 0; ch < C; ch++) { + result += grad[l * B * C + b * C + ch] * dy_dx[l * D * C + d * C + ch]; + } + } + + grad_inputs[t] = result; +} + + +template +void kernel_grid_wrapper(const float *inputs, const scalar_t *embeddings, const int *offsets, scalar_t *outputs, const uint32_t B, const uint32_t C, const uint32_t L, const float S, const uint32_t H, const bool calc_grad_inputs, scalar_t *dy_dx, const uint32_t gridtype, const bool align_corners) { + static constexpr uint32_t N_THREAD = 512; + const dim3 blocks_hashgrid = { div_round_up(B, N_THREAD), L, 1 }; + switch (C) { + case 1: kernel_grid<<>>(inputs, embeddings, offsets, outputs, B, L, S, H, calc_grad_inputs, dy_dx, gridtype, align_corners); break; + case 2: kernel_grid<<>>(inputs, embeddings, offsets, outputs, B, L, S, H, calc_grad_inputs, dy_dx, gridtype, align_corners); break; + case 4: kernel_grid<<>>(inputs, embeddings, offsets, outputs, B, L, S, H, calc_grad_inputs, dy_dx, gridtype, align_corners); break; + case 8: kernel_grid<<>>(inputs, embeddings, offsets, outputs, B, L, S, H, calc_grad_inputs, dy_dx, gridtype, align_corners); break; + default: throw std::runtime_error{"GridEncoding: C must be 1, 2, 4, or 8."}; + } +} + +// inputs: [B, D], float, in [0, 1] +// embeddings: [sO, C], float +// offsets: [L + 1], uint32_t +// outputs: [L, B, C], float (L first, so only one level of hashmap needs to fit into cache at a time.) +// H: base resolution +// dy_dx: [B, L * D * C] +template +void grid_encode_forward_cuda(const float *inputs, const scalar_t *embeddings, const int *offsets, scalar_t *outputs, const uint32_t B, const uint32_t D, const uint32_t C, const uint32_t L, const float S, const uint32_t H, const bool calc_grad_inputs, scalar_t *dy_dx, const uint32_t gridtype, const bool align_corners) { + switch (D) { + case 1: kernel_grid_wrapper(inputs, embeddings, offsets, outputs, B, C, L, S, H, calc_grad_inputs, dy_dx, gridtype, align_corners); break; + case 2: kernel_grid_wrapper(inputs, embeddings, offsets, outputs, B, C, L, S, H, calc_grad_inputs, dy_dx, gridtype, align_corners); break; + case 3: kernel_grid_wrapper(inputs, embeddings, offsets, outputs, B, C, L, S, H, calc_grad_inputs, dy_dx, gridtype, align_corners); break; + case 4: kernel_grid_wrapper(inputs, embeddings, offsets, outputs, B, C, L, S, H, calc_grad_inputs, dy_dx, gridtype, align_corners); break; + case 5: kernel_grid_wrapper(inputs, embeddings, offsets, outputs, B, C, L, S, H, calc_grad_inputs, dy_dx, gridtype, align_corners); break; + default: throw std::runtime_error{"GridEncoding: D must be 1, 2, 3, 4, or 5."}; + } + +} + +template +void kernel_grid_backward_wrapper(const scalar_t *grad, const float *inputs, const scalar_t *embeddings, const int *offsets, scalar_t *grad_embeddings, const uint32_t B, const uint32_t C, const uint32_t L, const float S, const uint32_t H, const bool calc_grad_inputs, scalar_t *dy_dx, scalar_t *grad_inputs, const uint32_t gridtype, const bool align_corners) { + static constexpr uint32_t N_THREAD = 256; + const uint32_t N_C = std::min(2u, C); // n_features_per_thread + const dim3 blocks_hashgrid = { div_round_up(B * C / N_C, N_THREAD), L, 1 }; + switch (C) { + case 1: + kernel_grid_backward<<>>(grad, inputs, embeddings, offsets, grad_embeddings, B, L, S, H, gridtype, align_corners); + if (calc_grad_inputs) kernel_input_backward<<>>(grad, dy_dx, grad_inputs, B, L); + break; + case 2: + kernel_grid_backward<<>>(grad, inputs, embeddings, offsets, grad_embeddings, B, L, S, H, gridtype, align_corners); + if (calc_grad_inputs) kernel_input_backward<<>>(grad, dy_dx, grad_inputs, B, L); + break; + case 4: + kernel_grid_backward<<>>(grad, inputs, embeddings, offsets, grad_embeddings, B, L, S, H, gridtype, align_corners); + if (calc_grad_inputs) kernel_input_backward<<>>(grad, dy_dx, grad_inputs, B, L); + break; + case 8: + kernel_grid_backward<<>>(grad, inputs, embeddings, offsets, grad_embeddings, B, L, S, H, gridtype, align_corners); + if (calc_grad_inputs) kernel_input_backward<<>>(grad, dy_dx, grad_inputs, B, L); + break; + default: throw std::runtime_error{"GridEncoding: C must be 1, 2, 4, or 8."}; + } +} + + +// grad: [L, B, C], float +// inputs: [B, D], float, in [0, 1] +// embeddings: [sO, C], float +// offsets: [L + 1], uint32_t +// grad_embeddings: [sO, C] +// H: base resolution +template +void grid_encode_backward_cuda(const scalar_t *grad, const float *inputs, const scalar_t *embeddings, const int *offsets, scalar_t *grad_embeddings, const uint32_t B, const uint32_t D, const uint32_t C, const uint32_t L, const float S, const uint32_t H, const bool calc_grad_inputs, scalar_t *dy_dx, scalar_t *grad_inputs, const uint32_t gridtype, const bool align_corners) { + switch (D) { + case 1: kernel_grid_backward_wrapper(grad, inputs, embeddings, offsets, grad_embeddings, B, C, L, S, H, calc_grad_inputs, dy_dx, grad_inputs, gridtype, align_corners); break; + case 2: kernel_grid_backward_wrapper(grad, inputs, embeddings, offsets, grad_embeddings, B, C, L, S, H, calc_grad_inputs, dy_dx, grad_inputs, gridtype, align_corners); break; + case 3: kernel_grid_backward_wrapper(grad, inputs, embeddings, offsets, grad_embeddings, B, C, L, S, H, calc_grad_inputs, dy_dx, grad_inputs, gridtype, align_corners); break; + case 4: kernel_grid_backward_wrapper(grad, inputs, embeddings, offsets, grad_embeddings, B, C, L, S, H, calc_grad_inputs, dy_dx, grad_inputs, gridtype, align_corners); break; + case 5: kernel_grid_backward_wrapper(grad, inputs, embeddings, offsets, grad_embeddings, B, C, L, S, H, calc_grad_inputs, dy_dx, grad_inputs, gridtype, align_corners); break; + default: throw std::runtime_error{"GridEncoding: D must be 1, 2, 3, 4, or 5."}; + } +} + + + +void grid_encode_forward(const at::Tensor inputs, const at::Tensor embeddings, const at::Tensor offsets, at::Tensor outputs, const uint32_t B, const uint32_t D, const uint32_t C, const uint32_t L, const float S, const uint32_t H, const bool calc_grad_inputs, at::Tensor dy_dx, const uint32_t gridtype, const bool align_corners) { + CHECK_CUDA(inputs); + CHECK_CUDA(embeddings); + CHECK_CUDA(offsets); + CHECK_CUDA(outputs); + CHECK_CUDA(dy_dx); + + CHECK_CONTIGUOUS(inputs); + CHECK_CONTIGUOUS(embeddings); + CHECK_CONTIGUOUS(offsets); + CHECK_CONTIGUOUS(outputs); + CHECK_CONTIGUOUS(dy_dx); + + CHECK_IS_FLOATING(inputs); + CHECK_IS_FLOATING(embeddings); + CHECK_IS_INT(offsets); + CHECK_IS_FLOATING(outputs); + CHECK_IS_FLOATING(dy_dx); + + AT_DISPATCH_FLOATING_TYPES_AND_HALF( + embeddings.scalar_type(), "grid_encode_forward", ([&] { + grid_encode_forward_cuda(inputs.data_ptr(), embeddings.data_ptr(), offsets.data_ptr(), outputs.data_ptr(), B, D, C, L, S, H, calc_grad_inputs, dy_dx.data_ptr(), gridtype, align_corners); + })); +} + +void grid_encode_backward(const at::Tensor grad, const at::Tensor inputs, const at::Tensor embeddings, const at::Tensor offsets, at::Tensor grad_embeddings, const uint32_t B, const uint32_t D, const uint32_t C, const uint32_t L, const float S, const uint32_t H, const bool calc_grad_inputs, const at::Tensor dy_dx, at::Tensor grad_inputs, const uint32_t gridtype, const bool align_corners) { + CHECK_CUDA(grad); + CHECK_CUDA(inputs); + CHECK_CUDA(embeddings); + CHECK_CUDA(offsets); + CHECK_CUDA(grad_embeddings); + CHECK_CUDA(dy_dx); + CHECK_CUDA(grad_inputs); + + CHECK_CONTIGUOUS(grad); + CHECK_CONTIGUOUS(inputs); + CHECK_CONTIGUOUS(embeddings); + CHECK_CONTIGUOUS(offsets); + CHECK_CONTIGUOUS(grad_embeddings); + CHECK_CONTIGUOUS(dy_dx); + CHECK_CONTIGUOUS(grad_inputs); + + CHECK_IS_FLOATING(grad); + CHECK_IS_FLOATING(inputs); + CHECK_IS_FLOATING(embeddings); + CHECK_IS_INT(offsets); + CHECK_IS_FLOATING(grad_embeddings); + CHECK_IS_FLOATING(dy_dx); + CHECK_IS_FLOATING(grad_inputs); + + AT_DISPATCH_FLOATING_TYPES_AND_HALF( + grad.scalar_type(), "grid_encode_backward", ([&] { + grid_encode_backward_cuda(grad.data_ptr(), inputs.data_ptr(), embeddings.data_ptr(), offsets.data_ptr(), grad_embeddings.data_ptr(), B, D, C, L, S, H, calc_grad_inputs, dy_dx.data_ptr(), grad_inputs.data_ptr(), gridtype, align_corners); + })); + +} diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/bundlesdf/mycuda/torch_ngp_grid_encoder/gridencoder.h b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/bundlesdf/mycuda/torch_ngp_grid_encoder/gridencoder.h new file mode 100644 index 0000000000000000000000000000000000000000..b093e78272ee55a309fadfa08db6a2943c247700 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/bundlesdf/mycuda/torch_ngp_grid_encoder/gridencoder.h @@ -0,0 +1,15 @@ +#ifndef _HASH_ENCODE_H +#define _HASH_ENCODE_H + +#include +#include + +// inputs: [B, D], float, in [0, 1] +// embeddings: [sO, C], float +// offsets: [L + 1], uint32_t +// outputs: [B, L * C], float +// H: base resolution +void grid_encode_forward(const at::Tensor inputs, const at::Tensor embeddings, const at::Tensor offsets, at::Tensor outputs, const uint32_t B, const uint32_t D, const uint32_t C, const uint32_t L, const float S, const uint32_t H, const bool calc_grad_inputs, at::Tensor dy_dx, const uint32_t gridtype, const bool align_corners); +void grid_encode_backward(const at::Tensor grad, const at::Tensor inputs, const at::Tensor embeddings, const at::Tensor offsets, at::Tensor grad_embeddings, const uint32_t B, const uint32_t D, const uint32_t C, const uint32_t L, const float S, const uint32_t H, const bool calc_grad_inputs, const at::Tensor dy_dx, at::Tensor grad_inputs, const uint32_t gridtype, const bool align_corners); + +#endif \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/bundlesdf/nerf_helpers.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/bundlesdf/nerf_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..0b8e0f2f4a23c4fb5e1ba5a365502aedbb742cf8 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/bundlesdf/nerf_helpers.py @@ -0,0 +1,475 @@ +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. + + +import torch,pdb,os,sys +import torch.nn as nn +import torch.nn.functional as F +import numpy as np +code_dir = os.path.dirname(os.path.realpath(__file__)) +sys.path.append(f'{code_dir}/../') +from Utils import * +from pytorch3d.transforms import so3_log_map,so3_exp_map,se3_exp_map + +img2mse = lambda x, y : torch.mean((x - y) ** 2) +img2mae = lambda x, y: (torch.abs(x - y)).mean() +mse2psnr = lambda x : -10. * torch.log(x) / torch.log(torch.Tensor([10.])) +to8b = lambda x : (255*np.clip(x,0,1)).astype(np.uint8) + + +class FeatureArray(nn.Module): + """ + Per-frame corrective latent code. + """ + + def __init__(self, num_frames, num_channels): + super().__init__() + + self.num_frames = num_frames + self.num_channels = num_channels + + self.data = nn.parameter.Parameter(torch.normal(0,1,size=[num_frames, num_channels]).float(), requires_grad=True) + self.register_parameter('data',self.data) + + + def __call__(self, ids): + return self.data[ids] + + +class PoseArray(nn.Module): + def __init__(self, num_frames,max_trans,max_rot): + super().__init__() + self.num_frames = num_frames + self.max_trans = max_trans + self.max_rot = max_rot + self.data = nn.parameter.Parameter(torch.zeros([num_frames, 6]).float(), requires_grad=True) + self.register_parameter('data',self.data) + + + def get_matrices(self,ids): + if not torch.is_tensor(ids): + ids = torch.tensor(ids).long() + theta = torch.tanh(self.data) + trans = theta[:,:3] * self.max_trans + rot = theta[:,3:6] * self.max_rot/180.0*np.pi + Ts_data = se3_exp_map(torch.cat((trans,rot),dim=-1)).permute(0,2,1) + Ts = torch.eye(4, device=self.data.device).reshape(1,4,4).repeat(len(ids),1,1) + mask = ids!=0 + Ts[mask] = Ts_data[ids[mask]] + return Ts + + + +class SHEncoder(nn.Module): + '''Spherical encoding + ''' + def __init__(self, input_dim=3, degree=4): + + super().__init__() + + self.input_dim = input_dim + self.degree = degree + + assert self.input_dim == 3 + assert self.degree >= 1 and self.degree <= 5 + + self.out_dim = degree ** 2 + + self.C0 = 0.28209479177387814 + self.C1 = 0.4886025119029199 + self.C2 = [ + 1.0925484305920792, + -1.0925484305920792, + 0.31539156525252005, + -1.0925484305920792, + 0.5462742152960396 + ] + self.C3 = [ + -0.5900435899266435, + 2.890611442640554, + -0.4570457994644658, + 0.3731763325901154, + -0.4570457994644658, + 1.445305721320277, + -0.5900435899266435 + ] + self.C4 = [ + 2.5033429417967046, + -1.7701307697799304, + 0.9461746957575601, + -0.6690465435572892, + 0.10578554691520431, + -0.6690465435572892, + 0.47308734787878004, + -1.7701307697799304, + 0.6258357354491761 + ] + + def forward(self, input, **kwargs): + + result = torch.empty((*input.shape[:-1], self.out_dim), dtype=input.dtype, device=input.device) + x, y, z = input.unbind(-1) + + result[..., 0] = self.C0 + if self.degree > 1: + result[..., 1] = -self.C1 * y + result[..., 2] = self.C1 * z + result[..., 3] = -self.C1 * x + if self.degree > 2: + xx, yy, zz = x * x, y * y, z * z + xy, yz, xz = x * y, y * z, x * z + result[..., 4] = self.C2[0] * xy + result[..., 5] = self.C2[1] * yz + result[..., 6] = self.C2[2] * (2.0 * zz - xx - yy) + #result[..., 6] = self.C2[2] * (3.0 * zz - 1) # xx + yy + zz == 1, but this will lead to different backward gradients, interesting... + result[..., 7] = self.C2[3] * xz + result[..., 8] = self.C2[4] * (xx - yy) + if self.degree > 3: + result[..., 9] = self.C3[0] * y * (3 * xx - yy) + result[..., 10] = self.C3[1] * xy * z + result[..., 11] = self.C3[2] * y * (4 * zz - xx - yy) + result[..., 12] = self.C3[3] * z * (2 * zz - 3 * xx - 3 * yy) + result[..., 13] = self.C3[4] * x * (4 * zz - xx - yy) + result[..., 14] = self.C3[5] * z * (xx - yy) + result[..., 15] = self.C3[6] * x * (xx - 3 * yy) + if self.degree > 4: + result[..., 16] = self.C4[0] * xy * (xx - yy) + result[..., 17] = self.C4[1] * yz * (3 * xx - yy) + result[..., 18] = self.C4[2] * xy * (7 * zz - 1) + result[..., 19] = self.C4[3] * yz * (7 * zz - 3) + result[..., 20] = self.C4[4] * (zz * (35 * zz - 30) + 3) + result[..., 21] = self.C4[5] * xz * (7 * zz - 3) + result[..., 22] = self.C4[6] * (xx - yy) * (7 * zz - 1) + result[..., 23] = self.C4[7] * xz * (xx - 3 * yy) + result[..., 24] = self.C4[8] * (xx * (xx - 3 * yy) - yy * (3 * xx - yy)) + + return result + + +class Embedder(nn.Module): + def __init__(self, **kwargs): + super().__init__() + self.kwargs = kwargs + self.create_embedding_fn() + + def create_embedding_fn(self): + embed_fns = [] + d = self.kwargs['input_dims'] + out_dim = 0 + if self.kwargs['include_input']: + embed_fns.append(lambda x : x) + out_dim += d + + max_freq = self.kwargs['max_freq_log2'] + N_freqs = self.kwargs['num_freqs'] + + if self.kwargs['log_sampling']: + freq_bands = 2.**torch.linspace(0., max_freq, steps=N_freqs) + else: + freq_bands = torch.linspace(2.**0., 2.**max_freq, steps=N_freqs) + + for freq in freq_bands: + for p_fn in self.kwargs['periodic_fns']: + embed_fns.append(lambda x, p_fn=p_fn, freq=freq : p_fn(x * freq)) + out_dim += d + + self.embed_fns = embed_fns + self.out_dim = out_dim + + def forward(self, inputs): + return torch.cat([fn(inputs) for fn in self.embed_fns], -1) + + +def get_embedder(multires, cfg, i=0, octree_m=None): + if i == -1: + return nn.Identity(), 3 + elif i==0: + embed_kwargs = { + 'include_input' : True, + 'input_dims' : 3, + 'max_freq_log2' : multires-1, + 'num_freqs' : multires, + 'log_sampling' : True, + 'periodic_fns' : [torch.sin, torch.cos], + } + + embed = Embedder(**embed_kwargs) + out_dim = embed.out_dim + elif i==1: + from mycuda.torch_ngp_grid_encoder.grid import GridEncoder + embed = GridEncoder(input_dim=3, n_levels=cfg['num_levels'], log2_hashmap_size=cfg['log2_hashmap_size'], desired_resolution=cfg['finest_res'], base_resolution=cfg['base_res'], level_dim=cfg['feature_grid_dim']) + print(embed) + out_dim = embed.out_dim + elif i==2: + embed = SHEncoder(degree=cfg['multires_views']) + out_dim = embed.out_dim + return embed, out_dim + + + +def mesh_to_real_world(mesh,pose_offset,translation,sc_factor): + ''' + @pose_offset: optimized delta pose of the first frame. Usually it's identity + ''' + mesh.vertices = mesh.vertices/sc_factor - np.array(translation).reshape(1,3) + mesh.apply_transform(pose_offset) + return mesh + + +def get_optimized_poses_in_real_world(poses_normalized, pose_array, sc_factor, translation): + ''' + @poses_normalized: np array, cam_in_ob (opengl convention), normalized to [-1,1] and centered + @pose_array: PoseArray, delta poses + Return: + cam_in_ob, real-world unit, opencv convention + ''' + original_poses = poses_normalized.copy() + original_poses[:, :3, 3] /= sc_factor # To true world scale + original_poses[:, :3, 3] -= translation + + # Apply pose transformation + tf = pose_array.get_matrices(np.arange(len(poses_normalized))).reshape(-1,4,4).data.cpu().numpy() + optimized_poses = tf@poses_normalized + + optimized_poses = np.array(optimized_poses).astype(np.float32) + optimized_poses[:, :3, 3] /= sc_factor + optimized_poses[:, :3, 3] -= translation + + original_init_ob_in_cam = optimized_poses[0].copy() + offset = np.linalg.inv(original_init_ob_in_cam)@original_poses[0] + for i in range(len(optimized_poses)): + new_ob_in_cam = optimized_poses[i]@offset + optimized_poses[i] = new_ob_in_cam + optimized_poses[i] = optimized_poses[i]@glcam_in_cvcam + + return optimized_poses,offset + +def preprocess_data(rgbs,depths,masks,normal_maps,poses,sc_factor,translation): + ''' + @rgbs: np array (N,H,W,3) + @depths: (N,H,W) + @masks: (N,H,W) + @normal_maps: (N,H,W,3) + @poses: (N,4,4) + ''' + depths[depths<0.001] = BAD_DEPTH + if masks is not None: + rgbs[masks==0] = BAD_COLOR + depths[masks==0] = BAD_DEPTH + if normal_maps is not None: + normal_maps[...,[1,2]] *= -1 # To OpenGL + normal_maps[masks==0] = 0 + masks = masks[...,None] + + rgbs = (rgbs / 255.0).astype(np.float32) + depths *= sc_factor + depths = depths[...,None] + poses[:, :3, 3] += translation + poses[:, :3, 3] *= sc_factor + return rgbs,depths,masks,normal_maps,poses + + +class NeRFSmall(nn.Module): + def __init__(self,num_layers=3,hidden_dim=64,geo_feat_dim=15,num_layers_color=4,hidden_dim_color=64,input_ch=3, input_ch_views=3): + super(NeRFSmall, self).__init__() + + self.input_ch = input_ch + self.input_ch_views = input_ch_views + + # sigma network + self.num_layers = num_layers + self.hidden_dim = hidden_dim + self.geo_feat_dim = geo_feat_dim + + sigma_net = [] + for l in range(num_layers): + if l == 0: + in_dim = self.input_ch + else: + in_dim = hidden_dim + + if l == num_layers - 1: + out_dim = 1 + self.geo_feat_dim # 1 sigma + 15 SH features for color + else: + out_dim = hidden_dim + + sigma_net.append(nn.Linear(in_dim, out_dim, bias=True)) + if l!=num_layers-1: + sigma_net.append(nn.ReLU(inplace=True)) + + self.sigma_net = nn.Sequential(*sigma_net) + torch.nn.init.constant_(self.sigma_net[-1].bias, 0.1) # Encourage last layer predict positive SDF + + # color network + self.num_layers_color = num_layers_color + self.hidden_dim_color = hidden_dim_color + + color_net = [] + for l in range(num_layers_color): + if l == 0: + in_dim = self.input_ch_views + self.geo_feat_dim + else: + in_dim = hidden_dim + + if l == num_layers_color - 1: + out_dim = 3 # 3 rgb + else: + out_dim = hidden_dim + + color_net.append(nn.Linear(in_dim, out_dim, bias=True)) + if l!=num_layers_color-1: + color_net.append(nn.ReLU(inplace=True)) + + self.color_net = nn.Sequential(*color_net) + + def forward_sdf(self,x): + ''' + @x: embedded positions + ''' + h = self.sigma_net(x) + sigma, geo_feat = h[..., 0], h[..., 1:] + return sigma + + + def forward(self, x): + x = x.float() + input_pts, input_views = torch.split(x, [self.input_ch, self.input_ch_views], dim=-1) + + # sigma + h = input_pts + h = self.sigma_net(h) + + sigma, geo_feat = h[..., 0], h[..., 1:] + + # color + h = torch.cat([input_views, geo_feat], dim=-1) + color = self.color_net(h) + + outputs = torch.cat([color, sigma.unsqueeze(dim=-1)], -1) + + return outputs + + +def sample_pdf(bins, weights, N_samples, det=False): + weights = weights + 1e-5 # prevent nans + pdf = weights / torch.sum(weights, -1, keepdim=True) + cdf = torch.cumsum(pdf, -1) + cdf = torch.cat([torch.zeros_like(cdf[...,:1]), cdf], -1) # (batch, len(bins)) + + if det: + u = torch.linspace(0., 1., steps=N_samples) + u = u.expand(list(cdf.shape[:-1]) + [N_samples]) + else: + u = torch.rand(list(cdf.shape[:-1]) + [N_samples]) + + u = u.contiguous() + inds = torch.searchsorted(cdf, u, right=True) + below = torch.max(torch.zeros_like(inds-1), inds-1) + above = torch.min((cdf.shape[-1]-1) * torch.ones_like(inds), inds) + inds_g = torch.stack([below, above], -1) # (batch, N_samples, 2) + + matched_shape = [inds_g.shape[0], inds_g.shape[1], cdf.shape[-1]] + cdf_g = torch.gather(cdf.unsqueeze(1).expand(matched_shape), 2, inds_g) + bins_g = torch.gather(bins.unsqueeze(1).expand(matched_shape), 2, inds_g) + + denom = (cdf_g[...,1]-cdf_g[...,0]) + denom = torch.where(denom<1e-5, torch.ones_like(denom), denom) + t = (u-cdf_g[...,0])/denom + samples = bins_g[...,0] + t * (bins_g[...,1]-bins_g[...,0]) + + return samples + + + +def get_camera_rays_np(H, W, K): + """Get ray origins, directions from a pinhole camera.""" + i, j = np.meshgrid(np.arange(W, dtype=np.float32), + np.arange(H, dtype=np.float32), indexing='xy') + dirs = np.stack([(i - K[0,2])/K[0,0], -(j - K[1,2])/K[1,1], -np.ones_like(i)], axis=-1) + return dirs + + + +def get_masks(z_vals, target_d, truncation, cfg, dir_norm=None): + valid_depth_mask = (target_d>=cfg['near']*cfg['sc_factor']) & (target_d<=cfg['far']*cfg['sc_factor']) + front_mask = (z_vals < target_d - truncation) + back_mask = (z_vals > target_d + truncation*cfg['neg_trunc_ratio']) + + sdf_mask = (1.0 - front_mask.float()) * (1.0 - back_mask.float()) * valid_depth_mask + + num_fs_samples = front_mask.sum() + num_sdf_samples = sdf_mask.sum() + num_samples = num_sdf_samples + num_fs_samples + fs_weight = 0.5 + sdf_weight = 1.0 - fs_weight + return front_mask.bool(), sdf_mask.bool(), fs_weight, sdf_weight + + +def get_sdf_loss(z_vals, target_d, predicted_sdf, truncation, cfg, return_mask=False, sample_weights=None, rays_d=None): + dir_norm = rays_d.norm(dim=-1,keepdim=True) + front_mask, sdf_mask, fs_weight, sdf_weight = get_masks(z_vals, target_d, truncation, cfg, dir_norm=dir_norm) + front_mask = front_mask.bool() + + mask = (target_d>cfg['far']*cfg['sc_factor']) & (predicted_sdf tymax) | (tymin > tmax)] = 0 + tmin[tymin>tmin] = tymin[tymin>tmin] + tmax[tymax tzmax) | (tzmin > tmax)] = 0 + tmin[tzmin>tmin] = tzmin[tzmin>tmin] #(N) + tmax[tzmax=0 + near = (dirs_unit*tmin.reshape(-1,1))[:,2] + far = (dirs_unit*tmax.reshape(-1,1))[:,2] + good_rays = rays[ishit] + near = near[ishit] + far = far[ishit] + near = np.abs(near) + far = np.abs(far) + good_rays = np.concatenate((good_rays,near.reshape(-1,1),far.reshape(-1,1)), axis=-1) #(N,8+2) + + return good_rays + +@torch.no_grad() +def sample_rays_uniform(N_samples,near,far,lindisp=False,perturb=True): + ''' + @near: (N_ray,1) + ''' + N_ray = near.shape[0] + t_vals = torch.linspace(0., 1., steps=N_samples, device=near.device).reshape(1,-1) + if not lindisp: + z_vals = near * (1.-t_vals) + far * (t_vals) + else: + z_vals = 1./(1./near * (1.-t_vals) + 1./far * (t_vals)) #(N_ray,N_sample) + + if perturb > 0.: + mids = .5 * (z_vals[...,1:] + z_vals[...,:-1]) + upper = torch.cat([mids, z_vals[...,-1:]], -1) + lower = torch.cat([z_vals[...,:1], mids], -1) + t_rand = torch.rand(z_vals.shape, device=far.device) + z_vals = lower + (upper - lower) * t_rand + z_vals = torch.clip(z_vals,near,far) + + return z_vals.reshape(N_ray,N_samples) + + +class DataLoader: + def __init__(self,rays,batch_size): + self.rays = rays + self.batch_size = batch_size + self.pos = 0 + self.ids = torch.randperm(len(self.rays)) + + def __next__(self): + if self.pos+self.batch_size0) & (rays[:,self.ray_depth_slice]<=self.cfg['far']*self.cfg['sc_factor']) + rays_dir = rays[mask][:,self.ray_dir_slice] + rays_depth = rays[mask][:,self.ray_depth_slice] + pts3d = rays_dir*rays_depth.reshape(-1,1) + frame_ids = rays[mask][:,self.ray_frame_id_slice].astype(int) + pts3d_w = (self.poses[frame_ids]@to_homo(pts3d)[...,None])[:,:3,0] + logging.info(f"Denoising rays based on octree cloud") + + kdtree = cKDTree(self.build_octree_pts) + dists,indices = kdtree.query(pts3d_w,k=1,workers=-1) + bad_mask = dists>0.02*self.cfg['sc_factor'] + bad_ids = np.arange(len(rays))[mask][bad_mask] + rays[bad_ids,self.ray_depth_slice] = BAD_DEPTH*self.cfg['sc_factor'] + rays[bad_ids, self.ray_type_slice] = 1 + rays = rays[rays[:,self.ray_type_slice]==0] + logging.info(f"bad_mask#={bad_mask.sum()}") + + rays = torch.tensor(rays, dtype=torch.float).cuda() + + self.rays = rays + print("rays",rays.shape) + self.data_loader = DataLoader(rays=self.rays, batch_size=self.cfg['N_rand']) + + + def create_nerf(self,device=torch.device("cuda")): + """Instantiate NeRF's MLP model. + """ + models = {} + embed_fn, input_ch = get_embedder(self.cfg['multires'], self.cfg, i=self.cfg['i_embed'], octree_m=self.octree_m) + embed_fn = embed_fn.to(device) + models['embed_fn'] = embed_fn + + input_ch_views = 0 + embeddirs_fn = None + if self.cfg['use_viewdirs']: + embeddirs_fn, input_ch_views = get_embedder(self.cfg['multires_views'], self.cfg, i=self.cfg['i_embed_views'], octree_m=self.octree_m) + models['embeddirs_fn'] = embeddirs_fn + + output_ch = 4 + skips = [4] + + model = NeRFSmall(num_layers=2,hidden_dim=64,geo_feat_dim=15,num_layers_color=3,hidden_dim_color=64,input_ch=input_ch, input_ch_views=input_ch_views+self.cfg['frame_features']).to(device) + model = model.to(device) + models['model'] = model + + model_fine = None + if self.cfg['N_importance'] > 0: + if not self.cfg['share_coarse_fine']: + model_fine = NeRFSmall(num_layers=2,hidden_dim=64,geo_feat_dim=15,num_layers_color=3,hidden_dim_color=64,input_ch=input_ch, input_ch_views=input_ch_views).to(device) + models['model_fine'] = model_fine + + # Create feature array + num_training_frames = len(self.images) + feature_array = None + if self.cfg['frame_features'] > 0: + feature_array = FeatureArray(num_training_frames, self.cfg['frame_features']).to(device) + models['feature_array'] = feature_array + # Create pose array + pose_array = None + if self.cfg['optimize_poses']: + pose_array = PoseArray(num_training_frames,max_trans=self.cfg['max_trans']*self.cfg['sc_factor'],max_rot=self.cfg['max_rot']).to(device) + models['pose_array'] = pose_array + self.models = models + + + + def make_frame_rays(self,frame_id): + mask = self.masks[frame_id,...,0].copy() + rays = get_camera_rays_np(self.H, self.W, self.K) # [self.H, self.W, 3] We create rays frame-by-frame to save memory + rays = np.concatenate([rays, self.images[frame_id]], -1) # [H, W, 6] + rays = np.concatenate([rays, self.depths[frame_id]], -1) # [H, W, 7] + rays = np.concatenate([rays, self.masks[frame_id]>0], -1) # [H, W, 8] + if self.normal_maps is not None: + rays = np.concatenate([rays, self.normal_maps[frame_id]], -1) # [H, W, 11] + rays = np.concatenate([rays, frame_id*np.ones(self.depths[frame_id].shape)], -1) # [H, W, 12] + ray_types = np.zeros((self.H,self.W,1)) # 0 is good; 1 is invalid depth (uncertain) + invalid_depth = ((self.depths[frame_id,...,0]self.cfg['far']*self.cfg['sc_factor'])) & (mask>0) + ray_types[invalid_depth] = 1 + rays = np.concatenate((rays,ray_types), axis=-1) + self.ray_dir_slice = [0,1,2] + self.ray_rgb_slice = [3,4,5] + self.ray_depth_slice = 6 + self.ray_mask_slice = 7 + if self.normal_maps is not None: + self.ray_normal_slice = [8,9,10] + self.ray_frame_id_slice = 11 + self.ray_type_slice = 12 + else: + self.ray_frame_id_slice = 8 + self.ray_type_slice = 9 + + n = rays.shape[-1] + + ########## Option2: dilate + down_scale_ratio = int(self.cfg['down_scale_ratio']) + if frame_id==0: #!NOTE first frame ob mask is assumed perfect + kernel = np.ones((100, 100), np.uint8) + mask = cv2.dilate(mask.astype(np.uint8), kernel, iterations=1) + if self.occ_masks is not None: + mask[self.occ_masks[frame_id]>0] = 0 + else: + dilate = 60//down_scale_ratio + kernel = np.ones((dilate, dilate), np.uint8) + mask = cv2.dilate(mask.astype(np.uint8), kernel, iterations=1) + if self.occ_masks is not None: + mask[self.occ_masks[frame_id]>0] = 0 + + + if self.cfg['rays_valid_depth_only']: + mask[invalid_depth] = 0 + + vs,us = np.where(mask>0) + cur_rays = rays[vs,us].reshape(-1,n) + cur_rays = cur_rays[cur_rays[:,self.ray_type_slice]==0] + cur_rays = compute_near_far_and_filter_rays(self.poses[frame_id],cur_rays,self.cfg) + if self.normal_maps is not None: + self.ray_near_slice = 13 + self.ray_far_slice = 14 + else: + self.ray_near_slice = 10 + self.ray_far_slice = 11 + + if self.cfg['use_octree']: + rays_o_world = (self.poses[frame_id]@to_homo(np.zeros((len(cur_rays),3))).T).T[:,:3] + rays_o_world = torch.from_numpy(rays_o_world).cuda().float() + rays_unit_d_cam = cur_rays[:,:3]/np.linalg.norm(cur_rays[:,:3],axis=-1).reshape(-1,1) + rays_d_world = (self.poses[frame_id][:3,:3]@rays_unit_d_cam.T).T + rays_d_world = torch.from_numpy(rays_d_world).cuda().float() + + vox_size = self.cfg['octree_raytracing_voxel_size']*self.cfg['sc_factor'] + level = int(np.floor(np.log2(2.0/vox_size))) + near,far,_,ray_depths_in_out = self.octree_m.ray_trace(rays_o_world,rays_d_world,level=level) + near = near.cpu().numpy() + valid = (near>0).reshape(-1) + cur_rays = cur_rays[valid] + + return cur_rays + + + def build_octree(self): + if self.cfg['save_octree_clouds']: + dir = f"{self.cfg['save_dir']}/build_octree_cloud.ply" + pcd = toOpen3dCloud(self.build_octree_pts) + o3d.io.write_point_cloud(dir,pcd) + if self._run is not None: + self._run.add_artifact(dir) + pts = torch.tensor(self.build_octree_pts).cuda().float() # Must be within [-1,1] + octree_smallest_voxel_size = self.cfg['octree_smallest_voxel_size']*self.cfg['sc_factor'] + finest_n_voxels = 2.0/octree_smallest_voxel_size + max_level = int(np.round(np.log2(finest_n_voxels))) + octree_smallest_voxel_size = 2.0/(2**max_level) + + #################### Dilate + dilate_radius = int(np.round(self.cfg['octree_dilate_size']/octree_smallest_voxel_size)) + dilate_radius = max(1, dilate_radius) + logging.info(f"Octree voxel dilate_radius:{dilate_radius}") + shifts = [] + for dx in [-1,0,1]: + for dy in [-1,0,1]: + for dz in [-1,0,1]: + shifts.append([dx,dy,dz]) + shifts = torch.tensor(shifts).cuda().long() # (27,3) + coords = torch.floor((pts+1)/octree_smallest_voxel_size).long() #(N,3) + dilated_coords = coords.detach().clone() + for iter in range(dilate_radius): + dilated_coords = (dilated_coords[None].expand(shifts.shape[0],-1,-1) + shifts[:,None]).reshape(-1,3) + dilated_coords = torch.unique(dilated_coords,dim=0) + pts = (dilated_coords+0.5) * octree_smallest_voxel_size - 1 + pts = torch.clip(pts,-1,1) + + if self.cfg['save_octree_clouds']: + pcd = toOpen3dCloud(pts.data.cpu().numpy()) + dir = f"{self.cfg['save_dir']}/build_octree_cloud_dilated.ply" + o3d.io.write_point_cloud(dir,pcd) + if self._run is not None: + self._run.add_artifact(dir) + #################### + + assert pts.min()>=-1 and pts.max()<=1 + self.octree_m = OctreeManager(pts, max_level) + + if self.cfg['save_octree_clouds']: + dir = f"{self.cfg['save_dir']}/octree_boxes_max_level.ply" + m = self.octree_m.draw(level=max_level,method='point') + m.export(dir) + if self._run is not None: + self._run.add_artifact(dir) + vox_size = self.cfg['octree_raytracing_voxel_size']*self.cfg['sc_factor'] + level = int(np.round(np.log2(2.0/vox_size))) + if self.cfg['save_octree_clouds']: + dir = f"{self.cfg['save_dir']}/octree_boxes_ray_tracing_level.ply" + m = self.octree_m.draw(level=level,method='point') + m.export(dir) + if self._run is not None: + self._run.add_artifact(dir) + + + def create_optimizer(self): + params = [] + for k in self.models: + if self.models[k] is not None and k!='pose_array': + params += list(self.models[k].parameters()) + + param_groups = [{'name':'basic', 'params':params, 'lr':self.cfg['lrate']}] + if self.models['pose_array'] is not None: + param_groups.append({'name':'pose_array', 'params':self.models['pose_array'].parameters(), 'lr':self.cfg['lrate_pose']}) + + self.optimizer = torch.optim.Adam(param_groups, betas=(0.9, 0.999),weight_decay=0,eps=1e-15) + + self.param_groups_init = copy.deepcopy(self.optimizer.param_groups) + + + def save_weights(self,out_file,models): + data = { + 'global_step': self.global_step, + 'model': models['model'].state_dict(), + 'optimizer': self.optimizer.state_dict(), + } + if 'model_fine' in models and models['model_fine'] is not None: + data['model_fine'] = models['model_fine'].state_dict() + if models['embed_fn'] is not None: + data['embed_fn'] = models['embed_fn'].state_dict() + if models['embeddirs_fn'] is not None: + data['embeddirs_fn'] = models['embeddirs_fn'].state_dict() + if self.cfg['optimize_poses']>0: + data['pose_array'] = models['pose_array'].state_dict() + if self.cfg['frame_features'] > 0: + data['feature_array'] = models['feature_array'].state_dict() + if self.octree_m is not None: + data['octree'] = self.octree_m.octree + dir = out_file + torch.save(data,dir) + print('Saved checkpoints at', dir) + if self._run is not None: + self._run.add_artifact(dir) + dir1 = copy.deepcopy(dir) + dir = f'{os.path.dirname(out_file)}/model_latest.pth' + if dir1!=dir: + os.system(f'cp {dir1} {dir}') + if self._run is not None: + self._run.add_artifact(dir) + + + def schedule_lr(self): + for i,param_group in enumerate(self.optimizer.param_groups): + init_lr = self.param_groups_init[i]['lr'] + new_lrate = init_lr * (self.cfg['decay_rate'] ** (float(self.global_step) / self.N_iters)) + param_group['lr'] = new_lrate + + + def render_images(self,img_i,cur_rays=None): + if cur_rays is None: + frame_ids = self.rays[:, self.ray_frame_id_slice].cuda() + cur_rays = self.rays[frame_ids==img_i].cuda() + gt_depth = cur_rays[:,self.ray_depth_slice] + gt_rgb = cur_rays[:,self.ray_rgb_slice].cpu() + ray_type = cur_rays[:,self.ray_type_slice].data.cpu().numpy() + + ori_chunk = self.cfg['chunk'] + self.cfg['chunk'] = copy.deepcopy(self.cfg['N_rand']) + with torch.no_grad(): + rgb, extras = self.render(rays=cur_rays, lindisp=False,perturb=False,raw_noise_std=0, depth=gt_depth) + self.cfg['chunk'] = ori_chunk + + sdf = extras['raw'][...,-1] + z_vals = extras['z_vals'] + signs = sdf[:, 1:] * sdf[:, :-1] + empty_rays = (signs>0).all(dim=-1) + mask = signs<0 + inds = torch.argmax(mask.float(), axis=1) + inds = inds[..., None] + depth = torch.gather(z_vals,dim=1,index=inds) + depth[empty_rays] = self.cfg['far']*self.cfg['sc_factor'] + depth = depth[..., None].data.cpu().numpy() + + rgb = rgb.data.cpu().numpy() + + rgb_full = np.zeros((self.H,self.W,3),dtype=float) + depth_full = np.zeros((self.H,self.W),dtype=float) + ray_mask_full = np.zeros((self.H,self.W,3),dtype=np.uint8) + X = cur_rays[:,self.ray_dir_slice].data.cpu().numpy() + X[:,[1,2]] = -X[:,[1,2]] + projected = (self.K@X.T).T + uvs = projected/projected[:,2].reshape(-1,1) + uvs = uvs.round().astype(int) + uvs_good = uvs[ray_type==0] + ray_mask_full[uvs_good[:,1],uvs_good[:,0]] = [255,0,0] + uvs_uncertain = uvs[ray_type==1] + ray_mask_full[uvs_uncertain[:,1],uvs_uncertain[:,0]] = [0,255,0] + rgb_full[uvs[:,1],uvs[:,0]] = rgb.reshape(-1,3) + depth_full[uvs[:,1],uvs[:,0]] = depth.reshape(-1) + gt_rgb_full = np.zeros((self.H,self.W,3),dtype=float) + gt_rgb_full[uvs[:,1],uvs[:,0]] = gt_rgb.reshape(-1,3).data.cpu().numpy() + gt_depth_full = np.zeros((self.H,self.W),dtype=float) + gt_depth_full[uvs[:,1],uvs[:,0]] = gt_depth.reshape(-1).data.cpu().numpy() + + return rgb_full, depth_full, ray_mask_full, gt_rgb_full, gt_depth_full, extras + + + def get_gradients(self): + if self.models['pose_array'] is not None: + max_pose_grad = torch.abs(self.models['pose_array'].data.grad).max() + max_embed_grad = 0 + for embed in self.models['embed_fn'].embeddings: + max_embed_grad = max(max_embed_grad,torch.abs(embed.weight.grad).max()) + if self.models['feature_array'] is not None: + max_feature_grad = torch.abs(self.models['feature_array'].data.grad).max() + return max_pose_grad, max_embed_grad, max_feature_grad + + + def get_truncation(self): + '''Annearl truncation over training + ''' + if self.cfg['trunc_decay_type']=='linear': + truncation = self.cfg['trunc_start'] - (self.cfg['trunc_start']-self.cfg['trunc']) * float(self.global_step)/self.cfg['n_step'] + elif self.cfg['trunc_decay_type']=='exp': + lamb = np.log(self.cfg['trunc']/self.cfg['trunc_start']) / (self.cfg['n_step']/4) + truncation = self.cfg['trunc_start']*np.exp(self.global_step*lamb) + truncation = max(truncation,self.cfg['trunc']) + else: + truncation = self.cfg['trunc'] + + truncation *= self.cfg['sc_factor'] + return truncation + + + def train_loop(self,batch): + target_s = batch[:, self.ray_rgb_slice] # Color (N,3) + target_d = batch[:, self.ray_depth_slice] # Normalized scale (N) + + target_mask = batch[:,self.ray_mask_slice].bool().reshape(-1) + frame_ids = batch[:,self.ray_frame_id_slice] + + rgb, extras = self.render(rays=batch, depth=target_d,lindisp=False,perturb=True,raw_noise_std=self.cfg['raw_noise_std'], get_normals=False) + + valid_samples = extras['valid_samples'] #(N_ray,N_samples) + z_vals = extras['z_vals'] # [N_rand, N_samples + N_importance] + sdf = extras['raw'][..., -1] + + N_rays,N_samples = sdf.shape[:2] + valid_rays = (valid_samples>0).any(dim=-1).bool().reshape(N_rays) & (batch[:,self.ray_type_slice]==0) + + ray_type = batch[:,self.ray_type_slice].reshape(-1) + ray_weights = torch.ones((N_rays), device=rgb.device, dtype=torch.float32) + ray_weights[(frame_ids==0).view(-1)] = self.cfg['first_frame_weight'] + ray_weights = ray_weights*valid_rays.view(-1) + sample_weights = ray_weights.view(N_rays,1).expand(-1,N_samples) * valid_samples + img_loss = (((rgb-target_s)**2 * ray_weights.view(-1,1))).mean() + rgb_loss = self.cfg['rgb_weight'] * img_loss + loss = rgb_loss + + rgb0_loss = torch.tensor(0) + if 'rgb0' in extras: + img_loss0 = (((extras['rgb0']-target_s)**2 * ray_weights.view(-1,1))).mean() + rgb0_loss = img_loss0*self.cfg['rgb_weight'] + loss += rgb0_loss + + depth_loss = torch.tensor(0) + depth_loss0 = torch.tensor(0) + if self.cfg['depth_weight']>0: + signs = sdf[:, 1:] * sdf[:, :-1] + mask = signs<0 + inds = torch.argmax(mask.float(), axis=1) + inds = inds[..., None] + z_min = torch.gather(z_vals,dim=1,index=inds) + weights = ray_weights * (depth<=self.cfg['far']*self.cfg['sc_factor']) * (mask.any(dim=-1)) + depth_loss = ((z_min*weights-depth.view(-1,1)*weights)**2).mean() * self.cfg['depth_weight'] + loss = loss+depth_loss + + truncation = self.get_truncation() + sample_weights[ray_type==1] = 0 + fs_loss, sdf_loss,empty_loss, front_mask,sdf_mask = get_sdf_loss(z_vals, target_d.reshape(-1,1).expand(-1,N_samples), sdf, truncation, self.cfg,return_mask=True, sample_weights=sample_weights, rays_d=batch[:,self.ray_dir_slice]) + fs_loss = fs_loss*self.cfg['fs_weight'] + empty_loss = empty_loss*self.cfg['empty_weight'] + sdf_loss = sdf_loss*self.cfg['trunc_weight'] + loss = loss + fs_loss + sdf_loss + empty_loss + + fs_rgb_loss = torch.tensor(0) + if self.cfg['fs_rgb_weight']>0: + fs_rgb_loss = ((((torch.sigmoid(extras['raw'][...,:3])-1)*front_mask[...,None])**2) * sample_weights[...,None]).mean() + loss += fs_rgb_loss*self.cfg['fs_rgb_weight'] + + eikonal_loss = torch.tensor(0) + if self.cfg['eikonal_weight']>0: + nerf_normals = extras['normals'] + eikonal_loss = ((torch.norm(nerf_normals[sdf<1], dim=-1)-1)**2).mean() * self.cfg['eikonal_weight'] + loss += eikonal_loss + + point_cloud_loss = torch.tensor(0) + point_cloud_normal_loss = torch.tensor(0) + + + reg_features = torch.tensor(0) + if self.models['feature_array'] is not None: + reg_features = self.cfg['feature_reg_weight'] * (self.models['feature_array'].data**2).mean() + loss += reg_features + + if self.models['pose_array'] is not None: + pose_array = self.models['pose_array'] + pose_reg = self.cfg['pose_reg_weight']*pose_array.data[1:].norm() + loss += pose_reg + + variation_loss = torch.tensor(0) + + self.optimizer.zero_grad() + self.amp_scaler.scale(loss).backward() + + self.amp_scaler.step(self.optimizer) + self.amp_scaler.update() + if self.global_step%10==0 and self.global_step>0: + self.schedule_lr() + + if self.global_step%self.cfg['i_weights']==0 and self.global_step>0: + self.save_weights(out_file=os.path.join(self.cfg['save_dir'], f'model_latest.pth'), models=self.models) + + if self.global_step % self.cfg['i_img'] == 0 and self.global_step>0: + ids = torch.unique(self.rays[:, self.ray_frame_id_slice]).data.cpu().numpy().astype(int).tolist() + ids.sort() + last = ids[-1] + ids = ids[::max(1,len(ids)//5)] + if last not in ids: + ids.append(last) + canvas = [] + for frame_idx in ids: + rgb, depth, ray_mask, gt_rgb, gt_depth, _ = self.render_images(frame_idx) + mask_vis = (rgb*255*0.2 + ray_mask*0.8).astype(np.uint8) + mask_vis = np.clip(mask_vis,0,255) + rgb = np.concatenate((rgb,gt_rgb),axis=1) + far = self.cfg['far']*self.cfg['sc_factor'] + gt_depth = np.clip(gt_depth, self.cfg['near']*self.cfg['sc_factor'], far) + depth_vis = np.concatenate((to8b(depth / far), to8b(gt_depth / far)), axis=1) + depth_vis = np.tile(depth_vis[...,None],(1,1,3)) + row = np.concatenate((to8b(rgb),depth_vis,mask_vis),axis=1) + canvas.append(row) + canvas = np.concatenate(canvas,axis=0).astype(np.uint8) + dir = f"{self.cfg['save_dir']}/image_step_{self.global_step:07d}.png" + imageio.imwrite(dir,canvas) + if self._run is not None: + self._run.add_artifact(dir) + + + if self.global_step%self.cfg['i_print']==0: + msg = f"Iter: {self.global_step}, valid_samples: {valid_samples.sum()}/{torch.numel(valid_samples)}, valid_rays: {valid_rays.sum()}/{torch.numel(valid_rays)}, " + metrics = { + 'loss':loss.item(), + 'rgb_loss':rgb_loss.item(), + 'rgb0_loss':rgb0_loss.item(), + 'fs_rgb_loss': fs_rgb_loss.item(), + 'depth_loss':depth_loss.item(), + 'depth_loss0':depth_loss0.item(), + 'fs_loss':fs_loss.item(), + 'point_cloud_loss': point_cloud_loss.item(), + 'point_cloud_normal_loss':point_cloud_normal_loss.item(), + 'sdf_loss':sdf_loss.item(), + 'eikonal_loss': eikonal_loss.item(), + "variation_loss": variation_loss.item(), + 'truncation(meter)': self.get_truncation()/self.cfg['sc_factor'], + } + if self.models['pose_array'] is not None: + metrics['pose_reg'] = pose_reg.item() + if 'feature_array' in self.models: + metrics['reg_features'] = reg_features.item() + for k in metrics.keys(): + msg += f"{k}: {metrics[k]:.7f}, " + msg += "\n" + logging.info(msg) + + if self._run is not None: + for k in metrics.keys(): + self._run.log_scalar(k,metrics[k],self.global_step) + + if self.global_step % self.cfg['i_mesh'] == 0 and self.global_step > 0: + with torch.no_grad(): + model = self.models['model_fine'] if self.models['model_fine'] is not None else self.models['model'] + mesh = self.extract_mesh(isolevel=0, voxel_size=self.cfg['mesh_resolution']) + self.mesh = copy.deepcopy(mesh) + if mesh is not None: + dir = os.path.join(self.cfg['save_dir'], f'step_{self.global_step:07d}_mesh_normalized_space.obj') + mesh.export(dir) + if self._run is not None: + self._run.add_artifact(dir) + dir = os.path.join(self.cfg['save_dir'], f'step_{self.global_step:07d}_mesh_real_world.obj') + if self.models['pose_array'] is not None: + _,offset = get_optimized_poses_in_real_world(self.poses,self.models['pose_array'],translation=self.cfg['translation'],sc_factor=self.cfg['sc_factor']) + else: + offset = np.eye(4) + mesh = mesh_to_real_world(mesh,offset,translation=self.cfg['translation'],sc_factor=self.cfg['sc_factor']) + mesh.export(dir) + if self._run is not None: + self._run.add_artifact(dir) + + if self.global_step % self.cfg['i_pose'] == 0 and self.global_step > 0: + if self.models['pose_array'] is not None: + optimized_poses,offset = get_optimized_poses_in_real_world(self.poses,self.models['pose_array'],translation=self.cfg['translation'],sc_factor=self.cfg['sc_factor']) + else: + optimized_poses = self.poses + dir = os.path.join(self.cfg['save_dir'], f'step_{self.global_step:07d}_optimized_poses.txt') + np.savetxt(dir,optimized_poses.reshape(-1,4)) + if self._run is not None: + self._run.add_artifact(dir) + + + def train(self): + set_seed(0) + + for iter in range(self.N_iters): + if iter%(self.N_iters//10)==0: + logging.info(f'train progress {iter}/{self.N_iters}') + batch = next(self.data_loader) + self.train_loop(batch.cuda()) + self.global_step += 1 + + + + @torch.no_grad() + def sample_rays_uniform_occupied_voxels(self,rays_d,depths_in_out,lindisp=False,perturb=False, depths=None, N_samples=None): + '''We first connect the discontinuous boxes for each ray and treat it as uniform sample, then we disconnect into correct boxes + @rays_d: (N_ray,3) + @depths_in_out: Padded tensor each has (N_ray,N_intersect,2) tensor, the time travel of each ray + ''' + N_rays = rays_d.shape[0] + N_intersect = depths_in_out.shape[1] + dirs = rays_d/rays_d.norm(dim=-1,keepdim=True) + + ########### Convert the time to Z + z_in_out = depths_in_out.cuda()*torch.abs(dirs[...,2]).reshape(N_rays,1,1).cuda() + + if depths is not None: + depths = depths.reshape(-1,1) + trunc = self.get_truncation() + valid = (depths>=self.cfg['near']*self.cfg['sc_factor']) & (depths<=self.cfg['far']*self.cfg['sc_factor']).expand(-1,N_intersect) + valid = valid & (z_in_out>0).all(dim=-1) #(N_ray, N_intersect) + z_in_out[valid] = torch.clip(z_in_out[valid], + min=torch.zeros_like(z_in_out[valid]), + max=torch.ones_like(z_in_out[valid])*(depths.reshape(-1,1,1).expand(-1,N_intersect,2)[valid]+trunc)) + + + depths_lens = z_in_out[:,:,1]-z_in_out[:,:,0] #(N_ray,N_intersect) + z_vals_continous = sample_rays_uniform(N_samples,torch.zeros((N_rays,1),device=z_in_out.device).reshape(-1,1),depths_lens.sum(dim=-1).reshape(-1,1),lindisp=lindisp,perturb=perturb) #(N_ray,N_sample) + + ############# Option2 mycuda extension + N_samples = z_vals_continous.shape[1] + z_vals = torch.zeros((N_rays,N_samples), dtype=torch.float, device=rays_d.device) + z_vals = common.sampleRaysUniformOccupiedVoxels(z_in_out.contiguous(),z_vals_continous.contiguous(), z_vals) + z_vals = z_vals.float().to(rays_d.device) #(N_ray,N_sample) + + return z_vals,z_vals_continous + + + def render_rays(self,ray_batch,retraw=True,lindisp=False,perturb=False,raw_noise_std=0.,depth=None, get_normals=False, tf=None): + """Volumetric rendering. + Args: + ray_batch: array of shape [batch_size, ...]. All information necessary + for sampling along a ray, including: ray origin, ray direction, min + dist, max dist, and unit-magnitude viewing direction, frame_ids. + model: function. Model for predicting RGB and density at each point + in space. + N_samples: int. Number of different times to sample along each ray. + retraw: bool. If True, include model's raw, unprocessed predictions. + lindisp: bool. If True, sample linearly in inverse depth rather than in depth. + perturb: float, 0 or 1. If non-zero, each ray is sampled at stratified + random points in time. + N_importance: int. Number of additional times to sample along each ray. + These samples are only passed to model_fine. + model_fine: "fine" network with same spec as model. + raw_noise_std: ... + verbose: bool. If True, print more debugging info. + @depth: depth (from depth image) values of the ray (N_ray,1) + @tf: (N_ray,4,4) glcam in ob, normalized space + Returns: + rgb_map: [num_rays, 3]. Estimated RGB color of a ray. Comes from fine model. + disp_map: [num_rays]. Disparity map. 1 / depth. + acc_map: [num_rays]. Accumulated opacity along each ray. Comes from fine model. + raw: [num_rays, num_samples, 4]. Raw predictions from model. + rgb0: See rgb_map. Output for coarse model. + disp0: See disp_map. Output for coarse model. + acc0: See acc_map. Output for coarse model. + z_std: [num_rays]. Standard deviation of distances along ray for each + sample. + """ + N_rays = ray_batch.shape[0] + rays_d = ray_batch[:,self.ray_dir_slice] + rays_o = torch.zeros_like(rays_d) + viewdirs = rays_d/rays_d.norm(dim=-1,keepdim=True) + + frame_ids = ray_batch[:,self.ray_frame_id_slice].long() + + tf = self.c2w_array[frame_ids] + if self.models['pose_array'] is not None: + tf = self.models['pose_array'].get_matrices(frame_ids)@tf + + rays_o_w = transform_pts(rays_o,tf) + viewdirs_w = (tf[:,:3,:3]@viewdirs[:,None].permute(0,2,1))[:,:3,0] + voxel_size = self.cfg['octree_raytracing_voxel_size']*self.cfg['sc_factor'] + level = int(np.floor(np.log2(2.0/voxel_size))) + near,far,_,depths_in_out = self.octree_m.ray_trace(rays_o_w,viewdirs_w,level=level,debug=0) + z_vals,_ = self.sample_rays_uniform_occupied_voxels(rays_d=viewdirs,depths_in_out=depths_in_out,lindisp=lindisp,perturb=perturb, depths=depth, N_samples=self.cfg['N_samples']) + + if self.cfg['N_samples_around_depth']>0 and depth is not None: #!NOTE only fine when depths are all valid + valid_depth_mask = (depth>=self.cfg['near']*self.cfg['sc_factor']) & (depth<=self.cfg['far']*self.cfg['sc_factor']) + valid_depth_mask = valid_depth_mask.reshape(-1) + trunc = self.get_truncation() + near_depth = depth[valid_depth_mask]-trunc + far_depth = depth[valid_depth_mask]+trunc*self.cfg['neg_trunc_ratio'] + z_vals_around_depth = torch.zeros((N_rays,self.cfg['N_samples_around_depth']), device=ray_batch.device).float() + # if torch.sum(inside_mask)>0: + z_vals_around_depth[valid_depth_mask] = sample_rays_uniform(self.cfg['N_samples_around_depth'],near_depth.reshape(-1,1),far_depth.reshape(-1,1),lindisp=lindisp,perturb=perturb) + invalid_depth_mask = valid_depth_mask==0 + + if invalid_depth_mask.any() and self.cfg['use_octree']: + z_vals_invalid,_ = self.sample_rays_uniform_occupied_voxels(rays_d=viewdirs[invalid_depth_mask],depths_in_out=depths_in_out[invalid_depth_mask],lindisp=lindisp,perturb=perturb, depths=None, N_samples=self.cfg['N_samples_around_depth']) + z_vals_around_depth[invalid_depth_mask] = z_vals_invalid + else: + z_vals_around_depth[invalid_depth_mask] = sample_rays_uniform(self.cfg['N_samples_around_depth'],near[invalid_depth_mask].reshape(-1,1),far[invalid_depth_mask].reshape(-1,1),lindisp=lindisp,perturb=perturb) + + z_vals = torch.cat((z_vals,z_vals_around_depth), dim=-1) + valid_samples = torch.ones(z_vals.shape, dtype=torch.bool, device=ray_batch.device) # During pose update if ray out of box, it becomes invalid + + pts = rays_o[...,None,:] + rays_d[...,None,:] * z_vals[...,:,None] # [N_rays, N_samples, 3] + + deformation = None + raw,normals,valid_samples = self.run_network(pts, viewdirs, frame_ids, tf=tf, valid_samples=valid_samples, get_normals=get_normals) # [N_rays, N_samples, 4] + + rgb_map, weights = self.raw2outputs(raw, z_vals, rays_d, raw_noise_std=raw_noise_std, valid_samples=valid_samples, depth=depth) + + if self.cfg['N_importance'] > 0: + rgb_map_0 = rgb_map + + for iter in range(self.cfg['N_importance_iter']): + z_vals_mid = .5 * (z_vals[...,1:] + z_vals[...,:-1]) + z_samples = sample_pdf(z_vals_mid, weights[...,1:-1], self.cfg['N_importance'], det=(perturb==0.)) + z_samples = z_samples.detach() + valid_samples_importance = torch.ones(z_samples.shape, dtype=torch.bool).to(z_vals.device) + valid_samples_importance[torch.all(valid_samples==0, dim=-1).reshape(-1)] = 0 + + if self.models['model_fine'] is not None and self.models['model_fine']!=self.models['model']: + z_vals, _ = torch.sort(torch.cat([z_vals, z_samples], -1), -1) + pts = rays_o[...,None,:] + rays_d[...,None,:] * z_vals[...,:,None] # [N_rays, N_samples + self.cfg['N_importance'], 3] + raw, normals,valid_samples = self.run_network(pts, viewdirs, frame_ids, tf=tf, valid_samples=valid_samples, get_normals=False) + else: + pts = rays_o[..., None, :] + rays_d[..., None, :] * z_samples[..., :, None] # [N_rays, N_samples + self.cfg['N_importance'], 3] + raw_fine,valid_samples_importance = self.run_network(pts, viewdirs, frame_ids, tf=tf, valid_samples=valid_samples_importance, get_normals=False) + z_vals = torch.cat([z_vals, z_samples], -1) #(N_ray, N_sample) + indices = torch.argsort(z_vals, dim=-1) + z_vals = torch.gather(z_vals,dim=1,index=indices) + raw = torch.gather(torch.cat([raw, raw_fine], dim=1), dim=1, index=indices[...,None].expand(-1,-1,raw.shape[-1])) + valid_samples = torch.cat((valid_samples,valid_samples_importance), dim=-1) + + rgb_map, weights = self.raw2outputs(raw, z_vals, rays_d, raw_noise_std=raw_noise_std,valid_samples=valid_samples) + + ret = {'rgb_map' : rgb_map, 'valid_samples':valid_samples, 'weights':weights, 'z_vals':z_vals} + + if retraw: + ret['raw'] = raw + + if normals is not None: + ret['normals'] = normals + + if deformation is not None: + ret['deformation'] = deformation + + if self.cfg['N_importance'] > 0: + ret['rgb0'] = rgb_map_0 + + return ret + + + def raw2outputs(self, raw, z_vals, rays_d, raw_noise_std=0, valid_samples=None, depth=None): + """Transforms model's predictions to semantically meaningful values. + Args: + raw: [num_rays, num_samples along ray, 4]. Prediction from model. + z_vals: [num_rays, num_samples along ray]. Integration time. + rays_d: [num_rays, 3]. Direction of each ray. + Returns: + rgb_map: [num_rays, 3]. Estimated RGB color of a ray. + disp_map: [num_rays]. Disparity map. Inverse of depth map. + acc_map: [num_rays]. Sum of weights along each ray. + weights: [num_rays, num_samples]. Weights assigned to each sampled color. + depth_map: [num_rays]. Estimated distance to object. + """ + truncation = self.get_truncation() + if depth is not None: + depth = depth.view(-1,1) + + if valid_samples is None: + valid_samples = torch.ones(z_vals.shape, dtype=torch.bool).to(z_vals.device) + + def sdf2weights(sdf): + sdf_from_depth = (depth.view(-1,1)-z_vals)/truncation + weights = torch.sigmoid(sdf_from_depth*self.cfg['sdf_lambda']) * torch.sigmoid(-sdf_from_depth*self.cfg['sdf_lambda']) # This not work well + + invalid = (depth>self.cfg['far']*self.cfg['sc_factor']).reshape(-1) + mask = (z_vals-depth<=truncation*self.cfg['neg_trunc_ratio']) & (z_vals-depth>=-truncation) + weights[~invalid] = weights[~invalid] * mask[~invalid] + weights[invalid] = 0 + + return weights / (weights.sum(dim=-1,keepdim=True) + 1e-10) + + rgb = torch.sigmoid(raw[...,:3]) # [N_rays, N_samples, 3] + weights = sdf2weights(raw[..., 3]) + + weights[valid_samples==0] = 0 + rgb_map = torch.sum(weights[...,None] * rgb, -2) # [N_rays, 3] + + return rgb_map, weights + + + def render(self, rays, depth=None,lindisp=False,perturb=False,raw_noise_std=0.0, get_normals=False): + """Render rays + Args: + H: int. Height of image in pixels. + W: int. Width of image in pixels. + K: float. Focal length of pinhole camera. + chunk: int. Maximum number of rays to process simultaneously. Used to + control maximum memory usage. Does not affect final results. + rays: array of shape [batch_size, 6]. Ray origin and direction for + each example in batch. + ndc: bool. If True, represent ray origin, direction in NDC coordinates. Only true for llff data + near: float or array of shape [batch_size]. Nearest distance for a ray. + far: float or array of shape [batch_size]. Farthest distance for a ray. + @depth: depth values (N_ray,1) + Returns: + rgb_map: [batch_size, 3]. Predicted RGB values for rays. + disp_map: [batch_size]. Disparity map. Inverse of depth. + acc_map: [batch_size]. Accumulated opacity (alpha) along a ray. + extras: dict with everything. + """ + all_ret = self.batchify_rays(rays,depth=depth,lindisp=lindisp,perturb=perturb,raw_noise_std=raw_noise_std, get_normals=get_normals) + + k_extract = ['rgb_map'] + ret_list = [all_ret[k] for k in k_extract] + ret_dict = {k : all_ret[k] for k in all_ret if k not in k_extract} + return ret_list + [ret_dict] + + + + def batchify_rays(self,rays_flat, depth=None,lindisp=False,perturb=False,raw_noise_std=0.0, get_normals=False): + """Render rays in smaller minibatches to avoid OOM. + """ + all_ret = {} + chunk = self.cfg['chunk'] + for i in range(0, rays_flat.shape[0], chunk): + if depth is not None: + cur_depth = depth[i:i+chunk] + else: + cur_depth = None + ret = self.render_rays(rays_flat[i:i+chunk],depth=cur_depth,lindisp=lindisp,perturb=perturb,raw_noise_std=raw_noise_std, get_normals=get_normals) + for k in ret: + if ret[k] is None: + continue + if k not in all_ret: + all_ret[k] = [] + all_ret[k].append(ret[k]) + + all_ret = {k : torch.cat(all_ret[k], 0) for k in all_ret} + return all_ret + + + def run_network(self, inputs, viewdirs, frame_ids=None, tf=None, latent_code=None, valid_samples=None, get_normals=False): + """Prepares inputs and applies network 'fn'. + @inputs: (N_ray,N_sample,3) sampled points on rays in GL camera's frame + @viewdirs: (N_ray,3) unit length vector in camera frame, z-axis backward + @frame_ids: (N_ray) + @tf: (N_ray,4,4) + @latent_code: (N_ray, D) + """ + N_ray,N_sample = inputs.shape[:2] + + if valid_samples is None: + valid_samples = torch.ones((N_ray,N_sample), dtype=torch.bool, device=inputs.device) + + inputs_flat = torch.reshape(inputs, [-1, inputs.shape[-1]]) + + tf_flat = tf[:,None].expand(-1,N_sample,-1,-1).reshape(-1,4,4) + inputs_flat = transform_pts(inputs_flat, tf_flat) + + valid_samples = valid_samples.bool() & (torch.abs(inputs_flat)<=1).all(dim=-1).view(N_ray,N_sample).bool() + + embedded = torch.zeros((inputs_flat.shape[0],self.models['embed_fn'].out_dim), device=inputs_flat.device) + if valid_samples is None: + valid_samples = torch.ones((N_ray,N_sample), dtype=torch.bool, device=inputs_flat.device) + + if get_normals: + if inputs_flat.requires_grad==False: + inputs_flat.requires_grad = True + + with torch.cuda.amp.autocast(enabled=self.cfg['amp']): + if self.cfg['i_embed'] in [3]: + embedded[valid_samples.reshape(-1)], valid_samples_embed = self.models['embed_fn'](inputs_flat[valid_samples.reshape(-1)]) + valid_samples = valid_samples.reshape(-1) + prev_valid_ids = valid_samples.nonzero().reshape(-1) + bad_ids = prev_valid_ids[valid_samples_embed==0] + new_valid_ids = torch.ones((N_ray*N_sample),device=inputs.device).bool() + new_valid_ids[bad_ids] = 0 + valid_samples = valid_samples & new_valid_ids + valid_samples = valid_samples.reshape(N_ray,N_sample).bool() + else: + embedded[valid_samples.reshape(-1)] = self.models['embed_fn'](inputs_flat[valid_samples.reshape(-1)]).to(embedded.dtype) + embedded = embedded.float() + + # Add latent code + if self.models['feature_array'] is not None: + if latent_code is None: + frame_features = self.models['feature_array'](frame_ids) + D = frame_features.shape[-1] + frame_features = frame_features[:,None].expand(-1,N_sample,-1).reshape(-1,D) + else: + D = latent_code.shape[-1] + frame_features = latent_code[:,None].expand(N_ray,N_sample,latent_code.shape[-1]).reshape(-1,D) + embedded = torch.cat([embedded, frame_features], -1) + + # Add view directions + if self.models['embeddirs_fn'] is not None: + input_dirs = (tf[..., :3, :3]@viewdirs[...,None])[...,0] #(N_ray,3) + embedded_dirs = self.models['embeddirs_fn'](input_dirs) + tmp = embedded_dirs.shape[1:] + embedded_dirs_flat = embedded_dirs[:,None].expand(-1,N_sample,*tmp).reshape(-1,*tmp) + embedded = torch.cat([embedded, embedded_dirs_flat], -1) + + outputs_flat = [] + with torch.cuda.amp.autocast(enabled=self.cfg['amp']): + chunk = self.cfg['netchunk'] + for i in range(0,embedded.shape[0],chunk): + out = self.models['model'](embedded[i:i+chunk]) + outputs_flat.append(out) + outputs_flat = torch.cat(outputs_flat, dim=0).float() + outputs = torch.reshape(outputs_flat, list(inputs.shape[:-1]) + [outputs_flat.shape[-1]]).float() + + normals = None + if get_normals: + sdf = outputs[...,-1] + d_output = torch.zeros(sdf.shape, device=sdf.device) + normals = torch.autograd.grad(outputs=sdf,inputs=inputs_flat,grad_outputs=d_output,create_graph=False,retain_graph=True,only_inputs=True,allow_unused=True)[0] + normals = normals.reshape(N_ray,N_sample,3) + + return outputs,normals,valid_samples + + + def run_network_density(self, inputs, get_normals=False): + """Directly query the network w/o pose transformations or deformations (inputs are already in normalized [-1,1]); Particularly used for mesh extraction + @inputs: (N,3) sampled points on rays in GL camera's frame + """ + inputs_flat = torch.reshape(inputs, [-1, inputs.shape[-1]]) + + inputs_flat = torch.clip(inputs_flat,-1,1) + valid_samples = torch.ones((len(inputs_flat)),device=inputs.device).bool() + + if not inputs_flat.requires_grad: + inputs_flat.requires_grad = True + + with torch.cuda.amp.autocast(enabled=self.cfg['amp']): + if self.cfg['i_embed'] in [3]: + embedded, valid_samples_embed = self.models['embed_fn'](inputs_flat) + valid_samples = valid_samples.reshape(-1) + prev_valid_ids = valid_samples.nonzero().reshape(-1) + bad_ids = prev_valid_ids[valid_samples_embed==0] + new_valid_ids = torch.ones((len(inputs_flat)),device=inputs.device).bool() + new_valid_ids[bad_ids] = 0 + valid_samples = valid_samples & new_valid_ids + else: + embedded = self.models['embed_fn'](inputs_flat) + embedded = embedded.float() + input_ch = embedded.shape[-1] + + outputs_flat = [] + with torch.cuda.amp.autocast(enabled=self.cfg['amp']): + chunk = self.cfg['netchunk'] + for i in range(0,embedded.shape[0],chunk): + alpha = self.models['model'].forward_sdf(embedded[i:i+chunk]) #(N,1) + outputs_flat.append(alpha.reshape(-1,1)) + outputs_flat = torch.cat(outputs_flat,dim=0).float() + outputs = torch.reshape(outputs_flat, list(inputs.shape[:-1]) + [outputs_flat.shape[-1]]) + + if get_normals: + d_output = torch.ones_like(outputs, requires_grad=False, device=outputs.device) + normal = torch.autograd.grad(outputs=outputs,inputs=inputs_flat,grad_outputs=d_output,create_graph=False,retain_graph=True,only_inputs=True,allow_unused=True)[0] + outputs = torch.cat((outputs, normal), dim=-1) + + return outputs,valid_samples + + + @torch.no_grad() + def extract_mesh(self, level=None, voxel_size=0.003, isolevel=0.0, return_sigma=False): + voxel_size *= self.cfg['sc_factor'] # in "network space" + + bounds = np.array(self.cfg['bounding_box']).reshape(2,3) + x_min, x_max = bounds[0,0], bounds[1,0] + y_min, y_max = bounds[0,1], bounds[1,1] + z_min, z_max = bounds[0,2], bounds[1,2] + tx = np.arange(x_min+0.5*voxel_size, x_max, voxel_size) + ty = np.arange(y_min+0.5*voxel_size, y_max, voxel_size) + tz = np.arange(z_min+0.5*voxel_size, z_max, voxel_size) + N = len(tx) + query_pts = torch.tensor(np.stack(np.meshgrid(tx, ty, tz, indexing='ij'), -1).astype(np.float32).reshape(-1,3)).float().cuda() + + if self.octree_m is not None: + vox_size = self.cfg['octree_raytracing_voxel_size']*self.cfg['sc_factor'] + level = int(np.floor(np.log2(2.0/vox_size))) + center_ids = self.octree_m.get_center_ids(query_pts, level) + valid = center_ids>=0 + else: + valid = torch.ones(len(query_pts), dtype=bool).cuda() + + logging.info(f'query_pts:{query_pts.shape}, valid:{valid.sum()}') + flat = query_pts[valid] + + sigma = [] + chunk = self.cfg['netchunk'] + for i in range(0,flat.shape[0],chunk): + inputs = flat[i:i+chunk] + with torch.no_grad(): + outputs,valid_samples = self.run_network_density(inputs=inputs) + sigma.append(outputs) + sigma = torch.cat(sigma, dim=0) + sigma_ = torch.ones((N**3)).float().cuda() + sigma_[valid] = sigma.reshape(-1) + sigma = sigma_.reshape(N,N,N).data.cpu().numpy() + + logging.info('Running Marching Cubes') + from skimage import measure + try: + vertices, triangles, normals, values = measure.marching_cubes(sigma, isolevel) + except Exception as e: + logging.info(f"ERROR Marching Cubes {e}") + return None + + logging.info(f'done V:{vertices.shape}, F:{triangles.shape}') + + voxel_size_ndc = np.array([tx[-1] - tx[0], ty[-1] - ty[0], tz[-1] - tz[0]]) / np.array([[tx.shape[0] - 1, ty.shape[0] - 1, tz.shape[0] - 1]]) + offset = np.array([tx[0], ty[0], tz[0]]) + vertices[:, :3] = voxel_size_ndc.reshape(1,3) * vertices[:, :3] + offset.reshape(1,3) + + mesh = trimesh.Trimesh(vertices, triangles, process=False) + + if return_sigma: + return mesh,sigma,query_pts + + return mesh + + + def mesh_texture_from_train_images(self, mesh, rgbs_raw, tex_res=1024): + ''' + @rgbs_raw: raw complete image that was trained on, no black holes + @mesh: in normalized space + ''' + assert len(self.images)==len(rgbs_raw) + + frame_ids = torch.arange(len(self.images)).long().cuda() + tf = self.c2w_array[frame_ids] + if self.models['pose_array'] is not None: + tf = self.models['pose_array'].get_matrices(frame_ids)@tf + tf = tf.data.cpu().numpy() + from offscreen_renderer import ModelRendererOffscreen + + tex_image = torch.zeros((tex_res,tex_res,3)).cuda().float() + weight_tex_image = torch.zeros(tex_image.shape[:-1]).cuda().float() + mesh.merge_vertices() + mesh.remove_duplicate_faces() + mesh = mesh.unwrap() + H,W = tex_image.shape[:2] + uvs_tex = (mesh.visual.uv*np.array([W-1,H-1]).reshape(1,2)) #(n_V,2) + + renderer = ModelRendererOffscreen(cam_K=self.K, H=self.H, W=self.W, zfar=self.cfg['far']*self.cfg['sc_factor']) + + vertices_cuda = torch.from_numpy(mesh.vertices).float().cuda() + faces_cuda = torch.from_numpy(mesh.faces).long().cuda() + face_vertices = torch.zeros((len(faces_cuda),3,3)) + for i in range(3): + face_vertices[:,i] = vertices_cuda[faces_cuda[:,i]] + + all_tri_list= {key: [] for key in range(mesh.triangles.shape[0])} + for i in range(len(rgbs_raw)): + cvcam_in_ob = tf[i]@np.linalg.inv(glcam_in_cvcam) + _, render_depth = renderer.render(mesh=mesh, ob_in_cvcam=np.linalg.inv(cvcam_in_ob)) + xyz_map = depth2xyzmap(render_depth, self.K) + mask = self.masks[i].reshape(self.H,self.W).astype(bool) + valid = (render_depth.reshape(self.H,self.W)>=0.1*self.cfg['sc_factor']) & (mask) + pts = xyz_map[valid].reshape(-1,3) + pts = transform_pts(pts, cvcam_in_ob) + ray_colors = rgbs_raw[i][valid].reshape(-1,3) + locations, distance, index_tri = trimesh.proximity.closest_point(mesh, pts) + normals = mesh.face_normals[index_tri] + for ind_tri, each_tri in enumerate(index_tri): + rays_o = np.zeros(3) + pts = transform_pts(rays_o, cvcam_in_ob) #transform to world space + rays_d = locations[ind_tri]-pts + rays_d /= np.linalg.norm(rays_d) + dot_product = np.dot(-rays_d, normals[ind_tri]) + angle_radians = np.arccos(dot_product) + angle_degrees = np.degrees(angle_radians) + all_tri_list[each_tri].extend([[i,angle_degrees]]) + + _CHOOSE_TOP_N = 4 + all_triangles_dict={} + for k,v in all_tri_list.items(): + if(v): + v.sort(key=lambda x: x[1]) + tep = [i[0] for i in v[:_CHOOSE_TOP_N]] + all_triangles_dict[k]=set(list(tep)) + + + all_tri_visited= {key: 0 for key in range(mesh.triangles.shape[0])} + + logging.info(f"Texture: Texture map computation") + for i in range(len(rgbs_raw)): + print(f'project train_images {i}/{len(rgbs_raw)}') + + cvcam_in_ob = tf[i]@np.linalg.inv(glcam_in_cvcam) + _, render_depth = renderer.render(mesh=mesh, ob_in_cvcam=np.linalg.inv(cvcam_in_ob)) + xyz_map = depth2xyzmap(render_depth, self.K) + mask = self.masks[i].reshape(self.H,self.W).astype(bool) + valid = (render_depth.reshape(self.H,self.W)>=0.1*self.cfg['sc_factor']) & (mask) + pts = xyz_map[valid].reshape(-1,3) + pts = transform_pts(pts, cvcam_in_ob) + ray_colors = rgbs_raw[i][valid].reshape(-1,3) + locations, distance, index_tri = trimesh.proximity.closest_point(mesh, pts) + normals = mesh.face_normals[index_tri] + rays_o = np.zeros((len(normals),3)) + rays_o = transform_pts(rays_o,cvcam_in_ob) + rays_d = locations-rays_o + rays_d /= np.linalg.norm(rays_d,axis=-1).reshape(-1,1) + dots = (normals*(-rays_d)).sum(axis=-1) + ray_weights = np.ones((len(rays_o))) + bool_weights=torch.zeros(len(locations), dtype=torch.bool, device='cuda') + count = 0 + for jj, trtind__ in enumerate(index_tri): + if(i in all_triangles_dict[trtind__] ): + bool_weights[jj]=1 + all_tri_visited[trtind__]=1 + count +=1 + + uvs = torch.zeros((len(locations),2)).cuda().float() + common.rayColorToTextureImageCUDA(torch.from_numpy(mesh.faces).cuda().long(), torch.from_numpy(mesh.vertices).cuda().float(), torch.from_numpy(locations).cuda().float(), torch.from_numpy(index_tri).cuda().long(), torch.from_numpy(uvs_tex).cuda().float(), uvs) + uvs = torch.round(uvs).long() + uvs_flat = uvs[:,1]*(W-1) + uvs[:,0] + uvs_flat_unique, inverse_ids, cnts = torch.unique(uvs_flat, return_counts=True, return_inverse=True) + perm = torch.arange(inverse_ids.size(0)).cuda() + inverse_ids, perm = inverse_ids.flip([0]), perm.flip([0]) + unique_ids = inverse_ids.new_empty(uvs_flat_unique.size(0)).scatter_(0, inverse_ids, perm) + uvs_unique = torch.stack((uvs_flat_unique%(W-1), uvs_flat_unique//(W-1)), dim=-1).reshape(-1,2) + cur_weights= bool_weights[unique_ids].cuda().float() + tex_image[uvs_unique[:,1],uvs_unique[:,0]] += torch.from_numpy(ray_colors).cuda().float()[unique_ids]*cur_weights.reshape(-1,1) + weight_tex_image[uvs_unique[:,1], uvs_unique[:,0]] += cur_weights + + tex_image = tex_image/weight_tex_image[...,None] + tex_image = tex_image.data.cpu().numpy() + tex_image = np.clip(tex_image,0,255).astype(np.uint8) + tex_image = tex_image[::-1].copy() + new_texture = texture_map_interpolation(tex_image) + + mesh.visual = trimesh.visual.texture.TextureVisuals(uv=mesh.visual.uv,image=Image.fromarray(new_texture)) + return mesh diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/bundlesdf/run_nerf.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/bundlesdf/run_nerf.py new file mode 100644 index 0000000000000000000000000000000000000000..8c6a1310d5c7e2e22744b13b33aeccec8c12deb3 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/bundlesdf/run_nerf.py @@ -0,0 +1,115 @@ +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. + + +from nerf_runner import * +code_dir = os.path.dirname(os.path.realpath(__file__)) +sys.path.append(f'{code_dir}/../') +from datareader import * +from bundlesdf.tool import * +import yaml,argparse + + +def run_neural_object_field(cfg, K, rgbs, depths, masks, cam_in_obs, debug=0, save_dir='/path/to/debug/foundationpose_bundlesdf'): + rgbs = np.asarray(rgbs) + depths = np.asarray(depths) + masks = np.asarray(masks) + cam_in_obs = np.asarray(cam_in_obs) + glcam_in_obs = cam_in_obs@glcam_in_cvcam + + cfg['save_dir'] = save_dir + os.makedirs(save_dir, exist_ok=True) + + for i,rgb in enumerate(rgbs): + imageio.imwrite(f'{save_dir}/rgb_{i:07d}.png', rgb) + + sc_factor,translation,pcd_real_scale, pcd_normalized = compute_scene_bounds(None,glcam_in_obs, K, use_mask=True,base_dir=save_dir,rgbs=rgbs,depths=depths,masks=masks, eps=cfg['dbscan_eps'], min_samples=cfg['dbscan_eps_min_samples']) + cfg['sc_factor'] = sc_factor + cfg['translation'] = translation + + o3d.io.write_point_cloud(f'{save_dir}/pcd_normalized.ply', pcd_normalized) + + rgbs_, depths_, masks_, normal_maps,poses = preprocess_data(rgbs, depths, masks,normal_maps=None,poses=glcam_in_obs,sc_factor=cfg['sc_factor'],translation=cfg['translation']) + + nerf = NerfRunner(cfg, rgbs_, depths_, masks_, normal_maps=None, poses=poses, K=K, occ_masks=None, build_octree_pcd=pcd_normalized) + nerf.train() + + mesh = nerf.extract_mesh(isolevel=0,voxel_size=cfg['mesh_resolution']) + mesh = nerf.mesh_texture_from_train_images(mesh, rgbs_raw=rgbs, tex_res=1028) + optimized_cvcam_in_obs,offset = get_optimized_poses_in_real_world(poses,nerf.models['pose_array'],cfg['sc_factor'],cfg['translation']) + mesh = mesh_to_real_world(mesh, pose_offset=offset, translation=nerf.cfg['translation'], sc_factor=nerf.cfg['sc_factor']) + return mesh + + +def run_one_ob(base_dir, cfg, use_refined_mask=False): + save_dir = f'{base_dir}/nerf' + os.system(f'rm -rf {save_dir} && mkdir -p {save_dir}') + with open(f'{base_dir}/select_frames.yml','r') as ff: + info = yaml.safe_load(ff) + rgbs = [] + depths = [] + masks = [] + cam_in_obs = [] + color_files = sorted(glob.glob(f'{base_dir}/rgb/*.png')) + K = np.loadtxt(f'{base_dir}/K.txt') + for i,color_file in enumerate(color_files): + rgb = imageio.imread(color_file) + depth = cv2.imread(color_file.replace('rgb','depth_enhanced'), -1)/1e3 + if use_refined_mask: + mask = cv2.imread(color_file.replace('rgb','mask_refined'), -1) + else: + mask = cv2.imread(color_file.replace('rgb','mask'), -1) + cam_in_ob = np.loadtxt(color_file.replace('rgb','cam_in_ob').replace('.png','.txt')).reshape(4,4) + rgbs.append(rgb) + depths.append(depth) + masks.append(mask) + cam_in_obs.append(cam_in_ob) + + mesh = run_neural_object_field(cfg, K, rgbs, depths, masks, cam_in_obs, save_dir=save_dir, debug=0) + return mesh + + +def run_ycbv(): + ob_ids = np.arange(1,22) + code_dir = os.path.dirname(os.path.realpath(__file__)) + with open(f'{code_dir}/config_ycbv.yml','r') as ff: + cfg = yaml.safe_load(ff) + + for ob_id in ob_ids: + base_dir = f'{args.ref_view_dir}/ob_{ob_id:07d}' + mesh = run_one_ob(base_dir=base_dir, cfg=cfg) + out_file = f'{base_dir}/model/model.obj' + os.makedirs(os.path.dirname(out_file), exist_ok=True) + mesh.export(out_file) + + +def run_linemod(): + ob_ids = np.setdiff1d(np.arange(1,16), np.array([7,3])).tolist() + code_dir = os.path.dirname(os.path.realpath(__file__)) + with open(f'{code_dir}/config_linemod.yml','r') as ff: + cfg = yaml.safe_load(ff) + for ob_id in ob_ids: + base_dir = f'{args.ref_view_dir}/ob_{ob_id:07d}' + mesh = run_one_ob(base_dir=base_dir, cfg=cfg, use_refined_mask=True) + out_file = f'{base_dir}/model/model.obj' + os.makedirs(os.path.dirname(out_file), exist_ok=True) + mesh.export(out_file) + logging.info(f"saved to {out_file}") + + +if __name__=="__main__": + parser = argparse.ArgumentParser() + code_dir = os.path.dirname(os.path.realpath(__file__)) + parser.add_argument('--ref_view_dir', type=str, default=f'/path/to/DATASET/YCB_Video/bowen_addon/ref_views_16') + parser.add_argument('--dataset', type=str, default=f'ycbv', help='one of [ycbv/linemod]') + args = parser.parse_args() + + if args.dataset=='ycbv': + run_ycbv() + else: + run_linemod() diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/bundlesdf/tool.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/bundlesdf/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..d52bb9d57a175edf54ed46647d37921107fb2953 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/bundlesdf/tool.py @@ -0,0 +1,132 @@ +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. + + +import joblib,json,gzip,pickle +from sklearn.cluster import DBSCAN +import shutil,re,imageio,pdb,os,sys +from Utils import * +import pandas as pd + + +def find_biggest_cluster(pts, eps=0.06, min_samples=1): + dbscan = DBSCAN(eps=eps,min_samples=min_samples,n_jobs=-1) + dbscan.fit(pts) + ids, cnts = np.unique(dbscan.labels_, return_counts=True) + best_id = ids[cnts.argsort()[-1]] + keep_mask = dbscan.labels_==best_id + pts_cluster = pts[keep_mask] + return pts_cluster, keep_mask + + +def compute_translation_scales(pts,max_dim=2,cluster=True, eps=0.06, min_samples=1): + if cluster: + pts, keep_mask = find_biggest_cluster(pts, eps, min_samples) + else: + keep_mask = np.ones((len(pts)), dtype=bool) + max_xyz = pts.max(axis=0) + min_xyz = pts.min(axis=0) + center = (max_xyz+min_xyz)/2 + sc_factor = max_dim/(max_xyz-min_xyz).max() #Normalize to [-1,1] + sc_factor *= 0.9 + translation_cvcam = -center + return translation_cvcam, sc_factor, keep_mask + + +def compute_scene_bounds_worker(color_file,K,glcam_in_world,use_mask,rgb=None,depth=None,mask=None): + if rgb is None: + depth_file = color_file.replace('images','depth_filtered') + mask_file = color_file.replace('images','masks') + rgb = np.array(Image.open(color_file))[...,:3] + depth = cv2.imread(depth_file,-1)/1e3 + xyz_map = depth2xyzmap(depth,K) + valid = depth>=0.1 + if use_mask: + if mask is None: + mask = cv2.imread(mask_file,-1) + valid = valid & (mask>0) + pts = xyz_map[valid].reshape(-1,3) + if len(pts)==0: + return None + colors = rgb[valid].reshape(-1,3) + pcd = toOpen3dCloud(pts,colors) + pcd = pcd.voxel_down_sample(0.01) + pcd, ind = pcd.remove_statistical_outlier(nb_neighbors=30,std_ratio=2.0) + cam_in_world = glcam_in_world@glcam_in_cvcam + pcd.transform(cam_in_world) + return np.asarray(pcd.points).copy(), np.asarray(pcd.colors).copy() + + +def compute_scene_bounds(color_files,glcam_in_worlds,K,use_mask=True,base_dir=None,rgbs=None,depths=None,masks=None,cluster=True, translation_cvcam=None, sc_factor=None, eps=0.06, min_samples=1): + assert color_files is None or rgbs is None + + if base_dir is None: + base_dir = os.path.dirname(color_files[0])+'/../' + + args = [] + if rgbs is not None: + for i in range(len(rgbs)): + args.append((None,K,glcam_in_worlds[i],use_mask,rgbs[i],depths[i],masks[i])) + else: + for i in range(len(color_files)): + args.append((color_files[i],K,glcam_in_worlds[i],use_mask)) + + logging.info(f"compute_scene_bounds_worker start") + ret = joblib.Parallel(n_jobs=10, prefer="threads")(joblib.delayed(compute_scene_bounds_worker)(*arg) for arg in args) + logging.info(f"compute_scene_bounds_worker done") + + pcd_all = None + for r in ret: + if r is None: + continue + if pcd_all is None: + pcd_all = toOpen3dCloud(r[0],r[1]) + else: + pcd_all += toOpen3dCloud(r[0],r[1]) + pcd = pcd_all.voxel_down_sample(eps/5) + + logging.info(f"merge pcd") + + o3d.io.write_point_cloud(f'{base_dir}/naive_fusion.ply',pcd) + pts = np.asarray(pcd.points).copy() + + def make_tf(translation_cvcam, sc_factor): + tf = np.eye(4) + tf[:3,3] = translation_cvcam + tf1 = np.eye(4) + tf1[:3,:3] *= sc_factor + tf = tf1@tf + return tf + + if translation_cvcam is None: + translation_cvcam, sc_factor, keep_mask = compute_translation_scales(pts, cluster=cluster, eps=eps, min_samples=min_samples) + tf = make_tf(translation_cvcam, sc_factor) + else: + tf = make_tf(translation_cvcam, sc_factor) + tmp = copy.deepcopy(pcd) + tmp.transform(tf) + tmp_pts = np.asarray(tmp.points) + keep_mask = (np.abs(tmp_pts)<1).all(axis=-1) + + logging.info(f"compute_translation_scales done") + + pcd = toOpen3dCloud(pts[keep_mask],np.asarray(pcd.colors)[keep_mask]) + o3d.io.write_point_cloud(f"{base_dir}/naive_fusion_biggest_cluster.ply",pcd) + pcd_real_scale = copy.deepcopy(pcd) + print(f'translation_cvcam={translation_cvcam}, sc_factor={sc_factor}') + with open(f'{base_dir}/normalization.yml','w') as ff: + tmp = { + 'translation_cvcam':translation_cvcam.tolist(), + 'sc_factor':float(sc_factor), + } + yaml.dump(tmp,ff) + + pcd.transform(tf) + return sc_factor, translation_cvcam, pcd_real_scale, pcd + + diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/datareader.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/datareader.py new file mode 100644 index 0000000000000000000000000000000000000000..e421935d47f567a196af0d15a266a8d3172fc321 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/datareader.py @@ -0,0 +1,627 @@ +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. + + +from Utils import * +import json,os,sys +import OpenEXR + + +BOP_LIST = ['lmo','tless','ycbv','hb','tudl','icbin','itodd'] +BOP_DIR = os.getenv('BOP_DIR') + +def get_bop_reader(video_dir, zfar=np.inf): + if 'ycbv' in video_dir or 'YCB' in video_dir: + return YcbVideoReader(video_dir, zfar=zfar) + if 'lmo' in video_dir or 'LINEMOD-O' in video_dir: + return LinemodOcclusionReader(video_dir, zfar=zfar) + if 'tless' in video_dir or 'TLESS' in video_dir: + return TlessReader(video_dir, zfar=zfar) + if 'hb' in video_dir: + return HomebrewedReader(video_dir, zfar=zfar) + if 'tudl' in video_dir: + return TudlReader(video_dir, zfar=zfar) + if 'icbin' in video_dir: + return IcbinReader(video_dir, zfar=zfar) + if 'itodd' in video_dir: + return ItoddReader(video_dir, zfar=zfar) + else: + raise RuntimeError + + +def get_bop_video_dirs(dataset): + if dataset=='ycbv': + video_dirs = sorted(glob.glob(f'{BOP_DIR}/ycbv/test/*')) + elif dataset=='lmo': + video_dirs = sorted(glob.glob(f'{BOP_DIR}/lmo/lmo_test_bop19/test/*')) + elif dataset=='tless': + video_dirs = sorted(glob.glob(f'{BOP_DIR}/tless/tless_test_primesense_bop19/test_primesense/*')) + elif dataset=='hb': + video_dirs = sorted(glob.glob(f'{BOP_DIR}/hb/hb_test_primesense_bop19/test_primesense/*')) + elif dataset=='tudl': + video_dirs = sorted(glob.glob(f'{BOP_DIR}/tudl/tudl_test_bop19/test/*')) + elif dataset=='icbin': + video_dirs = sorted(glob.glob(f'{BOP_DIR}/icbin/icbin_test_bop19/test/*')) + elif dataset=='itodd': + video_dirs = sorted(glob.glob(f'{BOP_DIR}/itodd/itodd_test_bop19/test/*')) + else: + raise RuntimeError + return video_dirs + + + +class YcbineoatReader: + def __init__(self,video_dir, downscale=1, shorter_side=None, zfar=np.inf): + self.video_dir = video_dir + self.downscale = downscale + # self.zfar = zfar + self.zfar = 100000 + self.color_files = sorted(glob.glob(f"{self.video_dir}/rgb/*.png")) + self.K = np.loadtxt(f'{video_dir}/cam_K.txt').reshape(3,3) + self.id_strs = [] + for color_file in self.color_files: + id_str = os.path.basename(color_file).replace('.png','') + self.id_strs.append(id_str) + self.H,self.W = cv2.imread(self.color_files[0]).shape[:2] + + if shorter_side is not None: + self.downscale = shorter_side/min(self.H, self.W) + + self.H = int(self.H*self.downscale) + self.W = int(self.W*self.downscale) + self.K[:2] *= self.downscale + + self.gt_pose_files = sorted(glob.glob(f'{self.video_dir}/annotated_poses/*')) + + self.videoname_to_object = { + 'bleach0': "021_bleach_cleanser", + 'bleach_hard_00_03_chaitanya': "021_bleach_cleanser", + 'cracker_box_reorient': '003_cracker_box', + 'cracker_box_yalehand0': '003_cracker_box', + 'mustard0': '006_mustard_bottle', + 'mustard_easy_00_02': '006_mustard_bottle', + 'sugar_box1': '004_sugar_box', + 'sugar_box_yalehand0': '004_sugar_box', + 'tomato_soup_can_yalehand0': '005_tomato_soup_can', + } + + + def get_video_name(self): + return self.video_dir.split('/')[-1] + + def __len__(self): + return len(self.color_files) + + def get_gt_pose(self,i): + try: + pose = np.loadtxt(self.gt_pose_files[i]).reshape(4,4) + return pose + except: + logging.info("GT pose not found, return None") + return None + + + def get_color(self,i): + color = imageio.imread(self.color_files[i])[...,:3] + color = cv2.resize(color, (self.W,self.H), interpolation=cv2.INTER_NEAREST) + return color + + def get_mask(self,i): + mask = cv2.imread(self.color_files[i].replace('rgb','masks'),-1) + if len(mask.shape)==3: + for c in range(3): + if mask[...,c].sum()>0: + mask = mask[...,c] + break + mask = cv2.resize(mask, (self.W,self.H), interpolation=cv2.INTER_NEAREST).astype(bool).astype(np.uint8) + return mask + + def get_depth(self,i): + depth_file = self.color_files[i].replace('rgb','depth').replace('png','exr') + if os.path.exists(depth_file): + with OpenEXR.File(depth_file) as infile: + header = infile.header() + print(f"type={header['type']}") + print(f"compression={header['compression']}") + depth = np.array(infile.channels()["V"].pixels,dtype=np.float64) + else: + depth = cv2.imread(self.color_files[i].replace('rgb','depth'),-1)/1e3 + depth = cv2.resize(depth, (self.W,self.H), interpolation=cv2.INTER_NEAREST) + + depth[(depth<0.001) | (depth>=self.zfar)] = 0 + zmin = depth.min() + zmax = depth.max() + depth_vis = depth_to_vis(depth, zmin=zmin, zmax=zmax, inverse=False, mode='rgb') + return depth + + + def get_xyz_map(self,i): + depth = self.get_depth(i) + xyz_map = depth2xyzmap(depth, self.K) + return xyz_map + + def get_occ_mask(self,i): + hand_mask_file = self.color_files[i].replace('rgb','masks_hand') + occ_mask = np.zeros((self.H,self.W), dtype=bool) + if os.path.exists(hand_mask_file): + occ_mask = occ_mask | (cv2.imread(hand_mask_file,-1)>0) + + right_hand_mask_file = self.color_files[i].replace('rgb','masks_hand_right') + if os.path.exists(right_hand_mask_file): + occ_mask = occ_mask | (cv2.imread(right_hand_mask_file,-1)>0) + + occ_mask = cv2.resize(occ_mask, (self.W,self.H), interpolation=cv2.INTER_NEAREST) + + return occ_mask.astype(np.uint8) + + def get_gt_mesh(self): + ob_name = self.videoname_to_object[self.get_video_name()] + YCB_VIDEO_DIR = os.getenv('YCB_VIDEO_DIR') + mesh = trimesh.load(f'{YCB_VIDEO_DIR}/models/{ob_name}/textured_simple.obj') + return mesh + + +class BopBaseReader: + def __init__(self, base_dir, zfar=np.inf, resize=1): + self.base_dir = base_dir + self.resize = resize + self.dataset_name = None + self.color_files = sorted(glob.glob(f"{self.base_dir}/rgb/*")) + if len(self.color_files)==0: + self.color_files = sorted(glob.glob(f"{self.base_dir}/gray/*")) + self.zfar = zfar + + self.K_table = {} + with open(f'{self.base_dir}/scene_camera.json','r') as ff: + info = json.load(ff) + for k in info: + self.K_table[f'{int(k):06d}'] = np.array(info[k]['cam_K']).reshape(3,3) + self.bop_depth_scale = info[k]['depth_scale'] + + if os.path.exists(f'{self.base_dir}/scene_gt.json'): + with open(f'{self.base_dir}/scene_gt.json','r') as ff: + self.scene_gt = json.load(ff) + self.scene_gt = copy.deepcopy(self.scene_gt) # Release file handle to be pickle-able by joblib + assert len(self.scene_gt)==len(self.color_files) + else: + self.scene_gt = None + + self.make_id_strs() + + + def make_scene_ob_ids_dict(self): + with open(f'{BOP_DIR}/{self.dataset_name}/test_targets_bop19.json','r') as ff: + self.scene_ob_ids_dict = {} + data = json.load(ff) + for d in data: + if d['scene_id']==self.get_video_id(): + id_str = f"{d['im_id']:06d}" + if id_str not in self.scene_ob_ids_dict: + self.scene_ob_ids_dict[id_str] = [] + self.scene_ob_ids_dict[id_str] += [d['obj_id']]*d['inst_count'] + + + def get_K(self, i_frame): + K = self.K_table[self.id_strs[i_frame]] + if self.resize!=1: + K[:2,:2] *= self.resize + return K + + + def get_video_dir(self): + video_id = int(self.base_dir.rstrip('/').split('/')[-1]) + return video_id + + def make_id_strs(self): + self.id_strs = [] + for i in range(len(self.color_files)): + name = os.path.basename(self.color_files[i]).split('.')[0] + self.id_strs.append(name) + + + def get_instance_ids_in_image(self, i_frame:int): + ob_ids = [] + if self.scene_gt is not None: + name = int(os.path.basename(self.color_files[i_frame]).split('.')[0]) + for k in self.scene_gt[str(name)]: + ob_ids.append(k['obj_id']) + elif self.scene_ob_ids_dict is not None: + return np.array(self.scene_ob_ids_dict[self.id_strs[i_frame]]) + else: + mask_dir = os.path.dirname(self.color_files[0]).replace('rgb','mask_visib') + id_str = self.id_strs[i_frame] + mask_files = sorted(glob.glob(f'{mask_dir}/{id_str}_*.png')) + ob_ids = [] + for mask_file in mask_files: + ob_id = int(os.path.basename(mask_file).split('.')[0].split('_')[1]) + ob_ids.append(ob_id) + ob_ids = np.asarray(ob_ids) + return ob_ids + + + def get_gt_mesh_file(self, ob_id): + raise RuntimeError("You should override this") + + + def get_color(self,i): + color = imageio.imread(self.color_files[i]) + if len(color.shape)==2: + color = np.tile(color[...,None], (1,1,3)) # Gray to RGB + if self.resize!=1: + color = cv2.resize(color, fx=self.resize, fy=self.resize, dsize=None) + return color + + + def get_depth(self,i, filled=False): + if filled: + depth_file = self.color_files[i].replace('rgb','depth_filled') + depth_file = f'{os.path.dirname(depth_file)}/0{os.path.basename(depth_file)}' + depth = cv2.imread(depth_file,-1)/1e3 + else: + depth_file = self.color_files[i].replace('rgb','depth').replace('gray','depth') + depth = cv2.imread(depth_file,-1)*1e-3*self.bop_depth_scale + if self.resize!=1: + depth = cv2.resize(depth, fx=self.resize, fy=self.resize, dsize=None, interpolation=cv2.INTER_NEAREST) + depth[depth<0.001] = 0 + depth[depth>self.zfar] = 0 + return depth + + def get_xyz_map(self,i): + depth = self.get_depth(i) + xyz_map = depth2xyzmap(depth, self.get_K(i)) + return xyz_map + + + def get_mask(self, i_frame:int, ob_id:int, type='mask_visib'): + ''' + @type: mask_visib (only visible part) / mask (projected mask from whole model) + ''' + pos = 0 + name = int(os.path.basename(self.color_files[i_frame]).split('.')[0]) + if self.scene_gt is not None: + for k in self.scene_gt[str(name)]: + if k['obj_id']==ob_id: + break + pos += 1 + mask_file = f'{self.base_dir}/{type}/{name:06d}_{pos:06d}.png' + if not os.path.exists(mask_file): + logging.info(f'{mask_file} not found') + return None + else: + # mask_dir = os.path.dirname(self.color_files[0]).replace('rgb',type) + # mask_file = f'{mask_dir}/{self.id_strs[i_frame]}_{ob_id:06d}.png' + raise RuntimeError + mask = cv2.imread(mask_file, -1) + if self.resize!=1: + mask = cv2.resize(mask, fx=self.resize, fy=self.resize, dsize=None, interpolation=cv2.INTER_NEAREST) + return mask>0 + + + def get_gt_mesh(self, ob_id:int): + mesh_file = self.get_gt_mesh_file(ob_id) + mesh = trimesh.load(mesh_file) + mesh.vertices *= 1e-3 + return mesh + + + def get_model_diameter(self, ob_id): + dir = os.path.dirname(self.get_gt_mesh_file(self.ob_ids[0])) + info_file = f'{dir}/models_info.json' + with open(info_file,'r') as ff: + info = json.load(ff) + return info[str(ob_id)]['diameter']/1e3 + + + + def get_gt_poses(self, i_frame, ob_id): + gt_poses = [] + name = int(self.id_strs[i_frame]) + for i_k, k in enumerate(self.scene_gt[str(name)]): + if k['obj_id']==ob_id: + cur = np.eye(4) + cur[:3,:3] = np.array(k['cam_R_m2c']).reshape(3,3) + cur[:3,3] = np.array(k['cam_t_m2c'])/1e3 + gt_poses.append(cur) + return np.asarray(gt_poses).reshape(-1,4,4) + + + def get_gt_pose(self, i_frame:int, ob_id, mask=None, use_my_correction=False): + ob_in_cam = np.eye(4) + best_iou = -np.inf + best_gt_mask = None + name = int(self.id_strs[i_frame]) + for i_k, k in enumerate(self.scene_gt[str(name)]): + if k['obj_id']==ob_id: + cur = np.eye(4) + cur[:3,:3] = np.array(k['cam_R_m2c']).reshape(3,3) + cur[:3,3] = np.array(k['cam_t_m2c'])/1e3 + if mask is not None: # When multi-instance exists, use mask to determine which one + gt_mask = cv2.imread(f'{self.base_dir}/mask_visib/{self.id_strs[i_frame]}_{i_k:06d}.png', -1).astype(bool) + intersect = (gt_mask*mask).astype(bool) + union = (gt_mask+mask).astype(bool) + iou = float(intersect.sum())/union.sum() + if iou>best_iou: + best_iou = iou + best_gt_mask = gt_mask + ob_in_cam = cur + else: + ob_in_cam = cur + break + + + if use_my_correction: + if 'ycb' in self.base_dir.lower() and 'train_real' in self.color_files[i_frame]: + video_id = self.get_video_id() + if ob_id==1: + if video_id in [12,13,14,17,24]: + ob_in_cam = ob_in_cam@self.symmetry_tfs[ob_id][1] + return ob_in_cam + + + def load_symmetry_tfs(self): + dir = os.path.dirname(self.get_gt_mesh_file(self.ob_ids[0])) + info_file = f'{dir}/models_info.json' + with open(info_file,'r') as ff: + info = json.load(ff) + self.symmetry_tfs = {} + self.symmetry_info_table = {} + for ob_id in self.ob_ids: + self.symmetry_info_table[ob_id] = info[str(ob_id)] + self.symmetry_tfs[ob_id] = symmetry_tfs_from_info(info[str(ob_id)], rot_angle_discrete=5) + self.geometry_symmetry_info_table = copy.deepcopy(self.symmetry_info_table) + + + def get_video_id(self): + return int(self.base_dir.split('/')[-1]) + + +class LinemodOcclusionReader(BopBaseReader): + def __init__(self,base_dir='/path/to/DATASET/LINEMOD-O/lmo_test_all/test/000002', zfar=np.inf): + super().__init__(base_dir, zfar=zfar) + self.dataset_name = 'lmo' + self.K = list(self.K_table.values())[0] + self.ob_ids = [1,5,6,8,9,10,11,12] + self.ob_id_to_names = { + 1: 'ape', + 2: 'benchvise', + 3: 'bowl', + 4: 'camera', + 5: 'water_pour', + 6: 'cat', + 7: 'cup', + 8: 'driller', + 9: 'duck', + 10: 'eggbox', + 11: 'glue', + 12: 'holepuncher', + 13: 'iron', + 14: 'lamp', + 15: 'phone', + } + self.load_symmetry_tfs() + + def get_gt_mesh_file(self, ob_id): + mesh_dir = f'{BOP_DIR}/{self.dataset_name}/models/obj_{ob_id:06d}.ply' + return mesh_dir + + + +class LinemodReader(LinemodOcclusionReader): + def __init__(self, base_dir='/path/to/DATASET/LINEMOD/lm_test_all/test/000001', zfar=np.inf, split=None): + super().__init__(base_dir, zfar=zfar) + self.dataset_name = 'lm' + if split is not None: # train/test + with open(f'/path/to/DATASET/LINEMOD/Linemod_preprocessed/data/{self.get_video_id():02d}/{split}.txt','r') as ff: + lines = ff.read().splitlines() + self.color_files = [] + for line in lines: + id = int(line) + self.color_files.append(f'{self.base_dir}/rgb/{id:06d}.png') + self.make_id_strs() + + self.ob_ids = np.setdiff1d(np.arange(1,16), np.array([7,3])).tolist() # Exclude bowl and mug + self.load_symmetry_tfs() + + + def get_gt_mesh_file(self, ob_id): + root = self.base_dir + while 1: + if os.path.exists(f'{root}/lm_models'): + mesh_dir = f'{root}/lm_models/models/obj_{ob_id:06d}.ply' + break + else: + root = os.path.abspath(f'{root}/../') + return mesh_dir + + + def get_reconstructed_mesh(self, ob_id, ref_view_dir): + mesh = trimesh.load(os.path.abspath(f'{ref_view_dir}/ob_{ob_id:07d}/model/model.obj')) + return mesh + + +class YcbVideoReader(BopBaseReader): + def __init__(self, base_dir, zfar=np.inf): + super().__init__(base_dir, zfar=zfar) + self.dataset_name = 'ycbv' + self.K = list(self.K_table.values())[0] + + self.make_id_strs() + + self.ob_ids = np.arange(1,22).astype(int).tolist() + YCB_VIDEO_DIR = os.getenv('YCB_VIDEO_DIR') + names = sorted(os.listdir(f'{YCB_VIDEO_DIR}/models/')) + self.ob_id_to_names = {} + self.name_to_ob_id = {} + for i,ob_id in enumerate(self.ob_ids): + self.ob_id_to_names[ob_id] = names[i] + self.name_to_ob_id[names[i]] = ob_id + + if 'BOP' not in self.base_dir: + with open(f'{self.base_dir}/../../keyframe.txt','r') as ff: + self.keyframe_lines = ff.read().splitlines() + + self.load_symmetry_tfs() + for ob_id in self.ob_ids: + if ob_id in [1,4,6,18]: # Cylinder + self.geometry_symmetry_info_table[ob_id] = { + 'symmetries_continuous': [ + {'axis':[0,0,1], 'offset':[0,0,0]}, + ], + 'symmetries_discrete': euler_matrix(0, np.pi, 0).reshape(1,4,4).tolist(), + } + elif ob_id in [13]: + self.geometry_symmetry_info_table[ob_id] = { + 'symmetries_continuous': [ + {'axis':[0,0,1], 'offset':[0,0,0]}, + ], + } + elif ob_id in [2,3,9,21]: # Rectangle box + tfs = [] + for rz in [0, np.pi]: + for rx in [0,np.pi]: + for ry in [0,np.pi]: + tfs.append(euler_matrix(rx, ry, rz)) + self.geometry_symmetry_info_table[ob_id] = { + 'symmetries_discrete': np.asarray(tfs).reshape(-1,4,4).tolist(), + } + else: + pass + + def get_gt_mesh_file(self, ob_id): + if 'BOP' in self.base_dir: + mesh_file = os.path.abspath(f'{self.base_dir}/../../ycbv_models/models/obj_{ob_id:06d}.ply') + else: + mesh_file = f'{self.base_dir}/../../ycbv_models/models/obj_{ob_id:06d}.ply' + return mesh_file + + + def get_gt_mesh(self, ob_id:int, get_posecnn_version=False): + if get_posecnn_version: + YCB_VIDEO_DIR = os.getenv('YCB_VIDEO_DIR') + mesh = trimesh.load(f'{YCB_VIDEO_DIR}/models/{self.ob_id_to_names[ob_id]}/textured_simple.obj') + return mesh + mesh_file = self.get_gt_mesh_file(ob_id) + mesh = trimesh.load(mesh_file, process=False) + mesh.vertices *= 1e-3 + tex_file = mesh_file.replace('.ply','.png') + if os.path.exists(tex_file): + from PIL import Image + im = Image.open(tex_file) + uv = mesh.visual.uv + material = trimesh.visual.texture.SimpleMaterial(image=im) + color_visuals = trimesh.visual.TextureVisuals(uv=uv, image=im, material=material) + mesh.visual = color_visuals + return mesh + + + def get_reconstructed_mesh(self, ob_id, ref_view_dir): + mesh = trimesh.load(os.path.abspath(f'{ref_view_dir}/ob_{ob_id:07d}/model/model.obj')) + return mesh + + + def get_transform_reconstructed_to_gt_model(self, ob_id): + out = np.eye(4) + return out + + + def get_visible_cloud(self, ob_id): + file = os.path.abspath(f'{self.base_dir}/../../models/{self.ob_id_to_names[ob_id]}/visible_cloud.ply') + pcd = o3d.io.read_point_cloud(file) + return pcd + + + def is_keyframe(self, i): + color_file = self.color_files[i] + video_id = self.get_video_id() + frame_id = int(os.path.basename(color_file).split('.')[0]) + key = f'{video_id:04d}/{frame_id:06d}' + return (key in self.keyframe_lines) + + + +class TlessReader(BopBaseReader): + def __init__(self, base_dir, zfar=np.inf): + super().__init__(base_dir, zfar=zfar) + self.dataset_name = 'tless' + + self.ob_ids = np.arange(1,31).astype(int).tolist() + self.load_symmetry_tfs() + + + def get_gt_mesh_file(self, ob_id): + mesh_file = f'{self.base_dir}/../../../models_cad/obj_{ob_id:06d}.ply' + return mesh_file + + + def get_gt_mesh(self, ob_id): + mesh = trimesh.load(self.get_gt_mesh_file(ob_id)) + mesh.vertices *= 1e-3 + mesh = trimesh_add_pure_colored_texture(mesh, color=np.ones((3))*200) + return mesh + + +class HomebrewedReader(BopBaseReader): + def __init__(self, base_dir, zfar=np.inf): + super().__init__(base_dir, zfar=zfar) + self.dataset_name = 'hb' + self.ob_ids = np.arange(1,34).astype(int).tolist() + self.load_symmetry_tfs() + self.make_scene_ob_ids_dict() + + + def get_gt_mesh_file(self, ob_id): + mesh_file = f'{self.base_dir}/../../../hb_models/models/obj_{ob_id:06d}.ply' + return mesh_file + + + def get_gt_pose(self, i_frame:int, ob_id, use_my_correction=False): + logging.info("WARN HomeBrewed doesn't have GT pose") + return np.eye(4) + + + +class ItoddReader(BopBaseReader): + def __init__(self, base_dir, zfar=np.inf): + super().__init__(base_dir, zfar=zfar) + self.dataset_name = 'itodd' + self.make_id_strs() + + self.ob_ids = np.arange(1,29).astype(int).tolist() + self.load_symmetry_tfs() + self.make_scene_ob_ids_dict() + + + def get_gt_mesh_file(self, ob_id): + mesh_file = f'{self.base_dir}/../../../itodd_models/models/obj_{ob_id:06d}.ply' + return mesh_file + + +class IcbinReader(BopBaseReader): + def __init__(self, base_dir, zfar=np.inf): + super().__init__(base_dir, zfar=zfar) + self.dataset_name = 'icbin' + self.ob_ids = np.arange(1,3).astype(int).tolist() + self.load_symmetry_tfs() + + def get_gt_mesh_file(self, ob_id): + mesh_file = f'{self.base_dir}/../../../icbin_models/models/obj_{ob_id:06d}.ply' + return mesh_file + + +class TudlReader(BopBaseReader): + def __init__(self, base_dir, zfar=np.inf): + super().__init__(base_dir, zfar=zfar) + self.dataset_name = 'tudl' + self.ob_ids = np.arange(1,4).astype(int).tolist() + self.load_symmetry_tfs() + + def get_gt_mesh_file(self, ob_id): + mesh_file = f'{self.base_dir}/../../../tudl_models/models/obj_{ob_id:06d}.ply' + return mesh_file + + diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/datasets/blender_rendering/generate_part_rendering.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/datasets/blender_rendering/generate_part_rendering.py new file mode 100644 index 0000000000000000000000000000000000000000..5fd421e9831ee2435fdf4190fa54dff0499ac65e --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/datasets/blender_rendering/generate_part_rendering.py @@ -0,0 +1,419 @@ +""" +blender renderer +""" +import argparse +import bpy +import copy +import math +import mathutils +import numpy as np +import os +import sys +#os.environ['CUDA_VISIBLE_DEVICES'] = '0' +sys.path.append(os.path.dirname(__file__)) +import util +from math import degrees, radians +from sklearn.cluster import KMeans +from ipdb import set_trace +from PIL import Image +import shutil + + +def import_mesh(fpath, scale=1., object_world_matrix=None): + bpy.ops.wm.obj_import(filepath=str(fpath), use_split_objects=False) + obj = bpy.context.selected_objects[0] + util.dump(bpy.context.selected_objects) + if object_world_matrix is not None: + obj.matrix_world = object_world_matrix + + bpy.ops.object.origin_set(type='ORIGIN_GEOMETRY', center='BOUNDS') + obj.location = (0., 0., 0.) # center the bounding box! + + if scale != 1.: + bpy.ops.transform.resize(value=(scale, scale, scale)) + + +def get_archimedean_spiral(sphere_radius, num_steps=250): + ''' + https://en.wikipedia.org/wiki/Spiral, section "Spherical spiral". c = a / pi + ''' + a = 2 + r = sphere_radius + i_list = np.linspace(-a / 2, a/2, num_steps) + translations = [] + # mids = .5 * (i_list[...,1:] + i_list[...,:-1]) + # upper = np.concatenate([mids, i_list[...,-1:]], -1) + # lower = np.concatenate([i_list[...,:1], mids], -1) + #torch.cat([z_vals[...,:1], mids], -1) + # stratified samples in those intervals + # t_rand = np.random.rand(*i_list.shape) + # i_list = lower + (upper - lower) * t_rand + + for i in i_list: + rt = r + theta = math.pi * 1 / 2 + math.pi * 1 / 8 + cos_v = math.cos(-i * math.pi) + sin_v = math.sin(-i * math.pi) + x = rt * math.sin(theta) * cos_v + z = rt * math.sin(-theta + math.pi) * sin_v + y = rt * - math.cos(theta) + + translations.append((x, y, z)) + + return np.array(translations) + +def point_at(obj, target, roll=0): + if not isinstance(target, mathutils.Vector): + target = mathutils.Vector(target) + loc = obj.location + direction = target - loc + quat = direction.to_track_quat('-Z', 'Y') + quat = quat.to_matrix().to_4x4() + rollMatrix = mathutils.Matrix.Rotation(roll, 4, 'Z') + loc = loc.to_tuple() + obj.matrix_world = quat @ rollMatrix + obj.location = loc + +def get_materials_metallic(): + mats = bpy.data.materials + materials_metallic = [] + for m in mats: + materials_metallic.append(m.metallic) + return materials_metallic + +def get_materials_roughness(): + mats = bpy.data.materials + materials_roughness = [] + for m in mats: + materials_roughness.append(m.roughness) + return materials_roughness + +def get_materials_color(): + mats = bpy.data.materials + materials_color = [] + for m in mats: + materials_color.append(m.diffuse_color) + return materials_color + +def get_materials_names(): + mats = bpy.data.materials + materials_names = [] + for m in mats: + materials_names.append(m.name) + return materials_names + +def new_color_material(mat_name, color, roughness, metallic, shadow_mode='NONE'): + mat = bpy.data.materials.get(mat_name) + if mat is None: + mat = bpy.data.materials.new(mat_name) + mat.use_nodes = True + nodes = mat.node_tree.nodes + links = mat.node_tree.links + # principled_node = nodes.get('Principled BSDF') + principled_node = nodes.new(type="ShaderNodeBsdfPrincipled") + output_node = nodes.get("Material Output") + principled_node.inputs.get("Base Color").default_value = color + principled_node.inputs.get("Alpha").default_value = color[3] + principled_node.inputs.get("Roughness").default_value = roughness + principled_node.inputs.get("Metallic").default_value = metallic + # principled_node.inputs.get("Emission Strength").default_value = 0 + link = links.new( principled_node.outputs['BSDF'], output_node.inputs['Surface'] ) + if color[-1] < 1: + mat.blend_method = 'BLEND' + mat.shadow_method = shadow_mode + return mat + +def spherical_to_cartesian(radius, azimuth, elevation): + x = radius * math.cos(azimuth) * math.sin(elevation) + y = radius * math.cos(elevation) + z = radius * math.sin(azimuth) * math.sin(elevation) + x_blender = x * 1.15 + y_blender = -z * 1.15 + z_blender = y * 1.15 + return (x_blender, y_blender, z_blender) + +def set_uniform_lights(): + focus_point = [0,0,0] + light_distance = 5 + light_names = ['Light_front', 'Light_back', 'Light_left', 'Light_right', 'Light_top', 'Light_bottom'] + light_locations = [] + for i in range(3): + light_location = focus_point[:] + light_location[i] -= light_distance + light_locations.append(light_location) + light_location = focus_point[:] + light_location[i] += light_distance + light_locations.append(light_location) + + for i in range(len(light_names)): + light_data = bpy.data.lights.new(name=light_names[i], type='POINT') + light_data.energy = 500 + light_object = bpy.data.objects.new(name=light_names[i], object_data=light_data) + bpy.context.collection.objects.link(light_object) + bpy.context.view_layer.objects.active = light_object + light_object.location = light_locations[i] + +def set_gpu_renderer(): + bpy.context.scene.render.engine = 'CYCLES' + # bpy.context.scene.render.engine = 'BLENDER_EEVEE' + bpy.context.scene.display.render_aa = 'OFF' + bpy.context.preferences.addons['cycles'].preferences.compute_device_type = 'CUDA' + bpy.context.preferences.addons["cycles"].preferences.get_devices() + for d in bpy.context.preferences.addons["cycles"].preferences.devices: + # only use GPU. + if 'GPU' not in d["name"]: + d["use"] = 0 + else: + d["use"] = 1 + d["use"] = 1 + print(d["name"], d["use"]) + bpy.context.scene.render.film_transparent = True + bpy.context.scene.view_settings.view_transform = 'Standard' + num_samples = 64 + bpy.context.scene.cycles.samples = num_samples + +def set_resolution(H=256, W=256): + + num_samples = 2048 + + bpy.context.scene.render.resolution_x = W + bpy.context.scene.render.resolution_y = H + +def import_file(obj_path): + cube = bpy.data.objects['Cube'] + cube.select_set(True) + bpy.ops.object.delete() + lig = bpy.data.objects['Light'] + lig.select_set(True) + bpy.ops.object.delete() + rot_mat = np.eye(3) + hom_coords = np.array([[0., 0., 0., 1.]]).reshape(1, 4) + obj_location = np.zeros((1,3)) + obj_pose = np.concatenate((rot_mat, obj_location.reshape(3,1)), axis=-1) + obj_pose = np.concatenate((obj_pose, hom_coords), axis=0) + import_mesh(obj_path, scale=1, object_world_matrix=obj_pose) + obj = bpy.context.selected_objects[0] + maxDim = max(obj.dimensions) + obj.dimensions = obj.dimensions / maxDim + +def clean_make_output_dirs(output_dir): + img_dir = os.path.join(output_dir, 'rgb') + pose_dir = os.path.join(output_dir, 'pose') + seg_dir = os.path.join(output_dir, 'seg') + uv_dir = os.path.join(output_dir, 'uv') + normal_dir = os.path.join(output_dir, 'normal') + depth_dir = os.path.join(output_dir, 'depth') + seg_print_dir = os.path.join(output_dir, 'seg_colored') + diffusion_dir = os.path.join(output_dir, 'diffusion') + canny_dir = os.path.join(output_dir, 'canny') + + if os.path.exists(img_dir): + shutil.rmtree(img_dir) + os.makedirs(img_dir) + else: + os.makedirs(img_dir) + + + if os.path.exists(seg_print_dir): + shutil.rmtree(seg_print_dir) + os.makedirs(seg_print_dir) + else: + os.makedirs(seg_print_dir) + + if os.path.exists(depth_dir): + shutil.rmtree(depth_dir) + os.makedirs(depth_dir) + else: + os.makedirs(depth_dir) + + if os.path.exists(diffusion_dir): + shutil.rmtree(diffusion_dir) + os.makedirs(diffusion_dir) + else: + os.makedirs(diffusion_dir) + + if os.path.exists(canny_dir): + shutil.rmtree(canny_dir) + os.makedirs(canny_dir) + else: + os.makedirs(canny_dir) + + if os.path.exists(seg_dir): + shutil.rmtree(seg_dir) + os.makedirs(seg_dir) + else: + os.makedirs(seg_dir) + + + util.cond_mkdir(img_dir) + util.cond_mkdir(pose_dir) + util.cond_mkdir(seg_dir) + util.cond_mkdir(uv_dir) + +parser = argparse.ArgumentParser(description='Renders given obj file by rotation a camera around it.') +parser.add_argument('--obj_path', required=True, type=str) +parser.add_argument('--output_dir', required=True, type=str) +parser.add_argument('--radius', type=float, default=1.8, help='Camera azimuth.') +parser.add_argument('--ren_num', type=int, default=10, help='Rendering frames number.') +parser.add_argument('--res_square', action='store_true', help='Padding CAD rendering into square for augmentation.') +argv = sys.argv +argv = sys.argv[sys.argv.index("--") + 1:] +args = parser.parse_args(argv) + +obj_path = args.obj_path +output_dir = args.output_dir +print('args.obj:' + obj_path) +print(output_dir) +render_num = args.ren_num +res_square = args.res_square + +# set GPU render +set_gpu_renderer() + +# set out size. +set_resolution() + +# load obj files. +import_file(obj_path) + +bpy.ops.transform.rotate(value=math.pi/2, orient_axis='X') + +# set output nodes +bpy.context.scene.view_layers['ViewLayer'].use_pass_material_index = True +bpy.context.scene.view_layers['ViewLayer'].use_pass_uv = True +bpy.context.scene.view_layers['ViewLayer'].use_pass_normal = True +bpy.context.scene.view_layers['ViewLayer'].use_pass_z = True +mat_list = get_materials_names() + +# set_trace() +for idx, mat in enumerate(mat_list): + if mat == 'Dots Stroke' or mat == 'Material': + bpy.data.materials[mat].pass_index = 0 + else: + bpy.data.materials[mat].pass_index = int(mat.split('_')[1])+1 + +bpy.context.scene.use_nodes = True +tree = bpy.context.scene.node_tree +links = tree.links +for n in tree.nodes: + tree.nodes.remove(n) +# pass materials and material idx. +render_layers = tree.nodes.new('CompositorNodeRLayers') +alpha_node = tree.nodes.new(type="CompositorNodeAlphaOver") +alpha_node.premul = 1 +output_node_img = tree.nodes.new(type='CompositorNodeOutputFile') +output_node_img.format.color_mode = 'RGBA' +output_node_img.format.file_format = 'PNG' +links.new(render_layers.outputs['Image'], alpha_node.inputs[2]) +links.new(alpha_node.outputs['Image'], output_node_img.inputs[0]) +math_node = tree.nodes.new(type='CompositorNodeMath') +math_node.operation = 'DIVIDE' +math_node.inputs[1].default_value = 255.0 +output_node_seg = tree.nodes.new(type='CompositorNodeOutputFile') +output_node_seg.format.color_mode = 'BW' +links.new(render_layers.outputs['IndexMA'], math_node.inputs[0]) +links.new(math_node.outputs['Value'], output_node_seg.inputs[0]) + +output_node_uv = tree.nodes.new(type='CompositorNodeOutputFile') +output_node_uv.format.color_mode = 'RGB' +output_node_uv.format.file_format = 'OPEN_EXR' +links.new(render_layers.outputs['UV'], output_node_uv.inputs[0]) + +output_node_normal = tree.nodes.new(type='CompositorNodeOutputFile') +output_node_normal.format.color_mode = 'RGB' +output_node_normal.format.file_format = 'OPEN_EXR' + +output_node_depth = tree.nodes.new(type='CompositorNodeOutputFile') +output_node_depth.format.color_mode = 'BW' +output_node_depth.format.file_format = 'OPEN_EXR' +add_nodes = [] +divide_nodes = [] +for i in range(3): + add_node = tree.nodes.new(type='CompositorNodeMath') + # Set the operation to 'ADD', then divide the result by 2 + add_node.operation = 'ADD' + add_node.inputs[1].default_value = 1 # The value to be added + add_nodes.append(add_node) + # To complete the operation (value + 1) / 2, we need another math node for division + divide_node = tree.nodes.new(type='CompositorNodeMath') + divide_node.location = add_node.location.x + 200, math_node.location.y # Positioning next to the add node + divide_node.operation = 'DIVIDE' + divide_node.inputs[1].default_value = 2 # Dividing by 2 + divide_nodes.append(divide_node) +# Create a Separate RGB node +separate_rgb = tree.nodes.new(type='CompositorNodeSepRGBA') +separate_rgb.location = 200, 0 # Adjust the location as needed +links.new(render_layers.outputs['Normal'], separate_rgb.inputs[0]) +combine_rgb = tree.nodes.new(type='CompositorNodeCombRGBA') +for i, channel in enumerate(['R', 'G', 'B']): + links.new(separate_rgb.outputs[channel], add_nodes[i].inputs[0]) + links.new(add_nodes[i].outputs[0], divide_nodes[i].inputs[0]) + links.new(divide_nodes[i].outputs[0], combine_rgb.inputs[channel]) +links.new(combine_rgb.outputs[0], output_node_normal.inputs[0]) +# print(render_layers.outputs.keys()) +links.new(render_layers.outputs['Depth'], output_node_depth.inputs[0]) + +# set uniform lights +set_uniform_lights() + +# set camera. +cam_locations = get_archimedean_spiral(args.radius, render_num) +# fit the camera height in the kitti360 dataset +cam_locations[:, 1] /= 2.5 +cam = bpy.data.objects['Camera'] +obj_location = np.zeros((1,3)) +cv_poses = util.look_at(cam_locations, obj_location) +blender_poses = [util.cv_cam2world_to_bcam2world(m) for m in cv_poses] +K = util.get_calibration_matrix_K_from_blender(cam.data) +fov = cam.data.angle # Y field of view angle + +os.makedirs(output_dir, exist_ok=True) + +with open(os.path.join(output_dir, 'fov.txt'),'w') as fov_files: + fov_files.write('%f\n'%fov) + +# from ipdb import set_trace +# set_trace() + +K = np.asarray(K) +with open(os.path.join(output_dir, 'cam_K.txt'),'w') as f: + f.write("%f %f %f\n" % (K[0, 0], K[0, 1], K[0, 2])) + f.write("%f %f %f\n" % (K[1, 0], K[1, 1], K[1, 2])) + f.write("%f %f %f\n" % (K[2, 0], K[2, 1], K[2, 2])) + +# clear and make output directories +clean_make_output_dirs(output_dir) + +# set node output directories +img_dir = os.path.join(output_dir, 'rgb') +pose_dir = os.path.join(output_dir, 'pose') +seg_dir = os.path.join(output_dir, 'seg') +uv_dir = os.path.join(output_dir, 'uv') +normal_dir = os.path.join(output_dir, 'normal') +depth_dir = os.path.join(output_dir, 'depth') +output_node_img.base_path = img_dir +output_node_seg.base_path = seg_dir +output_node_uv.base_path = uv_dir +output_node_normal.base_path = normal_dir +output_node_depth.base_path = depth_dir + +blender_cam2world_matrices = blender_poses +camera = cam +for i in range(len(blender_cam2world_matrices)): + camera.matrix_world = blender_cam2world_matrices[i] + output_node_img.file_slots[0].path = '{:06d}_'.format(i) + output_node_seg.file_slots[0].path = '{:06d}_'.format(i) + output_node_uv.file_slots[0].path = '{:06d}_'.format(i) + output_node_normal.file_slots[0].path = '{:06d}_'.format(i) + output_node_depth.file_slots[0].path = '{:06d}_'.format(i) + # Render the color image + bpy.ops.render.render(write_still=True) + # Write out camera pose + RT = util.get_world2cam_from_blender_cam(cam) + cam2world = RT.inverted() + with open(os.path.join(pose_dir, '%06d.txt'%i),'w') as pose_file: + matrix_flat = [] + for j in range(4): + for k in range(4): + matrix_flat.append(cam2world[j][k]) + pose_file.write(' '.join(map(str, matrix_flat)) + '\n') diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/datasets/blender_rendering/print_seg.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/datasets/blender_rendering/print_seg.py new file mode 100644 index 0000000000000000000000000000000000000000..bd05f0250484621551adfdc500a900afb944ce46 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/datasets/blender_rendering/print_seg.py @@ -0,0 +1,128 @@ +import os +import numpy as np +import cv2 +import random +import argparse +from ipdb import set_trace +import shutil +import json + +def create_static_color(image, output_path): + color_dict = dict() + for i in range(300): + color_dict[i] = random_color() + + with open(os.path.join(output_path, 'static_color.json'), 'w') as json_file: + json.dump(color_dict, json_file) + + return color_dict + +def random_color(): + return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) + +def color_segmentation(image_path, output_path, color_mapping_path, num_label_dir): + # 读取图像 + image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE) + if image is None: + print(f"Failed to read {image_path}") + return + + # 创建彩色图层 + colored_image = np.ones((image.shape[0], image.shape[1], 3), dtype=np.uint8)*255 + + # 创建颜色映射字典 + color_mapping = {} + + color_dict_json_path = os.path.join(output_path, 'static_color.json') + + if not os.path.exists(color_dict_json_path): + + create_static_color(image, output_path) + + # set_trace() + + with open(color_dict_json_path, 'r') as json_file: + color_dict = json.load(json_file) + + # 为每个唯一的像素值(即分割区域)上色 + for label in np.unique(image): + # set_trace() + if label == 0: # 假设0是背景 + continue + # if label != 1 & label != 9: + # continue + mask = image == label + # choose random color + # color = random_color() + # choose static color + color = color_dict[str(label)] + colored_image[mask] = color + color_mapping[label] = color + + # 保存着色后的图像 + colored_image_path = os.path.join(output_path, os.path.basename(image_path)) + cv2.imwrite(colored_image_path, colored_image) + print(f"Image saved to {colored_image_path}") + + # 保存颜色映射 + # mapping_file = os.path.join(color_mapping_path, os.path.basename(image_path) + ".txt") + # with open(mapping_file, 'w') as file: + # for label, color in color_mapping.items(): + # file.write(f"{label}: {color}\n") + + # print(f"Color mapping saved to {mapping_file}") + + ### xt + # 保存标签可视化图像 + # output_image = colored_image.copy() + # visual_mask = os.path.join(num_label_dir, os.path.basename(image_path)) + # print('number visual img', visual_mask) + # color_step = 255 / len(color_mapping) + # for label, color in color_mapping.items(): + # try: + # mask = cv2.inRange(output_image, color, color) + + # # _, connected_label, stats, _ = cv2.connectedComponentsWithStats(mask, connectivity=8) + # # for conct_label in range(1, len(stats)): + # # x, y, w, h, count = stats[0] + # center_y = mask.nonzero()[0][mask.nonzero()[1].argmin()] + # center_x = mask.nonzero()[1][mask.nonzero()[1].argmin()] + # thickness = 2# if count < 50 else 1 ##数量较少的加粗一下 + # # cv2.rectangle(output_image, (x, y), (x + w, y + h), (255, 255, 255), 2) + # cv2.putText(output_image, str(label), (center_x, center_y), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255) , thickness) + # except: + # continue + # cv2.imwrite(visual_mask, output_image) + # print(f"map of labels and RGB colors saved to {visual_mask}") + ### + + + +parser = argparse.ArgumentParser(description='Material Optimization Script for PhotoScene') +parser.add_argument('--inp_path', required=True) +args = parser.parse_args() +# input_dir = args.inp_path #'/path/to/PhotoScene/outputs/01926_001_final_results0001/seg_merge' +input_dir = args.inp_path#r'/public2/path/to/project/photoscene_new/data/01926_001_final_results0001/seg_merge' +replace_name = args.inp_path.split('/')[-1] +output_dir = input_dir.replace(replace_name, replace_name+'_colored') +color_mapping_dir = input_dir.replace(replace_name, replace_name+'_color_mapping') + +### xt +num_label_dir = input_dir.replace(replace_name, replace_name+'_num_mapping') +os.makedirs(num_label_dir, exist_ok=True) +### + +# 确保输出目录和颜色映射目录存在 + +# if os.path.exists(output_dir): +# shutil.rmtree(output_dir) +# os.makedirs(output_dir) + +os.makedirs(output_dir, exist_ok=True) +os.makedirs(color_mapping_dir, exist_ok=True) + +# 遍历输入目录中的所有文件 +for filename in os.listdir(input_dir): + file_path = os.path.join(input_dir, filename) + if os.path.isfile(file_path): + color_segmentation(file_path, output_dir, color_mapping_dir, num_label_dir) diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/datasets/blender_rendering/util.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/datasets/blender_rendering/util.py new file mode 100644 index 0000000000000000000000000000000000000000..97599a745bb7ad0bc2807f43c01493ca189caa0e --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/datasets/blender_rendering/util.py @@ -0,0 +1,236 @@ +import random +import bpy +from mathutils import Matrix, Vector +import os +import numpy as np +import math +from functools import reduce +from ipdb import set_trace + +def normalize(vec): + return vec / (np.linalg.norm(vec, axis=-1, keepdims=True) + 1e-9) + + +# All the following functions follow the opencv convention for camera coordinates. +def look_at(cam_location, point): + # Cam points in positive z direction + forward = point - cam_location + forward = normalize(forward) + + tmp = np.array([0., -1., 0.]) + + right = np.cross(tmp, forward) + right = normalize(right) + + up = np.cross(forward, right) + up = normalize(up) + + mat = np.stack((right, up, forward, cam_location), axis=-1) + + hom_vec = np.array([[0., 0., 0., 1.]]) + + if len(mat.shape) > 2: + hom_vec = np.tile(hom_vec, [mat.shape[0], 1, 1]) + + mat = np.concatenate((mat, hom_vec), axis=-2) + return mat + + +def sample_spherical(n, radius=1.): + xyz = np.random.normal(size=(n,3)) + xyz = normalize(xyz) * radius + return xyz + + +def set_camera_focal_length_in_world_units(camera_data, focal_length): + scene = bpy.context.scene + resolution_x_in_px = scene.render.resolution_x + resolution_y_in_px = scene.render.resolution_y + scale = scene.render.resolution_percentage / 100 + sensor_width_in_mm = camera_data.sensor_width + sensor_height_in_mm = camera_data.sensor_height + pixel_aspect_ratio = scene.render.pixel_aspect_x / scene.render.pixel_aspect_y + if (camera_data.sensor_fit == 'VERTICAL'): + # the sensor height is fixed (sensor fit is horizontal), + # the sensor width is effectively changed with the pixel aspect ratio + s_u = resolution_x_in_px * scale / sensor_width_in_mm / pixel_aspect_ratio + s_v = resolution_y_in_px * scale / sensor_height_in_mm + else: # 'HORIZONTAL' and 'AUTO' + # the sensor width is fixed (sensor fit is horizontal), + # the sensor height is effectively changed with the pixel aspect ratio + pixel_aspect_ratio = scene.render.pixel_aspect_x / scene.render.pixel_aspect_y + s_u = resolution_x_in_px * scale / sensor_width_in_mm + s_v = resolution_y_in_px * scale * pixel_aspect_ratio / sensor_height_in_mm + + camera_data.lens = focal_length / s_u + + +# Blender: camera looks in negative z-direction, y points up, x points right. +# Opencv: camera looks in positive z-direction, y points down, x points right. +def cv_cam2world_to_bcam2world(cv_cam2world): + ''' + + :cv_cam2world: numpy array. + :return: + ''' + R_bcam2cv = Matrix( + ((1, 0, 0), + (0, -1, 0), + (0, 0, -1))) + + cam_location = Vector(cv_cam2world[:3, -1].tolist()) + cv_cam2world_rot = Matrix(cv_cam2world[:3, :3].tolist()) + + cv_world2cam_rot = cv_cam2world_rot.transposed() + cv_translation = -1. * cv_world2cam_rot @ cam_location + + blender_world2cam_rot = R_bcam2cv @ cv_world2cam_rot + blender_translation = R_bcam2cv @ cv_translation + + blender_cam2world_rot = blender_world2cam_rot.transposed() + blender_cam_location = -1. * blender_cam2world_rot @ blender_translation + + blender_matrix_world = Matrix(( + blender_cam2world_rot[0][:] + (blender_cam_location[0],), + blender_cam2world_rot[1][:] + (blender_cam_location[1],), + blender_cam2world_rot[2][:] + (blender_cam_location[2],), + (0, 0, 0, 1) + )) + + return blender_matrix_world + + +# Returns camera rotation and translation matrices from Blender. +# +# There are 3 coordinate systems involved: +# 1. The World coordinates: "world" +# - right-handed +# 2. The Blender camera coordinates: "bcam" +# - x is horizontal +# - y is up +# - right-handed: negative z look-at direction +# 3. The desired computer vision camera coordinates: "cv" +# - x is horizontal +# - y is down (to align to the actual pixel coordinates +# used in digital images) +# - right-handed: positive z look-at direction +def get_world2cam_from_blender_cam(cam): + + # bcam stands for blender camera + R_bcam2cv = Matrix( + ((1, 0, 0), + (0, -1, 0), + (0, 0, -1))) + + # Transpose since the rotation is object rotation, + # and we want coordinate rotation + # Use matrix_world instead to account for all constraints + location, rotation = cam.matrix_world.decompose()[0:2] # Matrix_world returns the cam2world matrix. + R_world2bcam = rotation.to_matrix().transposed() + + # Convert camera location to translation vector used in coordinate changes + # T_world2bcam = -1*R_world2bcam*cam.location + # Use location from matrix_world to account for constraints: + T_world2bcam = -1 * R_world2bcam @ location + + # Build the coordinate transform matrix from world to computer vision camera + R_world2cv = R_bcam2cv @ R_world2bcam + T_world2cv = R_bcam2cv @ T_world2bcam + + # put into 3x4 matrix + RT = Matrix(( + R_world2cv[0][:] + (T_world2cv[0],), + R_world2cv[1][:] + (T_world2cv[1],), + R_world2cv[2][:] + (T_world2cv[2],), + (0,0,0,1) + )) + return RT + + +#--------------------------------------------------------------- +# 3x4 P matrix from Blender camera +#--------------------------------------------------------------- + +# Build intrinsic camera parameters from Blender camera data +# +# See notes on this in +# blender.stackexchange.com/questions/15102/what-is-blenders-camera-projection-matrix-model +def get_calibration_matrix_K_from_blender(camd): + # set_trace() + f_in_mm = camd.lens + scene = bpy.context.scene + resolution_x_in_px = scene.render.resolution_x + resolution_y_in_px = scene.render.resolution_y + scale = scene.render.resolution_percentage / 100 + sensor_width_in_mm = camd.sensor_width + sensor_height_in_mm = camd.sensor_height + pixel_aspect_ratio = scene.render.pixel_aspect_x / scene.render.pixel_aspect_y + if (camd.sensor_fit == 'VERTICAL'): + # the sensor height is fixed (sensor fit is horizontal), + # the sensor width is effectively changed with the pixel aspect ratio + s_u = resolution_x_in_px * scale / sensor_width_in_mm / pixel_aspect_ratio + s_v = resolution_y_in_px * scale / sensor_height_in_mm + else: # 'HORIZONTAL' and 'AUTO' + # the sensor width is fixed (sensor fit is horizontal), + # the sensor height is effectively changed with the pixel aspect ratio + pixel_aspect_ratio = scene.render.pixel_aspect_x / scene.render.pixel_aspect_y + s_u = resolution_x_in_px * scale / sensor_width_in_mm + s_v = resolution_y_in_px * scale * pixel_aspect_ratio / sensor_height_in_mm + + + # Parameters of intrinsic calibration matrix K + alpha_u = f_in_mm * s_u + alpha_v = f_in_mm * s_v + u_0 = resolution_x_in_px * scale / 2 + v_0 = resolution_y_in_px * scale / 2 + skew = 0 # only use rectangular pixels + + K = Matrix( + ((alpha_u, skew, u_0), + ( 0 , alpha_v, v_0), + ( 0 , 0, 1 ))) + return K + + +def cond_mkdir(path): + path = os.path.normpath(path) + if not os.path.exists(path): + os.makedirs(path) + + return path + + +def dump(obj): + for attr in dir(obj): + if hasattr(obj, attr): + print("obj.%s = %s" % (attr, getattr(obj, attr))) + +def get_archimedean_spiral(sphere_radius, num_steps=250): + ''' + https://en.wikipedia.org/wiki/Spiral, section "Spherical spiral". c = a / pi + ''' + a = 8 + r = sphere_radius + i_list = np.linspace(a / 2, a, num_steps) + translations = [] + mids = .5 * (i_list[...,1:] + i_list[...,:-1]) + upper = np.concatenate([mids, i_list[...,-1:]], -1) + lower = np.concatenate([i_list[...,:1], mids], -1) + #torch.cat([z_vals[...,:1], mids], -1) + # stratified samples in those intervals + t_rand = np.random.rand(*i_list.shape) + i_list = lower + (upper - lower) * t_rand + + for i in i_list: + rt = r * (0.9+ abs(math.sin(-i * math.pi)) * 0.1) + theta = math.pi * 16 / 15 / 2 + math.pi * 1/16 * (i - a/2) / a + cos_v = 0 if abs(math.cos(-i * math.pi)) < 0.1 else math.cos(-i * math.pi) + sin_v = 0 if abs(math.sin(-i * math.pi)) < 0.25 else math.sin(-i * math.pi) + x = rt * math.sin(theta) * cos_v + z = rt * math.sin(-theta + math.pi) * sin_v#* math.sin(-i) + y = rt * - math.cos(theta) + + translations.append((x, y, z)) + # i += a / (2 * num_steps) + + return np.array(translations) diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/datasets/crop_inputs.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/datasets/crop_inputs.py new file mode 100644 index 0000000000000000000000000000000000000000..19c0448cacd8cb46cafd8a94725b5c47477c7d2c --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/datasets/crop_inputs.py @@ -0,0 +1,22 @@ +import os +from PIL import Image +import numpy as np +import rembg +import kiui +from kiui.op import recenter + +path = "/path/to/foundationpose/inputs/gso_30/alarm/rgb/alarm.png" + +bg_remover = rembg.new_session() +input_image = Image.open(path) +input_image = np.array(input_image, dtype=np.uint8)[:, :, :3] + +# bg removal +carved_image = rembg.remove(input_image, session=bg_remover) # [H, W, 4] +mask = carved_image[..., -1] > 0 + +# recenter +image = recenter(carved_image, mask, border_ratio=0) + +# save +Image.fromarray(image).save('./test/alarm_crop.png') diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/datasets/organize_inputs.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/datasets/organize_inputs.py new file mode 100644 index 0000000000000000000000000000000000000000..b6720d480db4d29caafc7204c94c640a047446be --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/datasets/organize_inputs.py @@ -0,0 +1,55 @@ +import os +import shutil +from PIL import Image + +rgb_dir = "/path/to/unidepth/inputs/gso_30" +depth_dir = "/path/to/unidepth/outputs/gso_30/depth" +mesh_dir = "/path/to/wonder3d/evaluation/GT/gso" +cam_K_dir = "/path/to/unidepth/outputs/gso_30/cam_K" + +target_root_dir = "/path/to/foundationpose/inputs/gso_30" +if os.path.exists(target_root_dir): + shutil.rmtree(target_root_dir) +os.makedirs(target_root_dir, exist_ok=True) + +obj_names = os.listdir(rgb_dir) + +for obj_name in obj_names: + rgb_path = os.path.join(rgb_dir, obj_name) + depth_path = os.path.join(depth_dir, obj_name) + mesh_obj_path = os.path.join(mesh_dir, obj_name.split(".")[0], 'meshes', 'model.obj') + mesh_mtl_path = os.path.join(mesh_dir, obj_name.split(".")[0], 'meshes', 'model.mtl') + mesh_texture_path = os.path.join(mesh_dir, obj_name.split(".")[0], 'meshes', 'texture.png') + cam_K_path = os.path.join(cam_K_dir, obj_name.split(".")[0] + '_cam_K.txt') + + rgb_target_path = os.path.join(target_root_dir, obj_name.split(".")[0], 'rgb', obj_name) + depth_target_path = os.path.join(target_root_dir, obj_name.split(".")[0], 'depth', obj_name) + mesh_obj_target_path = os.path.join(target_root_dir, obj_name.split(".")[0], 'mesh', 'model.obj') + mesh_mtl_target_path = os.path.join(target_root_dir, obj_name.split(".")[0], 'mesh', 'model.mtl') + mesh_texture_target_path = os.path.join(target_root_dir, obj_name.split(".")[0], 'mesh', 'texture.png') + cam_K_target_path = os.path.join(target_root_dir, obj_name.split(".")[0], 'cam_K.txt') + + # Load the RGBA image + rgba_image = Image.open(rgb_path) + # Split the RGBA image into individual bands + r, g, b, a = rgba_image.split() + # Convert the alpha channel to a 3-channel PNG mask + mask_image = a.convert('RGB') + # Save the mask image + mask_target_path = os.path.join(target_root_dir, obj_name.split(".")[0], 'masks', obj_name) + os.makedirs(os.path.dirname(mask_target_path), exist_ok=True) + mask_image.save(mask_target_path) + + os.makedirs(os.path.dirname(rgb_target_path), exist_ok=True) + os.makedirs(os.path.dirname(depth_target_path), exist_ok=True) + os.makedirs(os.path.dirname(mesh_obj_target_path), exist_ok=True) + os.makedirs(os.path.dirname(mesh_mtl_target_path), exist_ok=True) + os.makedirs(os.path.dirname(mesh_texture_target_path), exist_ok=True) + os.makedirs(os.path.dirname(cam_K_target_path), exist_ok=True) + + os.system(f"cp {rgb_path} {rgb_target_path}") + os.system(f"cp {depth_path} {depth_target_path}") + os.system(f"cp {mesh_obj_path} {mesh_obj_target_path}") + os.system(f"cp {mesh_mtl_path} {mesh_mtl_target_path}") + os.system(f"cp {mesh_texture_path} {mesh_texture_target_path}") + os.system(f"cp {cam_K_path} {cam_K_target_path}") diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/docker/dockerfile b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/docker/dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..fc235a80f6f8e9e31e38aa1a29877747a400dfdb --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/docker/dockerfile @@ -0,0 +1,60 @@ +FROM nvidia/cudagl:11.3.0-devel-ubuntu20.04 + +ENV TZ=US/Pacific +RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone + +RUN apt-get update --fix-missing && \ + apt-get install -y libgtk2.0-dev && \ + apt-get install -y wget bzip2 ca-certificates curl git vim tmux g++ gcc build-essential cmake checkinstall gfortran libjpeg8-dev libtiff5-dev pkg-config yasm libavcodec-dev libavformat-dev libswscale-dev libdc1394-22-dev libxine2-dev libv4l-dev qt5-default libgtk2.0-dev libtbb-dev libatlas-base-dev libfaac-dev libmp3lame-dev libtheora-dev libvorbis-dev libxvidcore-dev libopencore-amrnb-dev libopencore-amrwb-dev x264 v4l-utils libprotobuf-dev protobuf-compiler libgoogle-glog-dev libgflags-dev libgphoto2-dev libhdf5-dev doxygen libflann-dev libboost-all-dev proj-data libproj-dev libyaml-cpp-dev cmake-curses-gui libzmq3-dev freeglut3-dev + + +RUN cd / && git clone https://github.com/pybind/pybind11 &&\ + cd pybind11 && git checkout v2.10.0 &&\ + mkdir build && cd build && cmake .. -DCMAKE_BUILD_TYPE=Release -DPYBIND11_INSTALL=ON -DPYBIND11_TEST=OFF &&\ + make -j6 && make install + + +RUN cd / && wget https://gitlab.com/libeigen/eigen/-/archive/3.4.0/eigen-3.4.0.tar.gz &&\ + tar xvzf ./eigen-3.4.0.tar.gz &&\ + cd eigen-3.4.0 &&\ + mkdir build &&\ + cd build &&\ + cmake .. &&\ + make install + +SHELL ["/bin/bash", "--login", "-c"] + +RUN cd / && wget --quiet https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /miniconda.sh && \ + /bin/bash /miniconda.sh -b -p /opt/conda &&\ + ln -s /opt/conda/etc/profile.d/conda.sh /etc/profile.d/conda.sh &&\ + echo ". /opt/conda/etc/profile.d/conda.sh" >> ~/.bashrc &&\ + /bin/bash -c "source ~/.bashrc" && \ + /opt/conda/bin/conda update -n base -c defaults conda -y &&\ + /opt/conda/bin/conda create -n my python=3.8 + + +ENV PATH $PATH:/opt/conda/envs/my/bin + +RUN conda init bash &&\ + echo "conda activate my" >> ~/.bashrc &&\ + conda activate my &&\ + pip install torch==2.0.0+cu118 torchvision==0.15.1+cu118 torchaudio==2.0.1 --index-url https://download.pytorch.org/whl/cu118 &&\ + pip install "git+https://github.com/facebookresearch/pytorch3d.git@stable" &&\ + pip install scipy joblib scikit-learn ruamel.yaml trimesh pyyaml opencv-python imageio open3d transformations warp-lang einops kornia pyrender + +RUN cd / && git clone --recursive https://github.com/NVIDIAGameWorks/kaolin +RUN conda activate my && cd /kaolin &&\ + FORCE_CUDA=1 python setup.py develop + +RUN cd / && git clone https://github.com/NVlabs/nvdiffrast &&\ + conda activate my && cd /nvdiffrast && pip install . + +ENV OPENCV_IO_ENABLE_OPENEXR=1 + +RUN conda activate my &&\ + pip install scikit-image meshcat webdataset omegaconf pypng roma seaborn opencv-contrib-python openpyxl wandb imgaug Ninja xlsxwriter timm albumentations xatlas rtree nodejs jupyterlab objaverse g4f ultralytics==8.0.120 pycocotools videoio numba &&\ + conda install -y -c anaconda h5py + + +ENV SHELL=/bin/bash +RUN ln -sf /bin/bash /bin/sh diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/docker/run_container.sh b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/docker/run_container.sh new file mode 100644 index 0000000000000000000000000000000000000000..85035714e53650c4c09cf67c01d94d08e62d78e3 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/docker/run_container.sh @@ -0,0 +1,3 @@ +docker rm -f foundationpose +DIR=$(pwd)/../ +xhost + && docker run --gpus all --env NVIDIA_DISABLE_REQUIRE=1 -it --network=host --name foundationpose --cap-add=SYS_PTRACE --security-opt seccomp=unconfined -v $DIR:$DIR -v /home:/home -v /mnt:/mnt -v /tmp/.X11-unix:/tmp/.X11-unix -v /tmp:/tmp --ipc=host -e DISPLAY=${DISPLAY} -e GIT_INDEX_FILE foundationpose:latest bash -c "cd $DIR && bash" diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/estimater.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/estimater.py new file mode 100644 index 0000000000000000000000000000000000000000..bfbf4946619bf71c7990d12029ea44efd4a594cd --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/estimater.py @@ -0,0 +1,278 @@ +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. + + +from Utils import * +from datareader import * +import itertools +from learning.training.predict_score import * +from learning.training.predict_pose_refine import * +import yaml + + +class FoundationPose: + def __init__(self, model_pts, model_normals, symmetry_tfs=None, mesh=None, scorer:ScorePredictor=None, refiner:PoseRefinePredictor=None, glctx=None, debug=0, debug_dir='/path/to/debug/novel_pose_debug/', bg_color='white', object_level=False, rgb_only=False, crop_ratio=1.0): + self.gt_pose = None + self.ignore_normal_flip = True + self.debug = debug + self.debug_dir = debug_dir + self.bg_color = bg_color + self.object_level = object_level + self.rgb_only = rgb_only + self.crop_ratio = crop_ratio + os.makedirs(debug_dir, exist_ok=True) + + self.reset_object(model_pts, model_normals, symmetry_tfs=symmetry_tfs, mesh=mesh) + self.make_rotation_grid(min_n_views=40, inplane_step=60) + + self.glctx = glctx + + if scorer is not None: + self.scorer = scorer + else: + self.scorer = ScorePredictor() + + if refiner is not None: + self.refiner = refiner + else: + self.refiner = PoseRefinePredictor() + + self.pose_last = None # Used for tracking; per the centered mesh + + + def reset_object(self, model_pts, model_normals, symmetry_tfs=None, mesh=None): + max_xyz = mesh.vertices.max(axis=0) + min_xyz = mesh.vertices.min(axis=0) + self.model_center = (min_xyz+max_xyz)/2 + if mesh is not None: + self.mesh_ori = mesh.copy() + mesh = mesh.copy() + mesh.vertices = mesh.vertices - self.model_center.reshape(1,3) + + model_pts = mesh.vertices + self.diameter = compute_mesh_diameter(model_pts=mesh.vertices, n_sample=10000) + self.vox_size = max(self.diameter/20.0, 0.003) + logging.info(f'self.diameter:{self.diameter}, vox_size:{self.vox_size}') + self.dist_bin = self.vox_size/2 + self.angle_bin = 20 # Deg + pcd = toOpen3dCloud(model_pts, normals=model_normals) + pcd = pcd.voxel_down_sample(self.vox_size) + self.max_xyz = np.asarray(pcd.points).max(axis=0) + self.min_xyz = np.asarray(pcd.points).min(axis=0) + self.pts = torch.tensor(np.asarray(pcd.points), dtype=torch.float32, device='cuda') + self.normals = F.normalize(torch.tensor(np.asarray(pcd.normals), dtype=torch.float32, device='cuda'), dim=-1) + logging.info(f'self.pts:{self.pts.shape}') + self.mesh_path = None + self.mesh = mesh + if self.mesh is not None: + self.mesh_path = f'/tmp/{uuid.uuid4()}.obj' + self.mesh.export(self.mesh_path) + self.mesh_tensors = make_mesh_tensors(self.mesh) + + if symmetry_tfs is None: + self.symmetry_tfs = torch.eye(4).float().cuda()[None] + else: + self.symmetry_tfs = torch.as_tensor(symmetry_tfs, device='cuda', dtype=torch.float) + + logging.info("reset done") + + + + def get_tf_to_centered_mesh(self): + tf_to_center = torch.eye(4, dtype=torch.float, device='cuda') + tf_to_center[:3,3] = -torch.as_tensor(self.model_center, device='cuda', dtype=torch.float) + return tf_to_center + + + def to_device(self, s='cuda:0'): + for k in self.__dict__: + self.__dict__[k] = self.__dict__[k] + if torch.is_tensor(self.__dict__[k]) or isinstance(self.__dict__[k], nn.Module): + logging.info(f"Moving {k} to device {s}") + self.__dict__[k] = self.__dict__[k].to(s) + for k in self.mesh_tensors: + logging.info(f"Moving {k} to device {s}") + self.mesh_tensors[k] = self.mesh_tensors[k].to(s) + if self.refiner is not None: + self.refiner.model.to(s) + if self.scorer is not None: + self.scorer.model.to(s) + if self.glctx is not None: + self.glctx = dr.RasterizeCudaContext(s) + + + + def make_rotation_grid(self, min_n_views=40, inplane_step=60): + cam_in_obs = sample_views_icosphere(n_views=min_n_views) + logging.info(f'cam_in_obs:{cam_in_obs.shape}') + rot_grid = [] + for i in range(len(cam_in_obs)): + for inplane_rot in np.deg2rad(np.arange(0, 360, inplane_step)): + cam_in_ob = cam_in_obs[i] + R_inplane = euler_matrix(0,0,inplane_rot) + cam_in_ob = cam_in_ob@R_inplane + ob_in_cam = np.linalg.inv(cam_in_ob) + rot_grid.append(ob_in_cam) + + rot_grid = np.asarray(rot_grid) + logging.info(f"rot_grid:{rot_grid.shape}") + rot_grid = mycpp.cluster_poses(30, 99999, rot_grid, self.symmetry_tfs.data.cpu().numpy()) + rot_grid = np.asarray(rot_grid) + logging.info(f"after cluster, rot_grid:{rot_grid.shape}") + self.rot_grid = torch.as_tensor(rot_grid, device='cuda', dtype=torch.float) + logging.info(f"self.rot_grid: {self.rot_grid.shape}") + + + def generate_random_pose_hypo(self, K, rgb, depth, mask, scene_pts=None): + ''' + @scene_pts: torch tensor (N,3) + ''' + ob_in_cams = self.rot_grid.clone() + center = self.guess_translation(depth=depth, mask=mask, K=K) + ob_in_cams[:,:3,3] = torch.tensor(center, device='cuda', dtype=torch.float).reshape(1,3) + return ob_in_cams + + + def guess_translation(self, depth, mask, K): + vs,us = np.where(mask>0) + if len(us)==0: + logging.info(f'mask is all zero') + return np.zeros((3)) + uc = (us.min()+us.max())/2.0 + vc = (vs.min()+vs.max())/2.0 + valid = mask.astype(bool) & (depth>=0.001) + if not valid.any(): + logging.info(f"valid is empty") + return np.zeros((3)) + + zc = np.median(depth[valid]) + center = (np.linalg.inv(K)@np.asarray([uc,vc,1]).reshape(3,1))*zc + + if self.debug>=2: + pcd = toOpen3dCloud(center.reshape(1,3)) + o3d.io.write_point_cloud(f'{self.debug_dir}/init_center.ply', pcd) + + return center.reshape(3) + + + def register(self, K, rgb, depth, ob_mask, ob_id=None, glctx=None, iteration=5): + '''Copmute pose from given pts to self.pcd + @pts: (N,3) np array, downsampled scene points + ''' + set_seed(0) + logging.info('Welcome') + + if self.glctx is None: + if glctx is None: + self.glctx = dr.RasterizeCudaContext() + # self.glctx = dr.RasterizeGLContext() + else: + self.glctx = glctx + + depth = erode_depth(depth, radius=2, device='cuda') + depth = bilateral_filter_depth(depth, radius=2, device='cuda') + + if self.debug>=2: + xyz_map = depth2xyzmap(depth, K) + valid = xyz_map[...,2]>=0.001 + pcd = toOpen3dCloud(xyz_map[valid], rgb[valid]) + o3d.io.write_point_cloud(f'{self.debug_dir}/scene_raw.ply',pcd) + cv2.imwrite(f'{self.debug_dir}/ob_mask.png', (ob_mask*255.0).clip(0,255)) + + normal_map = None + valid = (depth>=0.001) & (ob_mask>0) + if valid.sum()<4: + logging.info(f'valid too small, return') + pose = np.eye(4) + pose[:3,3] = self.guess_translation(depth=depth, mask=ob_mask, K=K) + return pose + + if self.debug>=2: + imageio.imwrite(f'{self.debug_dir}/color.png', rgb) + cv2.imwrite(f'{self.debug_dir}/depth.png', (depth*1000).astype(np.uint16)) + valid = xyz_map[...,2]>=0.001 + pcd = toOpen3dCloud(xyz_map[valid], rgb[valid]) + o3d.io.write_point_cloud(f'{self.debug_dir}/scene_complete.ply',pcd) + + self.H, self.W = depth.shape[:2] + self.K = K + self.ob_id = ob_id + self.ob_mask = ob_mask + + poses = self.generate_random_pose_hypo(K=K, rgb=rgb, depth=depth, mask=ob_mask, scene_pts=None) + poses = poses.data.cpu().numpy() + logging.info(f'poses:{poses.shape}') + center = self.guess_translation(depth=depth, mask=ob_mask, K=K) + + poses = torch.as_tensor(poses, device='cuda', dtype=torch.float) + poses[:,:3,3] = torch.as_tensor(center.reshape(1,3), device='cuda') + + add_errs = self.compute_add_err_to_gt_pose(poses) + logging.info(f"after viewpoint, add_errs min:{add_errs.min()}") + + xyz_map = depth2xyzmap(depth, K) + + refiner_debug_dir = f'{self.debug_dir}/refiner' + os.makedirs(refiner_debug_dir, exist_ok=True) + poses, vis = self.refiner.predict(refiner_debug_dir=refiner_debug_dir, mesh=self.mesh, mesh_tensors=self.mesh_tensors, rgb=rgb, depth=depth, K=K, ob_in_cams=poses.data.cpu().numpy(), normal_map=normal_map, xyz_map=xyz_map, glctx=self.glctx, mesh_diameter=self.diameter, iteration=iteration, get_vis=self.debug>=2, bg_color=self.bg_color, object_level=self.object_level, rgb_only=self.rgb_only, crop_ratio=self.crop_ratio) + + if vis is not None: + imageio.imwrite(f'{self.debug_dir}/vis_refiner.png', vis) + + scores, vis = self.scorer.predict(mesh=self.mesh, rgb=rgb, depth=depth, K=K, ob_in_cams=poses.data.cpu().numpy(), normal_map=normal_map, mesh_tensors=self.mesh_tensors, glctx=self.glctx, mesh_diameter=self.diameter, get_vis=self.debug>=2, object_level=self.object_level, rgb_only=self.rgb_only, crop_ratio=self.crop_ratio) + if vis is not None: + imageio.imwrite(f'{self.debug_dir}/vis_score.png', vis) + + add_errs = self.compute_add_err_to_gt_pose(poses) + logging.info(f"final, add_errs min:{add_errs.min()}") + + ids = torch.as_tensor(scores).argsort(descending=True) + logging.info(f'sort ids:{ids}') + scores = scores[ids] + poses = poses[ids] + + logging.info(f'sorted scores:{scores}') + + best_pose = poses[0]@self.get_tf_to_centered_mesh() + self.pose_last = poses[0] + self.best_id = ids[0] + + self.poses = poses + self.scores = scores + + return best_pose.data.cpu().numpy() + + + def compute_add_err_to_gt_pose(self, poses): + ''' + @poses: wrt. the centered mesh + ''' + return -torch.ones(len(poses), device='cuda', dtype=torch.float) + + + def track_one(self, rgb, depth, K, iteration, extra={}): + if self.pose_last is None: + logging.info("Please init pose by register first") + raise RuntimeError + logging.info("Welcome") + + depth = torch.as_tensor(depth, device='cuda', dtype=torch.float) + depth = erode_depth(depth, radius=2, device='cuda') + depth = bilateral_filter_depth(depth, radius=2, device='cuda') + logging.info("depth processing done") + + xyz_map = depth2xyzmap_batch(depth[None], torch.as_tensor(K, dtype=torch.float, device='cuda')[None], zfar=np.inf)[0] + + pose, vis = self.refiner.predict(mesh=self.mesh, mesh_tensors=self.mesh_tensors, rgb=rgb, depth=depth, K=K, ob_in_cams=self.pose_last.reshape(1,4,4).data.cpu().numpy(), normal_map=None, xyz_map=xyz_map, mesh_diameter=self.diameter, glctx=self.glctx, iteration=iteration, get_vis=self.debug>=2) + logging.info("pose done") + if self.debug>=2: + extra['vis'] = vis + self.pose_last = pose + return (pose@self.get_tf_to_centered_mesh()).data.cpu().numpy().reshape(4,4) + + diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/learning/datasets/h5_dataset.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/learning/datasets/h5_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..3bb51a5919e199bcc205564f1d075c535e1d5566 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/learning/datasets/h5_dataset.py @@ -0,0 +1,220 @@ +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. + + + +import os,sys,h5py,bisect,io,json +code_dir = os.path.dirname(os.path.realpath(__file__)) +sys.path.append(f'{code_dir}/../../../../') +from Utils import * +from learning.datasets.pose_dataset import * + + + + +class PairH5Dataset(torch.utils.data.Dataset): + def __init__(self, cfg, h5_file, mode='train', max_num_key=None, cache_data=None): + self.cfg = cfg + self.h5_file = h5_file + self.mode = mode + + logging.info(f"self.h5_file:{self.h5_file}") + self.n_perturb = None + self.H_ori = None + self.W_ori = None + self.cache_data = cache_data + + if self.mode=='test': + pass + else: + self.object_keys = [] + key_file = h5_file.replace('.h5','_keys.pkl') + if os.path.exists(key_file): + with open(key_file, 'rb') as ff: + self.object_keys = pickle.load(ff) + logging.info(f'object_keys loaded#:{len(self.object_keys)} from {key_file}') + if max_num_key is not None: + self.object_keys = self.object_keys[:max_num_key] + else: + with h5py.File(h5_file, 'r', libver='latest') as hf: + for k in hf: + self.object_keys.append(k) + if max_num_key is not None and len(self.object_keys)>=max_num_key: + logging.info("break due to max_num_key") + break + + logging.info(f'self.object_keys#:{len(self.object_keys)}, max_num_key:{max_num_key}') + + with h5py.File(h5_file, 'r', libver='latest') as hf: + group = hf[self.object_keys[0]] + cnt = 0 + for k_perturb in group: + if 'i_perturb' in k_perturb: + cnt += 1 + if 'crop_ratio' in group[k_perturb]: + self.cfg['crop_ratio'] = float(group[k_perturb]['crop_ratio'][()]) + if self.H_ori is None: + if 'H_ori' in group[k_perturb]: + self.H_ori = int(group[k_perturb]['H_ori'][()]) + self.W_ori = int(group[k_perturb]['W_ori'][()]) + else: + self.H_ori = 540 + self.W_ori = 720 + self.n_perturb = cnt + logging.info(f'self.n_perturb:{self.n_perturb}') + + + def __len__(self): + if self.mode=='test': + return 1 + return len(self.object_keys) + + + + def transform_depth_to_xyzmap(self, batch:BatchPoseData, H_ori, W_ori, bound=1): + bs = len(batch.rgbAs) + H,W = batch.rgbAs.shape[-2:] + mesh_radius = batch.mesh_diameters.cuda()/2 + tf_to_crops = batch.tf_to_crops.cuda() + crop_to_oris = batch.tf_to_crops.inverse().cuda() #(B,3,3) + batch.poseA = batch.poseA.cuda() + batch.Ks = batch.Ks.cuda() + + if batch.xyz_mapAs is None: + depthAs_ori = kornia.geometry.transform.warp_perspective(batch.depthAs.cuda().expand(bs,-1,-1,-1), crop_to_oris, dsize=(H_ori, W_ori), mode='nearest', align_corners=False) + batch.xyz_mapAs = depth2xyzmap_batch(depthAs_ori[:,0], batch.Ks, zfar=np.inf).permute(0,3,1,2) #(B,3,H,W) + batch.xyz_mapAs = kornia.geometry.transform.warp_perspective(batch.xyz_mapAs, tf_to_crops, dsize=(H,W), mode='nearest', align_corners=False) + batch.xyz_mapAs = batch.xyz_mapAs.cuda() + if self.cfg['normalize_xyz']: + invalid = batch.xyz_mapAs[:,2:3]<0.001 + batch.xyz_mapAs = batch.xyz_mapAs-batch.poseA[:,:3,3].reshape(bs,3,1,1) + if self.cfg['normalize_xyz']: + batch.xyz_mapAs *= 1/mesh_radius.reshape(bs,1,1,1) + invalid = invalid.expand(bs,3,-1,-1) | (torch.abs(batch.xyz_mapAs)>=2) + batch.xyz_mapAs[invalid.expand(bs,3,-1,-1)] = 0 + + if batch.xyz_mapBs is None: + depthBs_ori = kornia.geometry.transform.warp_perspective(batch.depthBs.cuda().expand(bs,-1,-1,-1), crop_to_oris, dsize=(H_ori, W_ori), mode='nearest', align_corners=False) + batch.xyz_mapBs = depth2xyzmap_batch(depthBs_ori[:,0], batch.Ks, zfar=np.inf).permute(0,3,1,2) #(B,3,H,W) + batch.xyz_mapBs = kornia.geometry.transform.warp_perspective(batch.xyz_mapBs, tf_to_crops, dsize=(H,W), mode='nearest', align_corners=False) + batch.xyz_mapBs = batch.xyz_mapBs.cuda() + if self.cfg['normalize_xyz']: + invalid = batch.xyz_mapBs[:,2:3]<0.001 + batch.xyz_mapBs = batch.xyz_mapBs-batch.poseA[:,:3,3].reshape(bs,3,1,1) + if self.cfg['normalize_xyz']: + batch.xyz_mapBs *= 1/mesh_radius.reshape(bs,1,1,1) + invalid = invalid.expand(bs,3,-1,-1) | (torch.abs(batch.xyz_mapBs)>=2) + batch.xyz_mapBs[invalid.expand(bs,3,-1,-1)] = 0 + + return batch + + + + def transform_batch(self, batch:BatchPoseData, H_ori, W_ori, bound=1): + '''Transform the batch before feeding to the network + !NOTE the H_ori, W_ori could be different at test time from the training data, and needs to be set + ''' + bs = len(batch.rgbAs) + batch.rgbAs = batch.rgbAs.cuda().float()/255.0 + batch.rgbBs = batch.rgbBs.cuda().float()/255.0 + + batch = self.transform_depth_to_xyzmap(batch, H_ori, W_ori, bound=bound) + return batch + + + + +class TripletH5Dataset(PairH5Dataset): + def __init__(self, cfg, h5_file, mode, max_num_key=None, cache_data=None): + super().__init__(cfg, h5_file, mode, max_num_key, cache_data=cache_data) + + + def transform_depth_to_xyzmap(self, batch:BatchPoseData, H_ori, W_ori, bound=1): + bs = len(batch.rgbAs) + H,W = batch.rgbAs.shape[-2:] + mesh_radius = batch.mesh_diameters.cuda()/2 + tf_to_crops = batch.tf_to_crops.cuda() + crop_to_oris = batch.tf_to_crops.inverse().cuda() #(B,3,3) + batch.poseA = batch.poseA.cuda() + batch.Ks = batch.Ks.cuda() + + if batch.xyz_mapAs is None: + depthAs_ori = kornia.geometry.transform.warp_perspective(batch.depthAs.cuda().expand(bs,-1,-1,-1), crop_to_oris, dsize=(H_ori, W_ori), mode='nearest', align_corners=False) + batch.xyz_mapAs = depth2xyzmap_batch(depthAs_ori[:,0], batch.Ks, zfar=np.inf).permute(0,3,1,2) #(B,3,H,W) + batch.xyz_mapAs = kornia.geometry.transform.warp_perspective(batch.xyz_mapAs, tf_to_crops, dsize=(H,W), mode='nearest', align_corners=False) + batch.xyz_mapAs = batch.xyz_mapAs.cuda() + invalid = batch.xyz_mapAs[:,2:3]<0.1 + batch.xyz_mapAs = (batch.xyz_mapAs-batch.poseA[:,:3,3].reshape(bs,3,1,1)) + if self.cfg['normalize_xyz']: + batch.xyz_mapAs *= 1/mesh_radius.reshape(bs,1,1,1) + invalid = invalid.expand(bs,3,-1,-1) | (torch.abs(batch.xyz_mapAs)>=2) + batch.xyz_mapAs[invalid.expand(bs,3,-1,-1)] = 0 + + if batch.xyz_mapBs is None: + depthBs_ori = kornia.geometry.transform.warp_perspective(batch.depthBs.cuda().expand(bs,-1,-1,-1), crop_to_oris, dsize=(H_ori, W_ori), mode='nearest', align_corners=False) + batch.xyz_mapBs = depth2xyzmap_batch(depthBs_ori[:,0], batch.Ks, zfar=np.inf).permute(0,3,1,2) #(B,3,H,W) + batch.xyz_mapBs = kornia.geometry.transform.warp_perspective(batch.xyz_mapBs, tf_to_crops, dsize=(H,W), mode='nearest', align_corners=False) + batch.xyz_mapBs = batch.xyz_mapBs.cuda() + invalid = batch.xyz_mapBs[:,2:3]<0.1 + batch.xyz_mapBs = (batch.xyz_mapBs-batch.poseA[:,:3,3].reshape(bs,3,1,1)) + if self.cfg['normalize_xyz']: + batch.xyz_mapBs *= 1/mesh_radius.reshape(bs,1,1,1) + invalid = invalid.expand(bs,3,-1,-1) | (torch.abs(batch.xyz_mapBs)>=2) + batch.xyz_mapBs[invalid.expand(bs,3,-1,-1)] = 0 + + return batch + + + def transform_batch(self, batch:BatchPoseData, H_ori, W_ori, bound=1): + bs = len(batch.rgbAs) + batch.rgbAs = batch.rgbAs.cuda().float()/255.0 + batch.rgbBs = batch.rgbBs.cuda().float()/255.0 + + batch = self.transform_depth_to_xyzmap(batch, H_ori, W_ori, bound=bound) + return batch + + + +class ScoreMultiPairH5Dataset(TripletH5Dataset): + def __init__(self, cfg, h5_file, mode, max_num_key=None, cache_data=None): + super().__init__(cfg, h5_file, mode, max_num_key, cache_data=cache_data) + if mode in ['train', 'val']: + self.cfg['train_num_pair'] = self.n_perturb + + +class PoseRefinePairH5Dataset(PairH5Dataset): + def __init__(self, cfg, h5_file, mode='train', max_num_key=None, cache_data=None): + super().__init__(cfg=cfg, h5_file=h5_file, mode=mode, max_num_key=max_num_key, cache_data=cache_data) + + if mode!='test': + with h5py.File(h5_file, 'r', libver='latest') as hf: + group = hf[self.object_keys[0]] + for key_perturb in group: + depthA = imageio.imread(group[key_perturb]['depthA'][()]) + depthB = imageio.imread(group[key_perturb]['depthB'][()]) + self.cfg['n_view'] = min(self.cfg['n_view'], depthA.shape[1]//depthB.shape[1]) + logging.info(f'n_view:{self.cfg["n_view"]}') + self.trans_normalizer = group[key_perturb]['trans_normalizer'][()] + if isinstance(self.trans_normalizer, np.ndarray): + self.trans_normalizer = self.trans_normalizer.tolist() + self.rot_normalizer = group[key_perturb]['rot_normalizer'][()]/180.0*np.pi + logging.info(f'self.trans_normalizer:{self.trans_normalizer}, self.rot_normalizer:{self.rot_normalizer}') + break + + + def transform_batch(self, batch:BatchPoseData, H_ori, W_ori, bound=1): + '''Transform the batch before feeding to the network + !NOTE the H_ori, W_ori could be different at test time from the training data, and needs to be set + ''' + bs = len(batch.rgbAs) + batch.rgbAs = batch.rgbAs.cuda().float()/255.0 + batch.rgbBs = batch.rgbBs.cuda().float()/255.0 + + batch = self.transform_depth_to_xyzmap(batch, H_ori, W_ori, bound=bound) + return batch + diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/learning/datasets/pose_dataset.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/learning/datasets/pose_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..8e76ee4645731128daad385879b738ff58eee9fc --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/learning/datasets/pose_dataset.py @@ -0,0 +1,135 @@ +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. + + +import os,sys +from dataclasses import dataclass +from typing import Iterator, List, Optional, Set, Union +import numpy as np +import torch +code_dir = os.path.dirname(os.path.realpath(__file__)) +sys.path.append(f'{code_dir}/../../../../') +from Utils import * + + +@dataclass +class PoseData: + """ + rgb: (h, w, 3) uint8 + depth: (bsz, h, w) float32 + bbox: (4, ) int + K: (3, 3) float32 + """ + rgb: np.ndarray = None + bbox: np.ndarray = None + K: np.ndarray = None + depth: Optional[np.ndarray] = None + object_data = None + mesh_diameter: float = None + rgbA: np.ndarray = None + rgbB: np.ndarray = None + depthA: np.ndarray = None + depthB: np.ndarray = None + maskA = None + maskB = None + poseA: np.ndarray = None #(4,4) + target: float = None + + def __init__(self, rgbA=None, rgbB=None, depthA=None, depthB=None, maskA=None, maskB=None, normalA=None, normalB=None, xyz_mapA=None, xyz_mapB=None, poseA=None, poseB=None, K=None, target=None, mesh_diameter=None, tf_to_crop=None, crop_mask=None, model_pts=None, label=None, model_scale=None): + self.rgbA = rgbA #(H,W,3) or (H,W*n_view,3) when multiview + self.rgbB = rgbB + self.depthA = depthA + self.depthB = depthB + self.poseA = poseA + self.poseB = poseB + self.maskA = maskA + self.maskB = maskB + self.crop_mask = crop_mask + self.normalA = normalA + self.normalB = normalB + self.xyz_mapA = xyz_mapA + self.xyz_mapB = xyz_mapB + self.target = target + self.K = K + self.mesh_diameter = mesh_diameter + self.tf_to_crop = tf_to_crop + self.model_pts = model_pts + self.label = label + self.model_scale = model_scale + + +@dataclass +class BatchPoseData: + """ + rgbs: (bsz, 3, h, w) torch tensor uint8 + depths: (bsz, h, w) float32 + bboxes: (bsz, 4) int + K: (bsz, 3, 3) float32 + """ + + rgbs: torch.Tensor = None + object_datas = None + bboxes: torch.Tensor = None + K: torch.Tensor = None + depths: Optional[torch.Tensor] = None + rgbAs = None + rgbBs = None + depthAs = None + depthBs = None + normalAs = None + normalBs = None + poseA = None #(B,4,4) + poseB = None + targets = None # Score targets, torch tensor (B) + + def __init__(self, rgbAs=None, rgbBs=None, depthAs=None, depthBs=None, normalAs=None, normalBs=None, maskAs=None, maskBs=None, poseA=None, poseB=None, xyz_mapAs=None, xyz_mapBs=None, tf_to_crops=None, Ks=None, crop_masks=None, model_pts=None, mesh_diameters=None, labels=None): + self.rgbAs = rgbAs + self.rgbBs = rgbBs + self.depthAs = depthAs + self.depthBs = depthBs + self.normalAs = normalAs + self.normalBs = normalBs + self.poseA = poseA + self.poseB = poseB + self.maskAs = maskAs + self.maskBs = maskBs + self.xyz_mapAs = xyz_mapAs + self.xyz_mapBs = xyz_mapBs + self.tf_to_crops = tf_to_crops + self.crop_masks = crop_masks + self.Ks = Ks + self.model_pts = model_pts + self.mesh_diameters = mesh_diameters + self.labels = labels + + + def pin_memory(self) -> "BatchPoseData": + for k in self.__dict__: + if self.__dict__[k] is not None: + try: + self.__dict__[k] = self.__dict__[k].pin_memory() + except Exception as e: + pass + return self + + def cuda(self): + for k in self.__dict__: + if self.__dict__[k] is not None: + try: + self.__dict__[k] = self.__dict__[k].cuda() + except: + pass + return self + + def select_by_indices(self, ids): + out = BatchPoseData() + for k in self.__dict__: + if self.__dict__[k] is not None: + out.__dict__[k] = self.__dict__[k][ids.to(self.__dict__[k].device)] + return out + diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/learning/models/network_modules.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/learning/models/network_modules.py new file mode 100644 index 0000000000000000000000000000000000000000..a0e4246628fcf60ab7b1cc44bca789892ac59bc6 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/learning/models/network_modules.py @@ -0,0 +1,138 @@ +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. + + +import os,sys,copy,math,tqdm +import numpy as np +dir_path = os.path.dirname(os.path.realpath(__file__)) +sys.path.append(dir_path) +import torch.nn.functional as F +import torch +import torch.nn as nn +import time +import cv2 +sys.path.append(f'{dir_path}/../../../../') +from Utils import * + + + +class ConvBN(nn.Module): + def __init__(self, C_in, C_out, kernel_size=3, stride=1, groups=1, bias=True,dilation=1,): + super().__init__() + padding = (kernel_size - 1) // 2 + self.net = nn.Sequential( + nn.Conv2d(C_in, C_out, kernel_size, stride, padding, groups=groups, bias=bias,dilation=dilation), + nn.BatchNorm2d(C_out), + ) + + def forward(self, x): + return self.net(x) + + +class ConvBNReLU(nn.Module): + def __init__(self, C_in, C_out, kernel_size=3, stride=1, groups=1, bias=True,dilation=1, norm_layer=nn.BatchNorm2d): + super().__init__() + padding = (kernel_size - 1) // 2 + layers = [ + nn.Conv2d(C_in, C_out, kernel_size, stride, padding, groups=groups, bias=bias,dilation=dilation), + ] + if norm_layer is not None: + layers.append(norm_layer(C_out)) + layers.append(nn.ReLU(inplace=True)) + self.net = nn.Sequential(*layers) + + def forward(self, x): + return self.net(x) + + +class ConvPadding(nn.Module): + def __init__(self,C_in, C_out, kernel_size=3, stride=1, groups=1, bias=True,dilation=1): + super(ConvPadding, self).__init__() + padding = (kernel_size - 1) // 2 + self.conv = nn.Conv2d(C_in, C_out, kernel_size, stride, padding, groups=groups, bias=bias,dilation=dilation) + + def forward(self,x): + return self.conv(x) + + +def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1, bias=False): + """3x3 convolution with padding""" + return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, + padding=dilation, groups=groups, bias=bias, dilation=dilation) + + +def conv1x1(in_planes, out_planes, stride=1, bias=False): + """1x1 convolution""" + return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=bias) + +class ResnetBasicBlock(nn.Module): + __constants__ = ['downsample'] + + def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1, base_width=64, dilation=1, norm_layer=nn.BatchNorm2d, bias=False): + super().__init__() + self.norm_layer = norm_layer + if groups != 1 or base_width != 64: + raise ValueError('BasicBlock only supports groups=1 and base_width=64') + if dilation > 1: + raise NotImplementedError("Dilation > 1 not supported in BasicBlock") + # Both self.conv1 and self.downsample layers downsample the input when stride != 1 + self.conv1 = conv3x3(inplanes, planes, stride,bias=bias) + if self.norm_layer is not None: + self.bn1 = norm_layer(planes) + self.relu = nn.ReLU(inplace=True) + self.conv2 = conv3x3(planes, planes,bias=bias) + if self.norm_layer is not None: + self.bn2 = norm_layer(planes) + self.downsample = downsample + self.stride = stride + + def forward(self, x): + identity = x + + out = self.conv1(x) + if self.norm_layer is not None: + out = self.bn1(out) + out = self.relu(out) + + out = self.conv2(out) + if self.norm_layer is not None: + out = self.bn2(out) + + if self.downsample is not None: + identity = self.downsample(x) + out += identity + out = self.relu(out) + + return out + + + +class PositionalEmbedding(nn.Module): + def __init__(self, d_model, max_len=512): + super().__init__() + + # Compute the positional encodings once in log space. + pe = torch.zeros(max_len, d_model).float() + pe.require_grad = False + + position = torch.arange(0, max_len).float().unsqueeze(1) #(N,1) + div_term = (torch.arange(0, d_model, 2).float() * -(math.log(10000.0) / d_model)).exp()[None] + + pe[:, 0::2] = torch.sin(position * div_term) #(N, d_model/2) + pe[:, 1::2] = torch.cos(position * div_term) + + pe = pe.unsqueeze(0) + self.register_buffer('pe', pe) #(1, max_len, D) + + + def forward(self, x): + ''' + @x: (B,N,D) + ''' + return x + self.pe[:, :x.size(1)] + diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/learning/models/refine_network.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/learning/models/refine_network.py new file mode 100644 index 0000000000000000000000000000000000000000..c2e399efc309f36129ad0365c940de71df443f60 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/learning/models/refine_network.py @@ -0,0 +1,93 @@ +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. + + +import os,sys +import numpy as np +code_dir = os.path.dirname(os.path.realpath(__file__)) +sys.path.append(code_dir) +sys.path.append(f'{code_dir}/../../../../') +from Utils import * +import torch.nn.functional as F +import torch +import torch.nn as nn +import cv2 +from functools import partial +from network_modules import * +from Utils import * + + + +class RefineNet(nn.Module): + def __init__(self, cfg=None, c_in=4, n_view=1): + super().__init__() + self.cfg = cfg + if self.cfg.use_BN: + norm_layer = nn.BatchNorm2d + norm_layer1d = nn.BatchNorm1d + else: + norm_layer = None + norm_layer1d = None + + self.encodeA = nn.Sequential( + ConvBNReLU(C_in=c_in,C_out=64,kernel_size=7,stride=2, norm_layer=norm_layer), + ConvBNReLU(C_in=64,C_out=128,kernel_size=3,stride=2, norm_layer=norm_layer), + ResnetBasicBlock(128,128,bias=True, norm_layer=norm_layer), + ResnetBasicBlock(128,128,bias=True, norm_layer=norm_layer), + ) + + self.encodeAB = nn.Sequential( + ResnetBasicBlock(256,256,bias=True, norm_layer=norm_layer), + ResnetBasicBlock(256,256,bias=True, norm_layer=norm_layer), + ConvBNReLU(256,512,kernel_size=3,stride=2, norm_layer=norm_layer), + ResnetBasicBlock(512,512,bias=True, norm_layer=norm_layer), + ResnetBasicBlock(512,512,bias=True, norm_layer=norm_layer), + ) + + embed_dim = 512 + num_heads = 4 + self.pos_embed = PositionalEmbedding(d_model=embed_dim, max_len=400) + + self.trans_head = nn.Sequential( + nn.TransformerEncoderLayer(d_model=embed_dim, nhead=num_heads, dim_feedforward=512, batch_first=True), + nn.Linear(512, 3), + ) + + if self.cfg['rot_rep']=='axis_angle': + rot_out_dim = 3 + elif self.cfg['rot_rep']=='6d': + rot_out_dim = 6 + else: + raise RuntimeError + self.rot_head = nn.Sequential( + nn.TransformerEncoderLayer(d_model=embed_dim, nhead=num_heads, dim_feedforward=512, batch_first=True), + nn.Linear(512, rot_out_dim), + ) + + + def forward(self, A, B): + """ + @A: (B,C,H,W) + """ + bs = len(A) + output = {} + + x = torch.cat([A,B], dim=0) + x = self.encodeA(x) + a = x[:bs] + b = x[bs:] + + ab = torch.cat((a,b),1).contiguous() + ab = self.encodeAB(ab) #(B,C,H,W) + + ab = self.pos_embed(ab.reshape(bs, ab.shape[1], -1).permute(0,2,1)) + + output['trans'] = self.trans_head(ab).mean(dim=1) + output['rot'] = self.rot_head(ab).mean(dim=1) + + return output diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/learning/models/score_network.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/learning/models/score_network.py new file mode 100644 index 0000000000000000000000000000000000000000..fbf362ec0f9d95d4ecbd00ef0d64c6d5d903f9e7 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/learning/models/score_network.py @@ -0,0 +1,90 @@ +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. + + +import os,sys +import numpy as np +code_dir = os.path.dirname(os.path.realpath(__file__)) +sys.path.append(code_dir) +sys.path.append(f'{code_dir}/../../../../') +from Utils import * +from functools import partial +import torch.nn.functional as F +import torch +import torch.nn as nn +import cv2 +from network_modules import * +from Utils import * + + + + +class ScoreNetMultiPair(nn.Module): + def __init__(self, cfg=None, c_in=4): + super().__init__() + self.cfg = cfg + if self.cfg.use_BN: + norm_layer = nn.BatchNorm2d + else: + norm_layer = None + + self.encoderA = nn.Sequential( + ConvBNReLU(C_in=c_in,C_out=64,kernel_size=7,stride=2, norm_layer=norm_layer), + ConvBNReLU(C_in=64,C_out=128,kernel_size=3,stride=2, norm_layer=norm_layer), + ResnetBasicBlock(128,128,bias=True, norm_layer=norm_layer), + ResnetBasicBlock(128,128,bias=True, norm_layer=norm_layer), + ) + + self.encoderAB = nn.Sequential( + ResnetBasicBlock(256,256,bias=True, norm_layer=norm_layer), + ResnetBasicBlock(256,256,bias=True, norm_layer=norm_layer), + ConvBNReLU(256,512,kernel_size=3,stride=2, norm_layer=norm_layer), + ResnetBasicBlock(512,512,bias=True, norm_layer=norm_layer), + ResnetBasicBlock(512,512,bias=True, norm_layer=norm_layer), + ) + + embed_dim = 512 + num_heads = 4 + self.att = nn.MultiheadAttention(embed_dim=embed_dim, num_heads=num_heads, bias=True, batch_first=True) + self.att_cross = nn.MultiheadAttention(embed_dim=embed_dim, num_heads=num_heads, bias=True, batch_first=True) + + self.pos_embed = PositionalEmbedding(d_model=embed_dim, max_len=400) + self.linear = nn.Linear(embed_dim, 1) + + + def extract_feat(self, A, B): + """ + @A: (B*L,C,H,W) L is num of pairs + """ + bs = A.shape[0] # B*L + + x = torch.cat([A,B], dim=0) + x = self.encoderA(x) + a = x[:bs] + b = x[bs:] + ab = torch.cat((a,b), dim=1) + ab = self.encoderAB(ab) + ab = self.pos_embed(ab.reshape(bs, ab.shape[1], -1).permute(0,2,1)) + ab, _ = self.att(ab, ab, ab) + return ab.mean(dim=1).reshape(bs,-1) + + + def forward(self, A, B, L): + """ + @A: (B*L,C,H,W) L is num of pairs + @L: num of pairs + """ + output = {} + bs = A.shape[0]//L + feats = self.extract_feat(A, B) #(B*L, C) + x = feats.reshape(bs,L,-1) + x, _ = self.att_cross(x, x, x) + + output['score_logit'] = self.linear(x).reshape(bs,L) # (B,L) + + return output diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/learning/training/predict_pose_refine.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/learning/training/predict_pose_refine.py new file mode 100644 index 0000000000000000000000000000000000000000..71d68d5a927ab8310ba759930a95b51d6b565610 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/learning/training/predict_pose_refine.py @@ -0,0 +1,374 @@ +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. + + +import functools +import os,sys,kornia +import time +code_dir = os.path.dirname(os.path.realpath(__file__)) +sys.path.append(f'{code_dir}/../../') +import numpy as np +import torch +from omegaconf import OmegaConf +from learning.models.refine_network import RefineNet +from learning.datasets.h5_dataset import * +from Utils import * +from datareader import * + +def crop_and_pad_rgb(rgb, padding=20): + if isinstance(rgb, torch.Tensor): + rgb = rgb.data.cpu().numpy() + rgb = rgb.astype(np.uint8) + valid_points = np.where(rgb.sum(axis=-1) > 10) + x, y, w, h = np.min(valid_points[1]), np.min(valid_points[0]), np.max(valid_points[1])-np.min(valid_points[1]), np.max(valid_points[0])-np.min(valid_points[0]) + center_x = x + w // 2 + center_y = y + h // 2 + radius = max(w, h) // 2 + x_min = max(0, center_x - radius) + x_max = min(rgb.shape[1], center_x + radius) + y_min = max(0, center_y - radius) + y_max = min(rgb.shape[0], center_y + radius) + + # Crop the non-zero region + cropped_rgb = rgb[y_min:y_max, x_min:x_max] + + # Resize the cropped region to a fixed size + resized_rgb = cv2.resize(cropped_rgb, (140, 140), interpolation=cv2.INTER_AREA) + + # Calculate padding + padding = 10 # Assuming 20 pixels of padding on each side + padded_rgb = cv2.copyMakeBorder(resized_rgb, padding, padding, padding, padding, cv2.BORDER_CONSTANT, value=[0, 0, 0]) + return padded_rgb + +@torch.inference_mode() +def make_crop_data_batch(render_size, ob_in_cams, mesh, rgb, depth, K, crop_ratio, xyz_map, normal_map=None, mesh_diameter=None, cfg=None, glctx=None, mesh_tensors=None, dataset:PoseRefinePairH5Dataset=None, bg_color='white', object_level=False, rgb_only=False): + logging.info("Welcome make_crop_data_batch") + H,W = depth.shape[:2] + args = [] + method = 'box_3d' + tf_to_crops = compute_crop_window_tf_batch(pts=mesh.vertices, H=H, W=W, poses=ob_in_cams, K=K, crop_ratio=crop_ratio, out_size=(render_size[1], render_size[0]), method=method, mesh_diameter=mesh_diameter) + + logging.info("make tf_to_crops done") + + B = len(ob_in_cams) + poseA = torch.as_tensor(ob_in_cams, dtype=torch.float, device='cuda') + + bs = 512 + rgb_rs = [] + depth_rs = [] + normal_rs = [] + xyz_map_rs = [] + + bbox2d_crop = torch.as_tensor(np.array([0, 0, cfg['input_resize'][0]-1, cfg['input_resize'][1]-1]).reshape(2,2), device='cuda', dtype=torch.float) + bbox2d_ori = transform_pts(bbox2d_crop, tf_to_crops.inverse()).reshape(-1,4) + + for b in range(0,len(poseA),bs): + extra = {} + rgb_r, depth_r, normal_r = nvdiffrast_render(K=K, H=H, W=W, ob_in_cams=poseA[b:b+bs], context='cuda', get_normal=cfg['use_normal'], glctx=glctx, mesh_tensors=mesh_tensors, output_size=cfg['input_resize'], bbox2d=bbox2d_ori[b:b+bs], use_light=True, extra=extra) + rgb_rs.append(rgb_r) + depth_rs.append(depth_r[...,None]) + normal_rs.append(normal_r) + xyz_map_rs.append(extra['xyz_map']) + + rgb_rs = torch.cat(rgb_rs, dim=0).permute(0,3,1,2) * 255 + depth_rs = torch.cat(depth_rs, dim=0).permute(0,3,1,2) #(B,1,H,W) + xyz_map_rs = torch.cat(xyz_map_rs, dim=0).permute(0,3,1,2) #(B,3,H,W) + Ks = torch.as_tensor(K, device='cuda', dtype=torch.float).reshape(1,3,3) + if cfg['use_normal']: + normal_rs = torch.cat(normal_rs, dim=0).permute(0,3,1,2) #(B,3,H,W) + + logging.info("render done") + + # debug rendered depth + depth_debug = depth_rs[0].permute(1,2,0).data.cpu().numpy() + H,W = depth_debug.shape[:2] + zmin = depth_debug.min() + zmax = depth_debug.max() + depth_vis = depth_to_vis(depth_debug, zmin=zmin, zmax=zmax, inverse=False, mode='gray') + + if bg_color == 'white': + fill_value = torch.tensor([255,255,255], device='cuda') + elif bg_color == 'black': + fill_value = torch.tensor([0,0,0], device='cuda') + else: + raise ValueError(f'Invalid background color: {bg_color}') + + # crop and pad referemce image + if object_level: + rgbBs_padded = crop_and_pad_rgb(rgb) + rgbBs = torch.as_tensor(rgbBs_padded, dtype=torch.float, device='cuda').permute(2,0,1)[None].expand(B,-1,-1,-1) + # rgbBs = torch.as_tensor(cv2.resize(rgb, (160, 160), interpolation=cv2.INTER_AREA), dtype=torch.float, device='cuda').permute(2,0,1)[None].expand(B,-1,-1,-1) + else: + rgbBs = kornia.geometry.transform.warp_perspective(torch.as_tensor(rgb, dtype=torch.float, device='cuda').permute(2,0,1)[None].expand(B,-1,-1,-1), tf_to_crops, dsize=render_size, mode='bilinear', align_corners=False, padding_mode='fill', fill_value=fill_value) + + + if rgb_rs.shape[-2:]!=cfg['input_resize']: + rgbAs = kornia.geometry.transform.warp_perspective(rgb_rs, tf_to_crops, dsize=render_size, mode='bilinear', align_corners=False, padding_mode='fill', fill_value=fill_value) + else: + rgbAs = rgb_rs + if xyz_map_rs.shape[-2:]!=cfg['input_resize']: + xyz_mapAs = kornia.geometry.transform.warp_perspective(xyz_map_rs, tf_to_crops, dsize=render_size, mode='nearest', align_corners=False) + else: + xyz_mapAs = xyz_map_rs + + # warp reference xyz map + if object_level: + if isinstance(xyz_map, torch.Tensor): + xyz_mapBs = torch.as_tensor(cv2.resize(xyz_map.data.cpu().numpy(), (160, 160), interpolation=cv2.INTER_NEAREST), dtype=torch.float, device='cuda').permute(2,0,1)[None].expand(B,-1,-1,-1) + elif isinstance(xyz_map, np.ndarray): + xyz_mapBs = torch.as_tensor(cv2.resize(xyz_map, (160, 160), interpolation=cv2.INTER_NEAREST), dtype=torch.float, device='cuda').permute(2,0,1)[None].expand(B,-1,-1,-1) + else: + raise ValueError(f'Invalid rgb type: {type(rgb)}') + else: + xyz_mapBs = kornia.geometry.transform.warp_perspective(torch.as_tensor(xyz_map, dtype=torch.float, device='cuda').permute(2,0,1)[None].expand(B,-1,-1,-1), tf_to_crops, dsize=render_size, mode='nearest', align_corners=False) + + if rgb_only: + xyz_mapAs = torch.zeros_like(xyz_mapAs) + xyz_mapBs = torch.zeros_like(xyz_mapBs) + + # xyz_mapBs = kornia.geometry.transform.warp_perspective(torch.as_tensor(xyz_map, device='cuda', dtype=torch.float).permute(2,0,1)[None].expand(B,-1,-1,-1), tf_to_crops, dsize=render_size, mode='nearest', align_corners=False) #(B,3,H,W) + + if cfg['use_normal']: + normalAs = kornia.geometry.transform.warp_perspective(normal_rs, tf_to_crops, dsize=render_size, mode='nearest', align_corners=False) + normalBs = kornia.geometry.transform.warp_perspective(torch.as_tensor(normal_map, dtype=torch.float, device='cuda').permute(2,0,1)[None].expand(B,-1,-1,-1), tf_to_crops, dsize=render_size, mode='nearest', align_corners=False) + else: + normalAs = None + normalBs = None + + logging.info("warp done") + + + # crop and pad rendered image + for i in range(rgbAs.shape[0]): + rgb = crop_and_pad_rgb(rgbAs[i].permute(1,2,0)) + rgbAs[i] = torch.as_tensor(rgb, dtype=torch.float, device='cuda').permute(2,0,1) + + mesh_diameters = torch.ones((len(rgbAs)), dtype=torch.float, device='cuda')*mesh_diameter + pose_data = BatchPoseData(rgbAs=rgbAs, rgbBs=rgbBs, depthAs=None, depthBs=None, normalAs=normalAs, normalBs=normalBs, poseA=poseA, poseB=None, xyz_mapAs=xyz_mapAs, xyz_mapBs=xyz_mapBs, tf_to_crops=tf_to_crops, Ks=Ks, mesh_diameters=mesh_diameters) + pose_data = dataset.transform_batch(batch=pose_data, H_ori=H, W_ori=W, bound=1) + + logging.info("pose batch data done") + + return pose_data + + + +class PoseRefinePredictor: + def __init__(self, ckpt_root_dir=None): + logging.info("welcome") + self.amp = True + self.run_name = "2023-10-28-18-33-37" + model_name = 'model_best.pth' + code_dir = os.path.dirname(os.path.realpath(__file__)) + ckpt_dir = f'{ckpt_root_dir}/{self.run_name}/{model_name}' + + self.cfg = OmegaConf.load(f'{ckpt_root_dir}/{self.run_name}/config.yml') + + self.cfg['ckpt_dir'] = ckpt_dir + self.cfg['enable_amp'] = True + + ########## Defaults, to be backward compatible + if 'use_normal' not in self.cfg: + self.cfg['use_normal'] = False + if 'use_mask' not in self.cfg: + self.cfg['use_mask'] = False + if 'use_BN' not in self.cfg: + self.cfg['use_BN'] = False + if 'c_in' not in self.cfg: + self.cfg['c_in'] = 4 + if 'crop_ratio' not in self.cfg or self.cfg['crop_ratio'] is None: + self.cfg['crop_ratio'] = 1.4 + if 'n_view' not in self.cfg: + self.cfg['n_view'] = 1 + if 'trans_rep' not in self.cfg: + self.cfg['trans_rep'] = 'tracknet' + if 'rot_rep' not in self.cfg: + self.cfg['rot_rep'] = 'axis_angle' + if 'zfar' not in self.cfg: + self.cfg['zfar'] = 3 + if 'normalize_xyz' not in self.cfg: + self.cfg['normalize_xyz'] = False + if isinstance(self.cfg['zfar'], str) and 'inf' in self.cfg['zfar'].lower(): + self.cfg['zfar'] = np.inf + if 'normal_uint8' not in self.cfg: + self.cfg['normal_uint8'] = False + logging.info(f"self.cfg: \n {OmegaConf.to_yaml(self.cfg)}") + + self.dataset = PoseRefinePairH5Dataset(cfg=self.cfg, h5_file='', mode='test') + self.model = RefineNet(cfg=self.cfg, c_in=self.cfg['c_in']).cuda() + + logging.info(f"Using pretrained model from {ckpt_dir}") + ckpt = torch.load(ckpt_dir) + if 'model' in ckpt: + ckpt = ckpt['model'] + self.model.load_state_dict(ckpt) + + self.model.cuda().eval() + logging.info("init done") + self.last_trans_update = None + self.last_rot_update = None + + + @torch.inference_mode() + def predict(self, refiner_debug_dir,rgb, depth, K, ob_in_cams, xyz_map, normal_map=None, get_vis=False, mesh=None, mesh_tensors=None, glctx=None, mesh_diameter=None, iteration=5, bg_color='white', object_level=False, rgb_only=False, crop_ratio=1.4): + ''' + @rgb: np array (H,W,3) + @ob_in_cams: np array (N,4,4) + ''' + torch.set_default_tensor_type('torch.cuda.FloatTensor') + logging.info(f'ob_in_cams:{ob_in_cams.shape}') + tf_to_center = np.eye(4) + ob_centered_in_cams = ob_in_cams + mesh_centered = mesh + + logging.info(f'self.cfg.use_normal:{self.cfg.use_normal}') + if not self.cfg.use_normal: + normal_map = None + + # crop_ratio = self.cfg['crop_ratio'] + logging.info(f"trans_normalizer:{self.cfg['trans_normalizer']}, rot_normalizer:{self.cfg['rot_normalizer']}") + bs = 1024 + + B_in_cams = torch.as_tensor(ob_centered_in_cams, device='cuda', dtype=torch.float) + + + if mesh_tensors is None: + mesh_tensors = make_mesh_tensors(mesh_centered) + + rgb_tensor = torch.as_tensor(rgb, device='cuda', dtype=torch.float) + depth_tensor = torch.as_tensor(depth, device='cuda', dtype=torch.float) + xyz_map_tensor = torch.as_tensor(xyz_map, device='cuda', dtype=torch.float) + trans_normalizer = self.cfg['trans_normalizer'] + if not isinstance(trans_normalizer, float): + trans_normalizer = torch.as_tensor(list(trans_normalizer), device='cuda', dtype=torch.float).reshape(1,3) + + for _ in range(iteration): + logging.info("making cropped data") + pose_data = make_crop_data_batch(self.cfg.input_resize, B_in_cams, mesh_centered, rgb_tensor, depth_tensor, K, crop_ratio=crop_ratio, normal_map=normal_map, xyz_map=xyz_map_tensor, cfg=self.cfg, glctx=glctx, mesh_tensors=mesh_tensors, dataset=self.dataset, mesh_diameter=mesh_diameter, bg_color=bg_color, object_level=object_level, rgb_only=rgb_only) + + + + B_in_cams = [] + for b in range(0, pose_data.rgbAs.shape[0], bs): + A = torch.cat([pose_data.rgbAs[b:b+bs].cuda(), pose_data.xyz_mapAs[b:b+bs].cuda()], dim=1).float() + B = torch.cat([pose_data.rgbBs[b:b+bs].cuda(), pose_data.xyz_mapBs[b:b+bs].cuda()], dim=1).float() + logging.info("forward start") + with torch.cuda.amp.autocast(enabled=self.amp): + output = self.model(A,B) + for k in output: + output[k] = output[k].float() + logging.info("forward done") + if self.cfg['trans_rep']=='tracknet': + if not self.cfg['normalize_xyz']: + trans_delta = torch.tanh(output["trans"])*trans_normalizer + else: + trans_delta = output["trans"] + + elif self.cfg['trans_rep']=='deepim': + def project_and_transform_to_crop(centers): + uvs = (pose_data.Ks[b:b+bs]@centers.reshape(-1,3,1)).reshape(-1,3) + uvs = uvs/uvs[:,2:3] + uvs = (pose_data.tf_to_crops[b:b+bs]@uvs.reshape(-1,3,1)).reshape(-1,3) + return uvs[:,:2] + + rot_delta = output["rot"] + z_pred = output['trans'][:,2]*pose_data.poseA[b:b+bs][...,2,3] + uvA_crop = project_and_transform_to_crop(pose_data.poseA[b:b+bs][...,:3,3]) + uv_pred_crop = uvA_crop + output['trans'][:,:2]*self.cfg['input_resize'][0] + uv_pred = transform_pts(uv_pred_crop, pose_data.tf_to_crops[b:b+bs].inverse().cuda()) + center_pred = torch.cat([uv_pred, torch.ones((len(rot_delta),1), dtype=torch.float, device='cuda')], dim=-1) + center_pred = (pose_data.Ks[b:b+bs].inverse().cuda()@center_pred.reshape(len(rot_delta),3,1)).reshape(len(rot_delta),3) * z_pred.reshape(len(rot_delta),1) + trans_delta = center_pred-pose_data.poseA[b:b+bs][...,:3,3] + + else: + trans_delta = output["trans"] + + if self.cfg['rot_rep']=='axis_angle': + rot_mat_delta = torch.tanh(output["rot"])*self.cfg['rot_normalizer'] + rot_mat_delta = so3_exp_map(rot_mat_delta).permute(0,2,1) + elif self.cfg['rot_rep']=='6d': + rot_mat_delta = rotation_6d_to_matrix(output['rot']).permute(0,2,1) + else: + raise RuntimeError + + if self.cfg['normalize_xyz']: + trans_delta *= (mesh_diameter/2) + + B_in_cam = egocentric_delta_pose_to_pose(pose_data.poseA[b:b+bs], trans_delta=trans_delta, rot_mat_delta=rot_mat_delta) + B_in_cams.append(B_in_cam) + + B_in_cams = torch.cat(B_in_cams, dim=0).reshape(len(ob_in_cams),4,4) + + B_in_cams_out = B_in_cams@torch.tensor(tf_to_center[None], device='cuda', dtype=torch.float) + torch.cuda.empty_cache() + self.last_trans_update = trans_delta + self.last_rot_update = rot_mat_delta + + if get_vis: + logging.info("get_vis...") + canvas = [] + padding = 2 + pose_data = make_crop_data_batch(self.cfg.input_resize, torch.as_tensor(ob_centered_in_cams), mesh_centered, rgb, depth, K, crop_ratio=crop_ratio, normal_map=normal_map, xyz_map=xyz_map_tensor, cfg=self.cfg, glctx=glctx, mesh_tensors=mesh_tensors, dataset=self.dataset, mesh_diameter=mesh_diameter, bg_color=bg_color, object_level=object_level, rgb_only=rgb_only) + for id in range(0, len(B_in_cams)): + rgbA_vis = (pose_data.rgbAs[id]*255).permute(1,2,0).data.cpu().numpy() + rgbB_vis = (pose_data.rgbBs[id]*255).permute(1,2,0).data.cpu().numpy() + + row = [rgbA_vis, rgbB_vis] + H,W = rgbA_vis.shape[:2] + if pose_data.depthAs is not None: + depthA = pose_data.depthAs[id].data.cpu().numpy().reshape(H,W) + depthB = pose_data.depthBs[id].data.cpu().numpy().reshape(H,W) + elif pose_data.xyz_mapAs is not None: + depthA = pose_data.xyz_mapAs[id][2].data.cpu().numpy().reshape(H,W) + depthB = pose_data.xyz_mapBs[id][2].data.cpu().numpy().reshape(H,W) + zmin = min(depthA.min(), depthB.min()) + zmax = max(depthA.max(), depthB.max()) + depthA_vis = depth_to_vis(depthA, zmin=zmin, zmax=zmax, inverse=False) + depthB_vis = depth_to_vis(depthB, zmin=zmin, zmax=zmax, inverse=False) + row += [depthA_vis, depthB_vis] + if pose_data.normalAs is not None: + pass + row = make_grid_image(row, nrow=len(row), padding=padding, pad_value=255) + row = cv_draw_text(row, text=f'id:{id}', uv_top_left=(10,10), color=(0,255,0), fontScale=0.5) + canvas.append(row) + canvas = make_grid_image(canvas, nrow=1, padding=padding, pad_value=255) + + pose_data = make_crop_data_batch(self.cfg.input_resize, B_in_cams, mesh_centered, rgb, depth, K, crop_ratio=crop_ratio, normal_map=normal_map, xyz_map=xyz_map_tensor, cfg=self.cfg, glctx=glctx, mesh_tensors=mesh_tensors, dataset=self.dataset, mesh_diameter=mesh_diameter, bg_color=bg_color, object_level=object_level, rgb_only=rgb_only) + canvas_refined = [] + for id in range(0, len(B_in_cams)): + rgbA_vis = (pose_data.rgbAs[id]*255).permute(1,2,0).data.cpu().numpy() + rgbB_vis = (pose_data.rgbBs[id]*255).permute(1,2,0).data.cpu().numpy() + + # save rgbA_vis and rgbB_vis + cv2.imwrite(f'{refiner_debug_dir}/rgbA_vis_{id}.png', rgbA_vis[:,:,::-1]) + cv2.imwrite(f'{refiner_debug_dir}/rgbB_vis_{id}.png', rgbB_vis[:,:,::-1]) + np.savetxt(f'{refiner_debug_dir}/ob_in_cam_{id}.txt', B_in_cams_out.data.cpu().numpy()[id].reshape(4,4)) + + row = [rgbA_vis, rgbB_vis] + H,W = rgbA_vis.shape[:2] + if pose_data.depthAs is not None: + depthA = pose_data.depthAs[id].data.cpu().numpy().reshape(H,W) + depthB = pose_data.depthBs[id].data.cpu().numpy().reshape(H,W) + elif pose_data.xyz_mapAs is not None: + depthA = pose_data.xyz_mapAs[id][2].data.cpu().numpy().reshape(H,W) + depthB = pose_data.xyz_mapBs[id][2].data.cpu().numpy().reshape(H,W) + zmin = min(depthA.min(), depthB.min()) + zmax = max(depthA.max(), depthB.max()) + depthA_vis = depth_to_vis(depthA, zmin=zmin, zmax=zmax, inverse=False) + depthB_vis = depth_to_vis(depthB, zmin=zmin, zmax=zmax, inverse=False) + row += [depthA_vis, depthB_vis] + row = make_grid_image(row, nrow=len(row), padding=padding, pad_value=255) + canvas_refined.append(row) + + canvas_refined = make_grid_image(canvas_refined, nrow=1, padding=padding, pad_value=255) + canvas = make_grid_image([canvas, canvas_refined], nrow=2, padding=padding, pad_value=255) + torch.cuda.empty_cache() + return B_in_cams_out, canvas + + return B_in_cams_out, None + diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/learning/training/predict_score.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/learning/training/predict_score.py new file mode 100644 index 0000000000000000000000000000000000000000..19a913f84df75de432f398617c93e8627a549e2b --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/learning/training/predict_score.py @@ -0,0 +1,292 @@ +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. + + +import functools +import os,sys,kornia +import time +import numpy as np +import torch +import torch.distributed as dist +from omegaconf import OmegaConf +from tqdm import tqdm +code_dir = os.path.dirname(os.path.realpath(__file__)) +sys.path.append(f'{code_dir}/../../../') +from learning.datasets.h5_dataset import * +from learning.models.score_network import * +from learning.datasets.pose_dataset import * +from Utils import * +from datareader import * + + +def vis_batch_data_scores(pose_data, ids, scores, pad_margin=5): + assert len(scores)==len(ids) + canvas = [] + for id in ids[:10]: + rgbA_vis = (pose_data.rgbAs[id]*255).permute(1,2,0).data.cpu().numpy() + rgbB_vis = (pose_data.rgbBs[id]*255).permute(1,2,0).data.cpu().numpy() + H,W = rgbA_vis.shape[:2] + zmin = pose_data.depthAs[id].data.cpu().numpy().reshape(H,W).min() + zmax = pose_data.depthAs[id].data.cpu().numpy().reshape(H,W).max() + + # debug depth in gray mode + depthA_vis_gray = depth_to_vis(pose_data.depthAs[id].data.cpu().numpy().reshape(H,W), zmin=zmin, zmax=zmax, inverse=False, mode='gray') + depthB_vis_gray = depth_to_vis(pose_data.depthBs[id].data.cpu().numpy().reshape(H,W), zmin=zmin, zmax=zmax, inverse=False, mode='gray') + + depthA_vis = depth_to_vis(pose_data.depthAs[id].data.cpu().numpy().reshape(H,W), zmin=zmin, zmax=zmax, inverse=False) + depthB_vis = depth_to_vis(pose_data.depthBs[id].data.cpu().numpy().reshape(H,W), zmin=zmin, zmax=zmax, inverse=False) + if pose_data.normalAs is not None: + pass + pad = np.ones((rgbA_vis.shape[0],pad_margin,3))*255 + if pose_data.normalAs is not None: + pass + else: + row = np.concatenate([rgbA_vis, pad, depthA_vis, pad, rgbB_vis, pad, depthB_vis], axis=1) + s = 100/row.shape[0] + row = cv2.resize(row, fx=s, fy=s, dsize=None) + row = cv_draw_text(row, text=f'id:{id}, score:{scores[id]:.3f}', uv_top_left=(10,10), color=(0,255,0), fontScale=0.5) + canvas.append(row) + pad = np.ones((pad_margin, row.shape[1], 3))*255 + canvas.append(pad) + canvas = np.concatenate(canvas, axis=0).astype(np.uint8) + return canvas + +def crop_and_pad_rgb(rgb, padding=20): + if isinstance(rgb, torch.Tensor): + rgb = rgb.data.cpu().numpy() + rgb = rgb.astype(np.uint8) + valid_points = np.where(rgb.sum(axis=-1) > 10) + x, y, w, h = np.min(valid_points[1]), np.min(valid_points[0]), np.max(valid_points[1])-np.min(valid_points[1]), np.max(valid_points[0])-np.min(valid_points[0]) + + center_x = x + w // 2 + center_y = y + h // 2 + radius = max(w, h) // 2 + x_min = max(0, center_x - radius) + x_max = min(rgb.shape[1], center_x + radius) + y_min = max(0, center_y - radius) + y_max = min(rgb.shape[0], center_y + radius) + + # Crop the non-zero region + cropped_rgb = rgb[y_min:y_max, x_min:x_max] + + # Resize the cropped region to a fixed size + resized_rgb = cv2.resize(cropped_rgb, (140, 140), interpolation=cv2.INTER_AREA) + + # Calculate padding + padding = 10 # Assuming 20 pixels of padding on each side + padded_rgb = cv2.copyMakeBorder(resized_rgb, padding, padding, padding, padding, cv2.BORDER_CONSTANT, value=[0, 0, 0]) + return padded_rgb + +@torch.no_grad() +def make_crop_data_batch(render_size, ob_in_cams, mesh, rgb, depth, K, crop_ratio, normal_map=None, mesh_diameter=None, glctx=None, mesh_tensors=None, dataset:TripletH5Dataset=None, cfg=None, bg_color='white', object_level=False, rgb_only=False): + logging.info("Welcome make_crop_data_batch") + H,W = depth.shape[:2] + + args = [] + method = 'box_3d' + tf_to_crops = compute_crop_window_tf_batch(pts=mesh.vertices, H=H, W=W, poses=ob_in_cams, K=K, crop_ratio=crop_ratio, out_size=(render_size[1], render_size[0]), method=method, mesh_diameter=mesh_diameter) + logging.info("make tf_to_crops done") + + B = len(ob_in_cams) + poseAs = torch.as_tensor(ob_in_cams, dtype=torch.float, device='cuda') + + bs = 512 + rgb_rs = [] + depth_rs = [] + xyz_map_rs = [] + + bbox2d_crop = torch.as_tensor(np.array([0, 0, cfg['input_resize'][0]-1, cfg['input_resize'][1]-1]).reshape(2,2), device='cuda', dtype=torch.float) + bbox2d_ori = transform_pts(bbox2d_crop, tf_to_crops.inverse()[:,None]).reshape(-1,4) + + for b in range(0,len(ob_in_cams),bs): + extra = {} + rgb_r, depth_r, normal_r = nvdiffrast_render(K=K, H=H, W=W, ob_in_cams=poseAs[b:b+bs], context='cuda', get_normal=cfg['use_normal'], glctx=glctx, mesh_tensors=mesh_tensors, output_size=cfg['input_resize'], bbox2d=bbox2d_ori[b:b+bs], use_light=True, extra=extra) + rgb_rs.append(rgb_r) + depth_rs.append(depth_r[...,None]) + xyz_map_rs.append(extra['xyz_map']) + + rgb_rs = torch.cat(rgb_rs, dim=0).permute(0,3,1,2) * 255 + depth_rs = torch.cat(depth_rs, dim=0).permute(0,3,1,2) + xyz_map_rs = torch.cat(xyz_map_rs, dim=0).permute(0,3,1,2) #(B,3,H,W) + logging.info("render done") + + if bg_color == 'white': + fill_value = torch.tensor([255,255,255], device='cuda') + elif bg_color == 'black': + fill_value = torch.tensor([0,0,0], device='cuda') + else: + raise ValueError(f'Invalid background color: {bg_color}') + + + # crop and pad reference image + if object_level: + rgbBs_padded = crop_and_pad_rgb(rgb) + rgbBs = torch.as_tensor(rgbBs_padded, dtype=torch.float, device='cuda').permute(2,0,1)[None].expand(B,-1,-1,-1) + else: + rgbBs = kornia.geometry.transform.warp_perspective(torch.as_tensor(rgb, dtype=torch.float, device='cuda').permute(2,0,1)[None].expand(B,-1,-1,-1), tf_to_crops, dsize=render_size, mode='bilinear', align_corners=False, padding_mode='fill', fill_value=fill_value) + + # depthBs = kornia.geometry.transform.warp_perspective(torch.as_tensor(depth, dtype=torch.float, device='cuda')[None,None].expand(B,-1,-1,-1), tf_to_crops, dsize=render_size, mode='nearest', align_corners=False) + + + if object_level: + if isinstance(depth, torch.Tensor): + depthBs = torch.as_tensor(cv2.resize(depth.data.cpu().numpy(), (160, 160), interpolation=cv2.INTER_NEAREST), dtype=torch.float, device='cuda')[None,None].expand(B,-1,-1,-1) + elif isinstance(depth, np.ndarray): + depthBs = torch.as_tensor(cv2.resize(depth, (160, 160), interpolation=cv2.INTER_NEAREST), dtype=torch.float, device='cuda')[None,None].expand(B,-1,-1,-1) + else: + raise ValueError(f'Invalid rgb type: {type(rgb)}') + else: + depthBs = kornia.geometry.transform.warp_perspective(torch.as_tensor(depth, dtype=torch.float, device='cuda')[None,None].expand(B,-1,-1,-1), tf_to_crops, dsize=render_size, mode='nearest', align_corners=False) + + if rgb_rs.shape[-2:]!=cfg['input_resize']: + rgbAs = kornia.geometry.transform.warp_perspective(rgb_rs, tf_to_crops, dsize=render_size, mode='bilinear', align_corners=False, padding_mode='fill', fill_value=fill_value) + depthAs = kornia.geometry.transform.warp_perspective(depth_rs, tf_to_crops, dsize=render_size, mode='nearest', align_corners=False) + else: + rgbAs = rgb_rs + depthAs = depth_rs + + if xyz_map_rs.shape[-2:]!=cfg['input_resize']: + xyz_mapAs = kornia.geometry.transform.warp_perspective(xyz_map_rs, tf_to_crops, dsize=render_size, mode='nearest', align_corners=False) + else: + xyz_mapAs = xyz_map_rs + + normalAs = None + normalBs = None + + Ks = torch.as_tensor(K, dtype=torch.float).reshape(1,3,3).expand(len(rgbAs),3,3) + mesh_diameters = torch.ones((len(rgbAs)), dtype=torch.float, device='cuda')*mesh_diameter + + if rgb_only: + depthAs = torch.zeros_like(depthAs) + depthBs = torch.zeros_like(depthBs) + xyz_mapAs = torch.zeros_like(xyz_mapAs) + + # crop and pad rendered image + for i in range(rgbAs.shape[0]): + rgb = crop_and_pad_rgb(rgbAs[i].permute(1,2,0)) + rgbAs[i] = torch.as_tensor(rgb, dtype=torch.float, device='cuda').permute(2,0,1) + + pose_data = BatchPoseData(rgbAs=rgbAs, rgbBs=rgbBs, depthAs=depthAs, depthBs=depthBs, normalAs=normalAs, normalBs=normalBs, poseA=poseAs, xyz_mapAs=xyz_mapAs, tf_to_crops=tf_to_crops, Ks=Ks, mesh_diameters=mesh_diameters) + pose_data = dataset.transform_batch(pose_data, H_ori=H, W_ori=W, bound=1) + + logging.info("pose batch data done") + + return pose_data + + +class ScorePredictor: + def __init__(self, amp=True, ckpt_root_dir=None): + self.amp = amp + self.run_name = "2024-01-11-20-02-45" + + model_name = 'model_best.pth' + code_dir = os.path.dirname(os.path.realpath(__file__)) + ckpt_dir = f'{ckpt_root_dir}/{self.run_name}/{model_name}' + + self.cfg = OmegaConf.load(f'{ckpt_root_dir}/{self.run_name}/config.yml') + + self.cfg['ckpt_dir'] = ckpt_dir + self.cfg['enable_amp'] = True + + ########## Defaults, to be backward compatible + if 'use_normal' not in self.cfg: + self.cfg['use_normal'] = False + if 'use_BN' not in self.cfg: + self.cfg['use_BN'] = False + if 'zfar' not in self.cfg: + self.cfg['zfar'] = np.inf + if 'c_in' not in self.cfg: + self.cfg['c_in'] = 4 + if 'normalize_xyz' not in self.cfg: + self.cfg['normalize_xyz'] = False + if 'crop_ratio' not in self.cfg or self.cfg['crop_ratio'] is None: + self.cfg['crop_ratio'] = 1.2 + + logging.info(f"self.cfg: \n {OmegaConf.to_yaml(self.cfg)}") + + self.dataset = ScoreMultiPairH5Dataset(cfg=self.cfg, mode='test', h5_file=None, max_num_key=1) + self.model = ScoreNetMultiPair(cfg=self.cfg, c_in=self.cfg['c_in']).cuda() + + logging.info(f"Using pretrained model from {ckpt_dir}") + ckpt = torch.load(ckpt_dir) + if 'model' in ckpt: + ckpt = ckpt['model'] + self.model.load_state_dict(ckpt) + + self.model.cuda().eval() + logging.info("init done") + + + @torch.inference_mode() + def predict(self, rgb, depth, K, ob_in_cams, normal_map=None, get_vis=False, mesh=None, mesh_tensors=None, glctx=None, mesh_diameter=None, bg_color='white', object_level=False, rgb_only=False, crop_ratio=1.4): + ''' + @rgb: np array (H,W,3) + ''' + logging.info(f"ob_in_cams:{ob_in_cams.shape}") + ob_in_cams = torch.as_tensor(ob_in_cams, dtype=torch.float, device='cuda') + + logging.info(f'self.cfg.use_normal:{self.cfg.use_normal}') + if not self.cfg.use_normal: + normal_map = None + + logging.info("making cropped data") + + if mesh_tensors is None: + mesh_tensors = make_mesh_tensors(mesh) + + rgb = torch.as_tensor(rgb, device='cuda', dtype=torch.float) + depth = torch.as_tensor(depth, device='cuda', dtype=torch.float) + + pose_data = make_crop_data_batch(self.cfg.input_resize, ob_in_cams, mesh, rgb, depth, K, crop_ratio=crop_ratio, glctx=glctx, mesh_tensors=mesh_tensors, dataset=self.dataset, cfg=self.cfg, mesh_diameter=mesh_diameter, bg_color=bg_color, object_level=object_level, rgb_only=rgb_only) + + def find_best_among_pairs(pose_data:BatchPoseData): + logging.info(f'pose_data.rgbAs.shape[0]: {pose_data.rgbAs.shape[0]}') + ids = [] + scores = [] + bs = pose_data.rgbAs.shape[0] + for b in range(0, pose_data.rgbAs.shape[0], bs): + A = torch.cat([pose_data.rgbAs[b:b+bs].cuda(), pose_data.xyz_mapAs[b:b+bs].cuda()], dim=1).float() + B = torch.cat([pose_data.rgbBs[b:b+bs].cuda(), pose_data.xyz_mapBs[b:b+bs].cuda()], dim=1).float() + if pose_data.normalAs is not None: + A = torch.cat([A, pose_data.normalAs.cuda().float()], dim=1) + B = torch.cat([B, pose_data.normalBs.cuda().float()], dim=1) + with torch.cuda.amp.autocast(enabled=self.amp): + output = self.model(A, B, L=len(A)) + scores_cur = output["score_logit"].float().reshape(-1) + ids.append(scores_cur.argmax()+b) + scores.append(scores_cur) + ids = torch.stack(ids, dim=0).reshape(-1) + scores = torch.cat(scores, dim=0).reshape(-1) + return ids, scores + + pose_data_iter = pose_data + global_ids = torch.arange(len(ob_in_cams), device='cuda', dtype=torch.long) + scores_global = torch.zeros((len(ob_in_cams)), dtype=torch.float, device='cuda') + + while 1: + ids, scores = find_best_among_pairs(pose_data_iter) + if len(ids)==1: + scores_global[global_ids] = scores + 100 + break + global_ids = global_ids[ids] + pose_data_iter = pose_data.select_by_indices(global_ids) + + scores = scores_global + + logging.info(f'forward done') + torch.cuda.empty_cache() + + if get_vis: + logging.info("get_vis...") + canvas = [] + ids = scores.argsort(descending=True) + canvas = vis_batch_data_scores(pose_data, ids=ids, scores=scores) + return scores, canvas + + return scores, None + diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/learning/training/training_config.py b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/learning/training/training_config.py new file mode 100644 index 0000000000000000000000000000000000000000..9d689c65da3fd03e9a32b5df332fcdd70af9c67d --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/learning/training/training_config.py @@ -0,0 +1,102 @@ +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. + + +import os,sys +from dataclasses import dataclass, field +from typing import List, Optional, Tuple,Union +import numpy as np +import omegaconf +import torch + + +@dataclass +class TrainingConfig(omegaconf.dictconfig.DictConfig): + input_resize: tuple = (160, 160) + normalize_xyz:Optional[bool] = True + use_mask:Optional[bool] = False + crop_ratio:Optional[float] = None + split_objects_across_gpus: bool = True + max_num_key: Optional[int] = None + use_normal:bool = False + n_view:int = 1 + zfar:float = np.inf + c_in:int = 6 + train_num_pair:Optional[int] = None + make_pair_online:Optional[bool] = False + render_backend:Optional[str] = 'nvdiffrast' + + # Run management + run_id: Optional[str] = None + exp_name:Optional[str] = None + resume_run_id: Optional[str] = None + save_dir: Optional[str] = None + batch_size: int = 64 + epoch_size: int = 115200 + val_size: int = 1280 + n_epochs: int = 25 + save_epoch_interval: int = 100 + n_dataloader_workers: int = 20 + n_rendering_workers: int = 1 + gradient_max_norm:float = np.inf + max_step_per_epoch: Optional[int] = 25000 + + # Network + use_BN:bool = True + loss_type:Optional[str] = 'pairwise_valid' + + # Optimizer + optimizer: str = "adam" + weight_decay: float = 0.0 + clip_grad_norm: float = np.inf + lr: float = 0.0001 + warmup_step: int = -1 # -1 means disable + n_epochs_warmup: int = 1 + + # Visualization + vis_interval: Optional[int] = 1000 + + debug: Optional[bool] = None + + + +@dataclass +class TrainRefinerConfig: + # Datasets + input_resize: tuple = (160, 160) #(W,H) + crop_ratio:Optional[float] = None + max_num_key: Optional[int] = None + use_normal:bool = False + use_mask:Optional[bool] = False + normal_uint8:bool = False + normalize_xyz:Optional[bool] = True + trans_normalizer:Optional[list] = None + rot_normalizer:Optional[float] = None + c_in:int = 6 + n_view:int = 1 + zfar:float = np.inf + trans_rep:str = 'tracknet' # tracknet/deepim + rot_rep:Optional[str] = 'axis_angle' # 6d/axis_angle + save_dir: Optional[str] = None + + # Run management + run_id: Optional[str] = None + exp_name:Optional[str] = None + batch_size: int = 64 + use_BN:bool = True + optimizer: str = "adam" + weight_decay: float = 0.0 + clip_grad_norm: float = np.inf + lr: float = 0.0001 + warmup_step: int = -1 + loss_type:str = 'l2' # l1/l2/add + + vis_interval: Optional[int] = 1000 + debug: Optional[bool] = None + + diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/mycpp/CMakeLists.txt b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/mycpp/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..7c8a9a5cca867d327b7495d98c5cf13bd15fcbe7 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/mycpp/CMakeLists.txt @@ -0,0 +1,25 @@ +cmake_minimum_required(VERSION 3.15) +project(mycpp) + + +set(CMAKE_BUILD_TYPE Release) +set(CMAKE_EXPORT_COMPILE_COMMANDS ON) +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14 -fopenmp -g3 -O3") + + +find_package(Boost REQUIRED COMPONENTS system program_options) +find_package(OpenMP REQUIRED) +find_package(Eigen3 REQUIRED) +find_package(pybind11 REQUIRED) + +include_directories( + include + ${BLAS_INCLUDE_DIR} +) + +file(GLOB MY_SRC ${PROJECT_SOURCE_DIR}/src/*.cpp) + +set(PYBIND11_CPP_STANDARD -std=c++14) + +pybind11_add_module(mycpp src/app/pybind_api.cpp ${MY_SRC}) +target_link_libraries(mycpp PRIVATE ${Boost_LIBRARIES} ${OpenMP_CXX_FLAGS} Eigen3::Eigen) \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/mycpp/include/Utils.h b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/mycpp/include/Utils.h new file mode 100644 index 0000000000000000000000000000000000000000..41703f5b51039b47b2dfe863edde1b448cdff882 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/mycpp/include/Utils.h @@ -0,0 +1,46 @@ +/*Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. +*/ + + +#pragma once + +// STL +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +using vectorMatrix4f = std::vector>; + + +namespace Utils +{ +float rotationGeodesicDistance(const Eigen::Matrix3f &R1, const Eigen::Matrix3f &R2); + +} // namespace Utils diff --git a/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/mycpp/src/Utils.cpp b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/mycpp/src/Utils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c1455d54b3fab9b602b1e68c4955001d6fc221b9 --- /dev/null +++ b/OVOW/engine/oneposeviagen/Orientation/orientation_estimation/pose_refinement/mycpp/src/Utils.cpp @@ -0,0 +1,29 @@ +/* +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. +*/ + + +#include "Utils.h" + + + +namespace Utils +{ + + +// Difference angle in radian +float rotationGeodesicDistance(const Eigen::Matrix3f &R1, const Eigen::Matrix3f &R2) +{ + float cos = ((R1 * R2.transpose()).trace()-1) / 2.0; + cos = std::max(std::min(cos, 1.0f), -1.0f); + return std::acos(cos); +} + + +} // namespace Utils