backup 06_ovow_code 2026-11-08 10:30:30 (part 4)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- OVOW/engine/oneposeviagen/Amodal3R/amodal3r.egg-info/PKG-INFO +5 -0
- OVOW/engine/oneposeviagen/Amodal3R/amodal3r.egg-info/SOURCES.txt +7 -0
- OVOW/engine/oneposeviagen/Amodal3R/amodal3r.egg-info/dependency_links.txt +1 -0
- OVOW/engine/oneposeviagen/Amodal3R/amodal3r.egg-info/top_level.txt +1 -0
- OVOW/engine/oneposeviagen/Amodal3R/configs/slat.yaml +38 -0
- OVOW/engine/oneposeviagen/Amodal3R/configs/ss.yaml +38 -0
- OVOW/engine/oneposeviagen/Amodal3R/dataLoader/__init__.py +3 -0
- OVOW/engine/oneposeviagen/Amodal3R/dataLoader/amodal3r.py +121 -0
- OVOW/engine/oneposeviagen/Amodal3R/dataLoader/utils.py +248 -0
- OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/blender_script/io_scene_usdz.zip +3 -0
- OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/blender_script/render.py +528 -0
- OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/build_metadata.py +270 -0
- OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/datasets/3D-FUTURE.py +97 -0
- OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/datasets/ABO.py +96 -0
- OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/datasets/HSSD.py +103 -0
- OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/datasets/ObjaverseXL.py +92 -0
- OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/datasets/Toys4k.py +92 -0
- OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/download.py +52 -0
- OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/encode_latent.py +127 -0
- OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/encode_ss_latent.py +128 -0
- OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/extract_feature.py +179 -0
- OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/render.py +121 -0
- OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/render_cond.py +125 -0
- OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/setup.sh +1 -0
- OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/stat_latent.py +66 -0
- OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/utils.py +43 -0
- OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/voxelize.py +86 -0
- OVOW/engine/oneposeviagen/Amodal3R/dit/diffusion_slat.py +181 -0
- OVOW/engine/oneposeviagen/Amodal3R/dit/diffusion_ss.py +135 -0
- OVOW/engine/oneposeviagen/Amodal3R/dit/utils.py +881 -0
- OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/benchmark.py +45 -0
- OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/setup.py +34 -0
- OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/src/api.cu +92 -0
- OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/src/api.h +76 -0
- OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/src/ext.cpp +10 -0
- OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/src/hilbert.cu +133 -0
- OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/src/hilbert.h +35 -0
- OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/src/z_order.cu +66 -0
- OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/src/z_order.h +35 -0
- OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/vox2seq/__init__.py +50 -0
- OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/vox2seq/pytorch/__init__.py +48 -0
- OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/vox2seq/pytorch/default.py +59 -0
- OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/vox2seq/pytorch/hilbert.py +303 -0
- OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/vox2seq/pytorch/z_order.py +126 -0
- OVOW/engine/oneposeviagen/Amodal3R/inference.py +107 -0
- OVOW/engine/oneposeviagen/Amodal3R/lightning/network_slat.py +153 -0
- OVOW/engine/oneposeviagen/Amodal3R/lightning/network_ss.py +133 -0
- OVOW/engine/oneposeviagen/Amodal3R/lightning/system.py +121 -0
- OVOW/engine/oneposeviagen/Amodal3R/lightning/utils.py +129 -0
- OVOW/engine/oneposeviagen/Amodal3R/setup.py +9 -0
OVOW/engine/oneposeviagen/Amodal3R/amodal3r.egg-info/PKG-INFO
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.4
|
| 2 |
+
Name: amodal3r
|
| 3 |
+
Version: 0.1
|
| 4 |
+
License-File: LICENSE.txt
|
| 5 |
+
Dynamic: license-file
|
OVOW/engine/oneposeviagen/Amodal3R/amodal3r.egg-info/SOURCES.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
LICENSE.txt
|
| 2 |
+
README.md
|
| 3 |
+
setup.py
|
| 4 |
+
amodal3r.egg-info/PKG-INFO
|
| 5 |
+
amodal3r.egg-info/SOURCES.txt
|
| 6 |
+
amodal3r.egg-info/dependency_links.txt
|
| 7 |
+
amodal3r.egg-info/top_level.txt
|
OVOW/engine/oneposeviagen/Amodal3R/amodal3r.egg-info/dependency_links.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
|
OVOW/engine/oneposeviagen/Amodal3R/amodal3r.egg-info/top_level.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
|
OVOW/engine/oneposeviagen/Amodal3R/configs/slat.yaml
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gpu_id: [0,1,2,3]
|
| 2 |
+
|
| 3 |
+
exp_name: amodal3r/train_ss
|
| 4 |
+
|
| 5 |
+
model:
|
| 6 |
+
ckpt_path: null
|
| 7 |
+
type: slat
|
| 8 |
+
|
| 9 |
+
train_dataset:
|
| 10 |
+
dataset_name: amodal3r
|
| 11 |
+
data_root: ./dataset/abo_3dfuture_hssd
|
| 12 |
+
split: train
|
| 13 |
+
img_size: [512,512]
|
| 14 |
+
|
| 15 |
+
test_dataset:
|
| 16 |
+
dataset_name: amodal3r
|
| 17 |
+
data_root: ./dataset/abo_3dfuture_hssd
|
| 18 |
+
split: test
|
| 19 |
+
img_size: [512,512]
|
| 20 |
+
|
| 21 |
+
train:
|
| 22 |
+
batch_size: 2
|
| 23 |
+
lr: 1e-4
|
| 24 |
+
beta1: 0.9
|
| 25 |
+
beta2: 0.95
|
| 26 |
+
weight_decay: 0.1
|
| 27 |
+
warmup_iters: 1000
|
| 28 |
+
n_epoch: 12
|
| 29 |
+
limit_train_batches: 1.0
|
| 30 |
+
limit_val_batches: 1.0
|
| 31 |
+
check_val_every_n_epoch: 1
|
| 32 |
+
use_rand_views: False
|
| 33 |
+
test:
|
| 34 |
+
batch_size: 2
|
| 35 |
+
|
| 36 |
+
logger:
|
| 37 |
+
name: tensorboard
|
| 38 |
+
dir: logs/${exp_name}
|
OVOW/engine/oneposeviagen/Amodal3R/configs/ss.yaml
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gpu_id: [0,1,2,3]
|
| 2 |
+
|
| 3 |
+
exp_name: amodal3r/train_ss
|
| 4 |
+
|
| 5 |
+
model:
|
| 6 |
+
ckpt_path: null
|
| 7 |
+
type: ss
|
| 8 |
+
|
| 9 |
+
train_dataset:
|
| 10 |
+
dataset_name: amodal3r
|
| 11 |
+
data_root: ./dataset/abo_3dfuture_hssd
|
| 12 |
+
split: train
|
| 13 |
+
img_size: [512,512]
|
| 14 |
+
|
| 15 |
+
test_dataset:
|
| 16 |
+
dataset_name: amodal3r
|
| 17 |
+
data_root: ./dataset/abo_3dfuture_hssd
|
| 18 |
+
split: test
|
| 19 |
+
img_size: [512,512]
|
| 20 |
+
|
| 21 |
+
train:
|
| 22 |
+
batch_size: 8
|
| 23 |
+
lr: 1e-4
|
| 24 |
+
beta1: 0.9
|
| 25 |
+
beta2: 0.95
|
| 26 |
+
weight_decay: 0.1
|
| 27 |
+
warmup_iters: 1000
|
| 28 |
+
n_epoch: 12
|
| 29 |
+
limit_train_batches: 1.0
|
| 30 |
+
limit_val_batches: 1.0
|
| 31 |
+
check_val_every_n_epoch: 1
|
| 32 |
+
use_rand_views: False
|
| 33 |
+
test:
|
| 34 |
+
batch_size: 8
|
| 35 |
+
|
| 36 |
+
logger:
|
| 37 |
+
name: tensorboard
|
| 38 |
+
dir: logs/${exp_name}
|
OVOW/engine/oneposeviagen/Amodal3R/dataLoader/__init__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dataLoader.amodal3r import Amodal3RData
|
| 2 |
+
|
| 3 |
+
dataset_dict = {'amodal3r': Amodal3RData}
|
OVOW/engine/oneposeviagen/Amodal3R/dataLoader/amodal3r.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import os
|
| 3 |
+
import random
|
| 4 |
+
from PIL import Image
|
| 5 |
+
import torch
|
| 6 |
+
import json
|
| 7 |
+
from dataLoader.utils import generate_random_mask, fov_to_ixt
|
| 8 |
+
|
| 9 |
+
class Amodal3RData(torch.utils.data.Dataset):
|
| 10 |
+
def __init__(self, cfg):
|
| 11 |
+
super(Amodal3RData, self).__init__()
|
| 12 |
+
self.data_root = cfg.data_root
|
| 13 |
+
self.split = cfg.split
|
| 14 |
+
self.img_size = np.array(cfg.img_size)
|
| 15 |
+
self.img_downscale = self.img_size/512
|
| 16 |
+
self.category = "combined"
|
| 17 |
+
|
| 18 |
+
if self.category == "combined":
|
| 19 |
+
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}')])
|
| 20 |
+
self.split_num = len(scenes_name)
|
| 21 |
+
elif self.category == "abo":
|
| 22 |
+
with open("./dataset/ABO/abo.txt", "r") as f:
|
| 23 |
+
base_scenes = f.readlines()
|
| 24 |
+
base_scenes = [f.strip() for f in base_scenes]
|
| 25 |
+
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])
|
| 26 |
+
self.split_num = 4000
|
| 27 |
+
elif self.category == "3df":
|
| 28 |
+
with open("./dataset/3dfuture/3dfuture.txt", "r") as f:
|
| 29 |
+
base_scenes = f.readlines()
|
| 30 |
+
base_scenes = [f.strip() for f in base_scenes]
|
| 31 |
+
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])
|
| 32 |
+
self.split_num = 8000
|
| 33 |
+
elif self.category == "hssd":
|
| 34 |
+
with open("./dataset/hssd/hssd.txt", "r") as f:
|
| 35 |
+
base_scenes = f.readlines()
|
| 36 |
+
base_scenes = [f.strip() for f in base_scenes]
|
| 37 |
+
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])
|
| 38 |
+
self.split_num = 6000
|
| 39 |
+
|
| 40 |
+
self.split_num = 50
|
| 41 |
+
|
| 42 |
+
if self.split=='train':
|
| 43 |
+
self.scenes_name = scenes_name[:self.split_num]
|
| 44 |
+
else:
|
| 45 |
+
if self.category == "combined":
|
| 46 |
+
self.scenes_name = scenes_name[-100:]
|
| 47 |
+
else:
|
| 48 |
+
self.scenes_name = scenes_name[self.split_num:]
|
| 49 |
+
|
| 50 |
+
print(self.category, " ", self.split, ": ", len(self.scenes_name))
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def build_metas(self, scene):
|
| 54 |
+
json_info = json.load(open(os.path.join(self.data_root, 'renders', scene, f'transforms.json')))
|
| 55 |
+
b2c = np.array([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]])
|
| 56 |
+
scene_info = {'ixts': [], 'c2ws': [], 'w2cs':[], 'img_paths': [], 'fovx': [], 'fovy':[], "mask_paths": []}
|
| 57 |
+
positions = []
|
| 58 |
+
for idx, frame in enumerate(json_info['frames']):
|
| 59 |
+
c2w = np.array(frame['transform_matrix'])
|
| 60 |
+
c2w = c2w @ b2c
|
| 61 |
+
fov = frame["camera_angle_x"]
|
| 62 |
+
ixt = fov_to_ixt(np.array([fov, fov]), np.array([512, 512]))
|
| 63 |
+
scene_info['ixts'].append(ixt.astype(np.float32))
|
| 64 |
+
scene_info['c2ws'].append(c2w.astype(np.float32))
|
| 65 |
+
scene_info['w2cs'].append(np.linalg.inv(c2w.astype(np.float32)))
|
| 66 |
+
img_path = os.path.join(self.data_root, 'renders', scene, f'{idx:03d}.png')
|
| 67 |
+
scene_info['img_paths'].append(img_path)
|
| 68 |
+
scene_info['fovx'].append(fov)
|
| 69 |
+
scene_info['fovy'].append(fov)
|
| 70 |
+
positions.append(c2w[:3,3])
|
| 71 |
+
mask_path = os.path.join(self.data_root, 'renders_mask', scene, f'{idx:03d}.png')
|
| 72 |
+
scene_info['mask_paths'].append(mask_path)
|
| 73 |
+
|
| 74 |
+
scene_info['ss_latent_path'] = os.path.join(self.data_root, 'ss_latents/ss_enc_conv3d_16l8_fp16', scene + '.npz')
|
| 75 |
+
scene_info['slat_path'] = os.path.join(self.data_root, 'latents/dinov2_vitl14_reg_slat_enc_swin8_B_64l8_fp16', scene + '.npz')
|
| 76 |
+
|
| 77 |
+
return scene_info
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def __getitem__(self, index):
|
| 81 |
+
scene_name = self.scenes_name[index]
|
| 82 |
+
scene_info = self.build_metas(scene_name)
|
| 83 |
+
|
| 84 |
+
ss_latent = np.load(scene_info['ss_latent_path'])['mean']
|
| 85 |
+
ss_latent = torch.from_numpy(ss_latent).float()
|
| 86 |
+
|
| 87 |
+
bg_color = np.zeros(3).astype(np.float32)
|
| 88 |
+
|
| 89 |
+
num_frames = len(scene_info['img_paths'])
|
| 90 |
+
# choose a random frame
|
| 91 |
+
frame_idx = random.randint(0, num_frames-1)
|
| 92 |
+
|
| 93 |
+
cond_img, cond_img_518_masked, visibility_mask, occlusion_mask = self.read_image(scene_info, frame_idx, bg_color)
|
| 94 |
+
|
| 95 |
+
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}
|
| 96 |
+
|
| 97 |
+
return ret
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def read_image(self, scene, view_idx, bg_color):
|
| 101 |
+
img_path = scene['img_paths'][view_idx]
|
| 102 |
+
img = Image.open(img_path).convert("RGBA")
|
| 103 |
+
img_518 = img.resize((518, 518), Image.Resampling.LANCZOS)
|
| 104 |
+
|
| 105 |
+
img_518 = np.array(img_518).astype(np.float32) / 255.
|
| 106 |
+
alpha = img_518[..., -1:]
|
| 107 |
+
img_518 = (img_518[..., :3] * img_518[..., -1:] + bg_color*(1 - img_518[..., -1:])).astype(np.float32)
|
| 108 |
+
|
| 109 |
+
occlusion_mask = generate_random_mask(height=518, width=518)
|
| 110 |
+
bg_mask = (alpha<0.1)
|
| 111 |
+
visibility_mask = occlusion_mask | bg_mask
|
| 112 |
+
visibility_mask = 1 - visibility_mask
|
| 113 |
+
|
| 114 |
+
# apply the mask
|
| 115 |
+
img_518_masked = img_518 * visibility_mask
|
| 116 |
+
|
| 117 |
+
return img_518.astype(np.float32), img_518_masked.astype(np.float32), visibility_mask.squeeze().astype(np.float32), occlusion_mask.squeeze().astype(np.float32)
|
| 118 |
+
|
| 119 |
+
def __len__(self):
|
| 120 |
+
return len(self.scenes_name)
|
| 121 |
+
|
OVOW/engine/oneposeviagen/Amodal3R/dataLoader/utils.py
ADDED
|
@@ -0,0 +1,248 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch, math
|
| 2 |
+
import numpy as np
|
| 3 |
+
from sklearn.cluster import KMeans
|
| 4 |
+
import re
|
| 5 |
+
import cv2
|
| 6 |
+
|
| 7 |
+
def init_volume_grid(bound=0.45, num_pts_each_axis=32):
|
| 8 |
+
# Define the range and number of points
|
| 9 |
+
start = -bound
|
| 10 |
+
stop = bound
|
| 11 |
+
num_points = num_pts_each_axis # Adjust the number of points to your preference
|
| 12 |
+
|
| 13 |
+
# Create a linear space for each axis
|
| 14 |
+
x = np.linspace(start, stop, num_points)
|
| 15 |
+
y = np.linspace(start, stop, num_points)
|
| 16 |
+
z = np.linspace(start, stop, num_points)
|
| 17 |
+
|
| 18 |
+
# Create a 3D grid of points using meshgrid
|
| 19 |
+
X, Y, Z = np.meshgrid(x, y, z, indexing='ij')
|
| 20 |
+
|
| 21 |
+
# Stack the grid points in a single array of shape (N, 3)
|
| 22 |
+
xyz = np.vstack((X.ravel(), Y.ravel(), Z.ravel())).T
|
| 23 |
+
|
| 24 |
+
return xyz
|
| 25 |
+
|
| 26 |
+
def build_rays_torch(c2ws, ixts, H, W, scale=1.0):
|
| 27 |
+
|
| 28 |
+
H, W = int(H*scale), int(W*scale)
|
| 29 |
+
ixts[:,:2] *= scale
|
| 30 |
+
rays_o = c2ws[:,:3, 3][:,None,None]
|
| 31 |
+
X, Y = torch.meshgrid(torch.arange(W), torch.arange(H), indexing='xy')
|
| 32 |
+
XYZ = torch.cat((X[:, :, None] + 0.5, Y[:, :, None] + 0.5, torch.ones_like(X[:, :, None])), dim=-1).to(c2ws)
|
| 33 |
+
|
| 34 |
+
i2ws = torch.inverse(ixts).permute(0,2,1) @ c2ws[:,:3, :3].permute(0,2,1)
|
| 35 |
+
XYZ = torch.stack([(XYZ @ i2w) for i2w in i2ws])
|
| 36 |
+
rays_o = rays_o.repeat(1,H,1,1)
|
| 37 |
+
rays_o = rays_o.repeat(1,1,W,1)
|
| 38 |
+
rays = torch.cat((rays_o, XYZ), dim=-1)
|
| 39 |
+
return rays
|
| 40 |
+
|
| 41 |
+
def build_rays(c2ws, ixts, H, W, scale=1.0):
|
| 42 |
+
|
| 43 |
+
H, W = int(H*scale), int(W*scale)
|
| 44 |
+
ixts[:,:2] *= scale
|
| 45 |
+
|
| 46 |
+
rays_o = c2ws[:,:3, 3][:,None,None]
|
| 47 |
+
X, Y = np.meshgrid(np.arange(W), np.arange(H))
|
| 48 |
+
XYZ = np.concatenate((X[:, :, None] + 0.5, Y[:, :, None] + 0.5, np.ones_like(X[:, :, None])), axis=-1)
|
| 49 |
+
i2ws = np.linalg.inv(ixts).transpose(0,2,1) @ c2ws[:,:3, :3].transpose(0,2,1)
|
| 50 |
+
XYZ = np.stack([(XYZ @ i2w) for i2w in i2ws])
|
| 51 |
+
rays_o = rays_o.repeat(H, axis=1)
|
| 52 |
+
rays_o = rays_o.repeat(W, axis=2)
|
| 53 |
+
rays = np.concatenate((rays_o, XYZ), axis=-1)
|
| 54 |
+
return rays.astype(np.float32)
|
| 55 |
+
|
| 56 |
+
def build_rays_ortho(c2ws, H, W, scale=1.0):
|
| 57 |
+
|
| 58 |
+
c2ws_rot = c2ws[:,:3,:3]
|
| 59 |
+
c2ws_t = c2ws[:,:3,3].reshape(-1,1,3)
|
| 60 |
+
|
| 61 |
+
rays_d = torch.zeros(1,1,3).to(c2ws)
|
| 62 |
+
rays_d[...,-1] = 1.0
|
| 63 |
+
rays_d = rays_d @ c2ws_rot.transpose(1,2)
|
| 64 |
+
rays_d = rays_d[:,None].expand(-1,H,W,-1)
|
| 65 |
+
|
| 66 |
+
X, Y = np.meshgrid(np.arange(W), np.arange(H))
|
| 67 |
+
X = torch.from_numpy(X[:, :, None] + 0.5).float()/W * 2 - 1.0
|
| 68 |
+
Y = torch.from_numpy(Y[:, :, None] + 0.5).float()/H * 2 - 1.0
|
| 69 |
+
XYZ = torch.cat((X*scale, Y*scale, torch.zeros_like(X)), dim=-1).to(c2ws)
|
| 70 |
+
XYZ = XYZ.view(1,-1,3)
|
| 71 |
+
rays_o = XYZ @ c2ws_rot.transpose(1,2) + c2ws_t
|
| 72 |
+
rays = torch.cat((rays_o.view(rays_d.shape), rays_d), dim=-1)
|
| 73 |
+
return rays
|
| 74 |
+
|
| 75 |
+
def KMean(xyz, n_clusters):
|
| 76 |
+
kmeans = KMeans(n_clusters = n_clusters, n_init=10, random_state=20211202)
|
| 77 |
+
kmeans.fit(xyz)
|
| 78 |
+
labels = kmeans.labels_
|
| 79 |
+
|
| 80 |
+
clusters = []
|
| 81 |
+
for i in range(n_clusters):
|
| 82 |
+
idx = np.where(labels==i)[0]
|
| 83 |
+
clusters.append(idx.astype(np.uint8))
|
| 84 |
+
|
| 85 |
+
return clusters
|
| 86 |
+
|
| 87 |
+
def fov_to_ixt(fov, reso):
|
| 88 |
+
ixt = np.eye(3, dtype=np.float32)
|
| 89 |
+
ixt[0][2], ixt[1][2] = reso[0]/2, reso[1]/2
|
| 90 |
+
focal = .5 * reso / np.tan(.5 * fov)
|
| 91 |
+
ixt[[0,1],[0,1]] = focal
|
| 92 |
+
return ixt
|
| 93 |
+
|
| 94 |
+
def intrinsic_to_fov(K, w=None, h=None):
|
| 95 |
+
# Extract the focal lengths from the intrinsic matrix
|
| 96 |
+
fx = K[0, 0]
|
| 97 |
+
fy = K[1, 1]
|
| 98 |
+
|
| 99 |
+
w = K[0, 2]*2 if w is None else w
|
| 100 |
+
h = K[1, 2]*2 if h is None else h
|
| 101 |
+
|
| 102 |
+
# Calculating field of view
|
| 103 |
+
fov_x = 2 * np.arctan2(w, 2 * fx)
|
| 104 |
+
fov_y = 2 * np.arctan2(h, 2 * fy)
|
| 105 |
+
|
| 106 |
+
return fov_x, fov_y
|
| 107 |
+
|
| 108 |
+
def fov2focal(fov, pixels):
|
| 109 |
+
return pixels / (2 * math.tan(fov / 2))
|
| 110 |
+
|
| 111 |
+
def focal2fov(focal, pixels):
|
| 112 |
+
return 2*math.atan(pixels/(2*focal))
|
| 113 |
+
|
| 114 |
+
def pose_sub_selete(poses, N_poses):
|
| 115 |
+
# to select N_poses poses that close to the equatorial
|
| 116 |
+
# Define the camera's local up-vector and the world's up-vector
|
| 117 |
+
camera_up_vector = np.array([0, 1, 0])
|
| 118 |
+
world_up_vector = np.array([1, 0, 0])
|
| 119 |
+
|
| 120 |
+
# Extract the rotation matrices from the transformation matrices
|
| 121 |
+
rotations = poses[:, :3, :3] # Shape: [num_poses, 3, 3]
|
| 122 |
+
|
| 123 |
+
# Transform the camera's up-vector to world coordinates for all poses
|
| 124 |
+
camera_up_world = np.einsum('ijk,k->ij', rotations, camera_up_vector) # Shape: [num_poses, 3]
|
| 125 |
+
|
| 126 |
+
# Normalize the transformed up-vectors
|
| 127 |
+
camera_up_world_norm = camera_up_world / np.linalg.norm(camera_up_world, axis=1)[:, np.newaxis]
|
| 128 |
+
|
| 129 |
+
# Calculate the dot product with the world up-vector to find cosines of angles
|
| 130 |
+
cos_angles = np.dot(camera_up_world_norm, world_up_vector)
|
| 131 |
+
|
| 132 |
+
# Calculate angles in radians using arccos
|
| 133 |
+
angles = np.arccos(np.clip(cos_angles, -1.0, 1.0))
|
| 134 |
+
|
| 135 |
+
# Select the poses with the smallest angles (closest to the equatorial plane)
|
| 136 |
+
indices = np.argsort(angles)[:N_poses]
|
| 137 |
+
|
| 138 |
+
return indices
|
| 139 |
+
|
| 140 |
+
def read_pfm(filename):
|
| 141 |
+
file = open(filename, 'rb')
|
| 142 |
+
color = None
|
| 143 |
+
width = None
|
| 144 |
+
height = None
|
| 145 |
+
scale = None
|
| 146 |
+
endian = None
|
| 147 |
+
|
| 148 |
+
header = file.readline().decode('utf-8').rstrip()
|
| 149 |
+
if header == 'PF':
|
| 150 |
+
color = True
|
| 151 |
+
elif header == 'Pf':
|
| 152 |
+
color = False
|
| 153 |
+
else:
|
| 154 |
+
raise Exception('Not a PFM file.')
|
| 155 |
+
|
| 156 |
+
dim_match = re.match(r'^(\d+)\s(\d+)\s$', file.readline().decode('utf-8'))
|
| 157 |
+
if dim_match:
|
| 158 |
+
width, height = map(int, dim_match.groups())
|
| 159 |
+
else:
|
| 160 |
+
raise Exception('Malformed PFM header.')
|
| 161 |
+
|
| 162 |
+
scale = float(file.readline().rstrip())
|
| 163 |
+
if scale < 0: # little-endian
|
| 164 |
+
endian = '<'
|
| 165 |
+
scale = -scale
|
| 166 |
+
else:
|
| 167 |
+
endian = '>' # big-endian
|
| 168 |
+
|
| 169 |
+
data = np.fromfile(file, endian + 'f')
|
| 170 |
+
shape = (height, width, 3) if color else (height, width)
|
| 171 |
+
|
| 172 |
+
data = np.reshape(data, shape)
|
| 173 |
+
data = np.flipud(data)
|
| 174 |
+
file.close()
|
| 175 |
+
return data, scale
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def generate_mae_mask(image_shape=(3,512,512), patch_size=16, mask_ratio=0.3):
|
| 180 |
+
_, height, width = image_shape
|
| 181 |
+
|
| 182 |
+
num_patches_h = height // patch_size
|
| 183 |
+
num_patches_w = width // patch_size
|
| 184 |
+
total_patches = num_patches_h * num_patches_w
|
| 185 |
+
|
| 186 |
+
num_masked_patches = int(total_patches * mask_ratio)
|
| 187 |
+
|
| 188 |
+
mask = np.ones(total_patches, dtype=np.float32)
|
| 189 |
+
mask[:num_masked_patches] = 0
|
| 190 |
+
|
| 191 |
+
np.random.shuffle(mask)
|
| 192 |
+
|
| 193 |
+
mask = mask.reshape(num_patches_h, num_patches_w)
|
| 194 |
+
|
| 195 |
+
mask = np.repeat(np.repeat(mask, patch_size, axis=0), patch_size, axis=1)
|
| 196 |
+
|
| 197 |
+
return mask
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def generate_random_mask(width=512, height=512):
|
| 201 |
+
"""Generates a stable mask with a fewer number of coherent blocks."""
|
| 202 |
+
|
| 203 |
+
img = np.zeros((width, height, 3), np.uint8)
|
| 204 |
+
|
| 205 |
+
# Set size scale
|
| 206 |
+
size = int((width + height) * 0.03)
|
| 207 |
+
if width < 64 or height < 64:
|
| 208 |
+
raise Exception("Width and Height of mask must be at least 64!")
|
| 209 |
+
|
| 210 |
+
# Draw random lines (reduced count)
|
| 211 |
+
for _ in range(np.random.randint(1, 3)):
|
| 212 |
+
x1, x2 = np.random.randint(1, width), np.random.randint(1, width)
|
| 213 |
+
y1, y2 = np.random.randint(1, height), np.random.randint(1, height)
|
| 214 |
+
thickness = np.random.randint(3, size)
|
| 215 |
+
cv2.line(img, (x1, y1), (x2, y2), (1, 1, 1), thickness)
|
| 216 |
+
|
| 217 |
+
# Draw random circles (reduced count)
|
| 218 |
+
for _ in range(np.random.randint(1, 3)):
|
| 219 |
+
x1, y1 = np.random.randint(1, width), np.random.randint(1, height)
|
| 220 |
+
radius = np.random.randint(3, size)
|
| 221 |
+
cv2.circle(img, (x1, y1), radius, (1, 1, 1), -1)
|
| 222 |
+
|
| 223 |
+
# Draw random ellipses (reduced count)
|
| 224 |
+
for _ in range(np.random.randint(1, 3)):
|
| 225 |
+
x1, y1 = np.random.randint(1, width), np.random.randint(1, height)
|
| 226 |
+
s1, s2 = np.random.randint(3, size), np.random.randint(3, size)
|
| 227 |
+
a1, a2 = np.random.randint(0, 180), np.random.randint(0, 360)
|
| 228 |
+
thickness = np.random.randint(3, size)
|
| 229 |
+
cv2.ellipse(img, (x1, y1), (s1, s2), a1, 0, a2, (1, 1, 1), thickness)
|
| 230 |
+
|
| 231 |
+
# Add coherent block masks (reduced number of blocks)
|
| 232 |
+
num_blocks = np.random.randint(3, 7)
|
| 233 |
+
block_size_range = (25, 75) # Larger block sizes for stability
|
| 234 |
+
for _ in range(num_blocks):
|
| 235 |
+
block_height = np.random.randint(*block_size_range)
|
| 236 |
+
block_width = np.random.randint(*block_size_range)
|
| 237 |
+
|
| 238 |
+
start_x = np.random.randint(0, max(0, width - block_width))
|
| 239 |
+
start_y = np.random.randint(0, max(0, height - block_height))
|
| 240 |
+
|
| 241 |
+
img[start_y:start_y + block_height, start_x:start_x + block_width] = (1, 1, 1)
|
| 242 |
+
|
| 243 |
+
# Dilate the block for smoother edges
|
| 244 |
+
kernel_size = np.random.randint(5, 9) # Slightly larger kernel for stability
|
| 245 |
+
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (kernel_size, kernel_size))
|
| 246 |
+
img = cv2.dilate(img, kernel, iterations=1)
|
| 247 |
+
|
| 248 |
+
return img[:, :, 0:1]
|
OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/blender_script/io_scene_usdz.zip
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ec07ab6125fe0a021ed08c64169eceda126330401aba3d494d5203d26ac4b093
|
| 3 |
+
size 34685
|
OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/blender_script/render.py
ADDED
|
@@ -0,0 +1,528 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse, sys, os, math, re, glob
|
| 2 |
+
from typing import *
|
| 3 |
+
import bpy
|
| 4 |
+
from mathutils import Vector, Matrix
|
| 5 |
+
import numpy as np
|
| 6 |
+
import json
|
| 7 |
+
import glob
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
"""=============== BLENDER ==============="""
|
| 11 |
+
|
| 12 |
+
IMPORT_FUNCTIONS: Dict[str, Callable] = {
|
| 13 |
+
"obj": bpy.ops.import_scene.obj,
|
| 14 |
+
"glb": bpy.ops.import_scene.gltf,
|
| 15 |
+
"gltf": bpy.ops.import_scene.gltf,
|
| 16 |
+
"usd": bpy.ops.import_scene.usd,
|
| 17 |
+
"fbx": bpy.ops.import_scene.fbx,
|
| 18 |
+
"stl": bpy.ops.import_mesh.stl,
|
| 19 |
+
"usda": bpy.ops.import_scene.usda,
|
| 20 |
+
"dae": bpy.ops.wm.collada_import,
|
| 21 |
+
"ply": bpy.ops.import_mesh.ply,
|
| 22 |
+
"abc": bpy.ops.wm.alembic_import,
|
| 23 |
+
"blend": bpy.ops.wm.append,
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
EXT = {
|
| 27 |
+
'PNG': 'png',
|
| 28 |
+
'JPEG': 'jpg',
|
| 29 |
+
'OPEN_EXR': 'exr',
|
| 30 |
+
'TIFF': 'tiff',
|
| 31 |
+
'BMP': 'bmp',
|
| 32 |
+
'HDR': 'hdr',
|
| 33 |
+
'TARGA': 'tga'
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
def init_render(engine='CYCLES', resolution=512, geo_mode=False):
|
| 37 |
+
bpy.context.scene.render.engine = engine
|
| 38 |
+
bpy.context.scene.render.resolution_x = resolution
|
| 39 |
+
bpy.context.scene.render.resolution_y = resolution
|
| 40 |
+
bpy.context.scene.render.resolution_percentage = 100
|
| 41 |
+
bpy.context.scene.render.image_settings.file_format = 'PNG'
|
| 42 |
+
bpy.context.scene.render.image_settings.color_mode = 'RGBA'
|
| 43 |
+
bpy.context.scene.render.film_transparent = True
|
| 44 |
+
|
| 45 |
+
bpy.context.scene.cycles.device = 'GPU'
|
| 46 |
+
bpy.context.scene.cycles.samples = 128 if not geo_mode else 1
|
| 47 |
+
bpy.context.scene.cycles.filter_type = 'BOX'
|
| 48 |
+
bpy.context.scene.cycles.filter_width = 1
|
| 49 |
+
bpy.context.scene.cycles.diffuse_bounces = 1
|
| 50 |
+
bpy.context.scene.cycles.glossy_bounces = 1
|
| 51 |
+
bpy.context.scene.cycles.transparent_max_bounces = 3 if not geo_mode else 0
|
| 52 |
+
bpy.context.scene.cycles.transmission_bounces = 3 if not geo_mode else 1
|
| 53 |
+
bpy.context.scene.cycles.use_denoising = True
|
| 54 |
+
|
| 55 |
+
bpy.context.preferences.addons['cycles'].preferences.get_devices()
|
| 56 |
+
bpy.context.preferences.addons['cycles'].preferences.compute_device_type = 'CUDA'
|
| 57 |
+
|
| 58 |
+
def init_nodes(save_depth=False, save_normal=False, save_albedo=False, save_mist=False):
|
| 59 |
+
if not any([save_depth, save_normal, save_albedo, save_mist]):
|
| 60 |
+
return {}, {}
|
| 61 |
+
outputs = {}
|
| 62 |
+
spec_nodes = {}
|
| 63 |
+
|
| 64 |
+
bpy.context.scene.use_nodes = True
|
| 65 |
+
bpy.context.scene.view_layers['View Layer'].use_pass_z = save_depth
|
| 66 |
+
bpy.context.scene.view_layers['View Layer'].use_pass_normal = save_normal
|
| 67 |
+
bpy.context.scene.view_layers['View Layer'].use_pass_diffuse_color = save_albedo
|
| 68 |
+
bpy.context.scene.view_layers['View Layer'].use_pass_mist = save_mist
|
| 69 |
+
|
| 70 |
+
nodes = bpy.context.scene.node_tree.nodes
|
| 71 |
+
links = bpy.context.scene.node_tree.links
|
| 72 |
+
for n in nodes:
|
| 73 |
+
nodes.remove(n)
|
| 74 |
+
|
| 75 |
+
render_layers = nodes.new('CompositorNodeRLayers')
|
| 76 |
+
|
| 77 |
+
if save_depth:
|
| 78 |
+
depth_file_output = nodes.new('CompositorNodeOutputFile')
|
| 79 |
+
depth_file_output.base_path = ''
|
| 80 |
+
depth_file_output.file_slots[0].use_node_format = True
|
| 81 |
+
depth_file_output.format.file_format = 'PNG'
|
| 82 |
+
depth_file_output.format.color_depth = '16'
|
| 83 |
+
depth_file_output.format.color_mode = 'BW'
|
| 84 |
+
# Remap to 0-1
|
| 85 |
+
map = nodes.new(type="CompositorNodeMapRange")
|
| 86 |
+
map.inputs[1].default_value = 0 # (min value you will be getting)
|
| 87 |
+
map.inputs[2].default_value = 10 # (max value you will be getting)
|
| 88 |
+
map.inputs[3].default_value = 0 # (min value you will map to)
|
| 89 |
+
map.inputs[4].default_value = 1 # (max value you will map to)
|
| 90 |
+
|
| 91 |
+
links.new(render_layers.outputs['Depth'], map.inputs[0])
|
| 92 |
+
links.new(map.outputs[0], depth_file_output.inputs[0])
|
| 93 |
+
|
| 94 |
+
outputs['depth'] = depth_file_output
|
| 95 |
+
spec_nodes['depth_map'] = map
|
| 96 |
+
|
| 97 |
+
if save_normal:
|
| 98 |
+
normal_file_output = nodes.new('CompositorNodeOutputFile')
|
| 99 |
+
normal_file_output.base_path = ''
|
| 100 |
+
normal_file_output.file_slots[0].use_node_format = True
|
| 101 |
+
normal_file_output.format.file_format = 'OPEN_EXR'
|
| 102 |
+
normal_file_output.format.color_mode = 'RGB'
|
| 103 |
+
normal_file_output.format.color_depth = '16'
|
| 104 |
+
|
| 105 |
+
links.new(render_layers.outputs['Normal'], normal_file_output.inputs[0])
|
| 106 |
+
|
| 107 |
+
outputs['normal'] = normal_file_output
|
| 108 |
+
|
| 109 |
+
if save_albedo:
|
| 110 |
+
albedo_file_output = nodes.new('CompositorNodeOutputFile')
|
| 111 |
+
albedo_file_output.base_path = ''
|
| 112 |
+
albedo_file_output.file_slots[0].use_node_format = True
|
| 113 |
+
albedo_file_output.format.file_format = 'PNG'
|
| 114 |
+
albedo_file_output.format.color_mode = 'RGBA'
|
| 115 |
+
albedo_file_output.format.color_depth = '8'
|
| 116 |
+
|
| 117 |
+
alpha_albedo = nodes.new('CompositorNodeSetAlpha')
|
| 118 |
+
|
| 119 |
+
links.new(render_layers.outputs['DiffCol'], alpha_albedo.inputs['Image'])
|
| 120 |
+
links.new(render_layers.outputs['Alpha'], alpha_albedo.inputs['Alpha'])
|
| 121 |
+
links.new(alpha_albedo.outputs['Image'], albedo_file_output.inputs[0])
|
| 122 |
+
|
| 123 |
+
outputs['albedo'] = albedo_file_output
|
| 124 |
+
|
| 125 |
+
if save_mist:
|
| 126 |
+
bpy.data.worlds['World'].mist_settings.start = 0
|
| 127 |
+
bpy.data.worlds['World'].mist_settings.depth = 10
|
| 128 |
+
|
| 129 |
+
mist_file_output = nodes.new('CompositorNodeOutputFile')
|
| 130 |
+
mist_file_output.base_path = ''
|
| 131 |
+
mist_file_output.file_slots[0].use_node_format = True
|
| 132 |
+
mist_file_output.format.file_format = 'PNG'
|
| 133 |
+
mist_file_output.format.color_mode = 'BW'
|
| 134 |
+
mist_file_output.format.color_depth = '16'
|
| 135 |
+
|
| 136 |
+
links.new(render_layers.outputs['Mist'], mist_file_output.inputs[0])
|
| 137 |
+
|
| 138 |
+
outputs['mist'] = mist_file_output
|
| 139 |
+
|
| 140 |
+
return outputs, spec_nodes
|
| 141 |
+
|
| 142 |
+
def init_scene() -> None:
|
| 143 |
+
"""Resets the scene to a clean state.
|
| 144 |
+
|
| 145 |
+
Returns:
|
| 146 |
+
None
|
| 147 |
+
"""
|
| 148 |
+
# delete everything
|
| 149 |
+
for obj in bpy.data.objects:
|
| 150 |
+
bpy.data.objects.remove(obj, do_unlink=True)
|
| 151 |
+
|
| 152 |
+
# delete all the materials
|
| 153 |
+
for material in bpy.data.materials:
|
| 154 |
+
bpy.data.materials.remove(material, do_unlink=True)
|
| 155 |
+
|
| 156 |
+
# delete all the textures
|
| 157 |
+
for texture in bpy.data.textures:
|
| 158 |
+
bpy.data.textures.remove(texture, do_unlink=True)
|
| 159 |
+
|
| 160 |
+
# delete all the images
|
| 161 |
+
for image in bpy.data.images:
|
| 162 |
+
bpy.data.images.remove(image, do_unlink=True)
|
| 163 |
+
|
| 164 |
+
def init_camera():
|
| 165 |
+
cam = bpy.data.objects.new('Camera', bpy.data.cameras.new('Camera'))
|
| 166 |
+
bpy.context.collection.objects.link(cam)
|
| 167 |
+
bpy.context.scene.camera = cam
|
| 168 |
+
cam.data.sensor_height = cam.data.sensor_width = 32
|
| 169 |
+
cam_constraint = cam.constraints.new(type='TRACK_TO')
|
| 170 |
+
cam_constraint.track_axis = 'TRACK_NEGATIVE_Z'
|
| 171 |
+
cam_constraint.up_axis = 'UP_Y'
|
| 172 |
+
cam_empty = bpy.data.objects.new("Empty", None)
|
| 173 |
+
cam_empty.location = (0, 0, 0)
|
| 174 |
+
bpy.context.scene.collection.objects.link(cam_empty)
|
| 175 |
+
cam_constraint.target = cam_empty
|
| 176 |
+
return cam
|
| 177 |
+
|
| 178 |
+
def init_lighting():
|
| 179 |
+
# Clear existing lights
|
| 180 |
+
bpy.ops.object.select_all(action="DESELECT")
|
| 181 |
+
bpy.ops.object.select_by_type(type="LIGHT")
|
| 182 |
+
bpy.ops.object.delete()
|
| 183 |
+
|
| 184 |
+
# Create key light
|
| 185 |
+
default_light = bpy.data.objects.new("Default_Light", bpy.data.lights.new("Default_Light", type="POINT"))
|
| 186 |
+
bpy.context.collection.objects.link(default_light)
|
| 187 |
+
default_light.data.energy = 1000
|
| 188 |
+
default_light.location = (4, 1, 6)
|
| 189 |
+
default_light.rotation_euler = (0, 0, 0)
|
| 190 |
+
|
| 191 |
+
# create top light
|
| 192 |
+
top_light = bpy.data.objects.new("Top_Light", bpy.data.lights.new("Top_Light", type="AREA"))
|
| 193 |
+
bpy.context.collection.objects.link(top_light)
|
| 194 |
+
top_light.data.energy = 10000
|
| 195 |
+
top_light.location = (0, 0, 10)
|
| 196 |
+
top_light.scale = (100, 100, 100)
|
| 197 |
+
|
| 198 |
+
# create bottom light
|
| 199 |
+
bottom_light = bpy.data.objects.new("Bottom_Light", bpy.data.lights.new("Bottom_Light", type="AREA"))
|
| 200 |
+
bpy.context.collection.objects.link(bottom_light)
|
| 201 |
+
bottom_light.data.energy = 1000
|
| 202 |
+
bottom_light.location = (0, 0, -10)
|
| 203 |
+
bottom_light.rotation_euler = (0, 0, 0)
|
| 204 |
+
|
| 205 |
+
return {
|
| 206 |
+
"default_light": default_light,
|
| 207 |
+
"top_light": top_light,
|
| 208 |
+
"bottom_light": bottom_light
|
| 209 |
+
}
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def load_object(object_path: str) -> None:
|
| 213 |
+
"""Loads a model with a supported file extension into the scene.
|
| 214 |
+
|
| 215 |
+
Args:
|
| 216 |
+
object_path (str): Path to the model file.
|
| 217 |
+
|
| 218 |
+
Raises:
|
| 219 |
+
ValueError: If the file extension is not supported.
|
| 220 |
+
|
| 221 |
+
Returns:
|
| 222 |
+
None
|
| 223 |
+
"""
|
| 224 |
+
file_extension = object_path.split(".")[-1].lower()
|
| 225 |
+
if file_extension is None:
|
| 226 |
+
raise ValueError(f"Unsupported file type: {object_path}")
|
| 227 |
+
|
| 228 |
+
if file_extension == "usdz":
|
| 229 |
+
# install usdz io package
|
| 230 |
+
dirname = os.path.dirname(os.path.realpath(__file__))
|
| 231 |
+
usdz_package = os.path.join(dirname, "io_scene_usdz.zip")
|
| 232 |
+
bpy.ops.preferences.addon_install(filepath=usdz_package)
|
| 233 |
+
# enable it
|
| 234 |
+
addon_name = "io_scene_usdz"
|
| 235 |
+
bpy.ops.preferences.addon_enable(module=addon_name)
|
| 236 |
+
# import the usdz
|
| 237 |
+
from io_scene_usdz.import_usdz import import_usdz
|
| 238 |
+
|
| 239 |
+
import_usdz(context, filepath=object_path, materials=True, animations=True)
|
| 240 |
+
return None
|
| 241 |
+
|
| 242 |
+
# load from existing import functions
|
| 243 |
+
import_function = IMPORT_FUNCTIONS[file_extension]
|
| 244 |
+
|
| 245 |
+
print(f"Loading object from {object_path}")
|
| 246 |
+
if file_extension == "blend":
|
| 247 |
+
import_function(directory=object_path, link=False)
|
| 248 |
+
elif file_extension in {"glb", "gltf"}:
|
| 249 |
+
import_function(filepath=object_path, merge_vertices=True, import_shading='NORMALS')
|
| 250 |
+
else:
|
| 251 |
+
import_function(filepath=object_path)
|
| 252 |
+
|
| 253 |
+
def delete_invisible_objects() -> None:
|
| 254 |
+
"""Deletes all invisible objects in the scene.
|
| 255 |
+
|
| 256 |
+
Returns:
|
| 257 |
+
None
|
| 258 |
+
"""
|
| 259 |
+
# bpy.ops.object.mode_set(mode="OBJECT")
|
| 260 |
+
bpy.ops.object.select_all(action="DESELECT")
|
| 261 |
+
for obj in bpy.context.scene.objects:
|
| 262 |
+
if obj.hide_viewport or obj.hide_render:
|
| 263 |
+
obj.hide_viewport = False
|
| 264 |
+
obj.hide_render = False
|
| 265 |
+
obj.hide_select = False
|
| 266 |
+
obj.select_set(True)
|
| 267 |
+
bpy.ops.object.delete()
|
| 268 |
+
|
| 269 |
+
# Delete invisible collections
|
| 270 |
+
invisible_collections = [col for col in bpy.data.collections if col.hide_viewport]
|
| 271 |
+
for col in invisible_collections:
|
| 272 |
+
bpy.data.collections.remove(col)
|
| 273 |
+
|
| 274 |
+
def split_mesh_normal():
|
| 275 |
+
bpy.ops.object.select_all(action="DESELECT")
|
| 276 |
+
objs = [obj for obj in bpy.context.scene.objects if obj.type == "MESH"]
|
| 277 |
+
bpy.context.view_layer.objects.active = objs[0]
|
| 278 |
+
for obj in objs:
|
| 279 |
+
obj.select_set(True)
|
| 280 |
+
bpy.ops.object.mode_set(mode="EDIT")
|
| 281 |
+
bpy.ops.mesh.select_all(action='SELECT')
|
| 282 |
+
bpy.ops.mesh.split_normals()
|
| 283 |
+
bpy.ops.object.mode_set(mode='OBJECT')
|
| 284 |
+
bpy.ops.object.select_all(action="DESELECT")
|
| 285 |
+
|
| 286 |
+
def delete_custom_normals():
|
| 287 |
+
for this_obj in bpy.data.objects:
|
| 288 |
+
if this_obj.type == "MESH":
|
| 289 |
+
bpy.context.view_layer.objects.active = this_obj
|
| 290 |
+
bpy.ops.mesh.customdata_custom_splitnormals_clear()
|
| 291 |
+
|
| 292 |
+
def override_material():
|
| 293 |
+
new_mat = bpy.data.materials.new(name="Override0123456789")
|
| 294 |
+
new_mat.use_nodes = True
|
| 295 |
+
new_mat.node_tree.nodes.clear()
|
| 296 |
+
bsdf = new_mat.node_tree.nodes.new('ShaderNodeBsdfDiffuse')
|
| 297 |
+
bsdf.inputs[0].default_value = (0.5, 0.5, 0.5, 1)
|
| 298 |
+
bsdf.inputs[1].default_value = 1
|
| 299 |
+
output = new_mat.node_tree.nodes.new('ShaderNodeOutputMaterial')
|
| 300 |
+
new_mat.node_tree.links.new(bsdf.outputs['BSDF'], output.inputs['Surface'])
|
| 301 |
+
bpy.context.scene.view_layers['View Layer'].material_override = new_mat
|
| 302 |
+
|
| 303 |
+
def unhide_all_objects() -> None:
|
| 304 |
+
"""Unhides all objects in the scene.
|
| 305 |
+
|
| 306 |
+
Returns:
|
| 307 |
+
None
|
| 308 |
+
"""
|
| 309 |
+
for obj in bpy.context.scene.objects:
|
| 310 |
+
obj.hide_set(False)
|
| 311 |
+
|
| 312 |
+
def convert_to_meshes() -> None:
|
| 313 |
+
"""Converts all objects in the scene to meshes.
|
| 314 |
+
|
| 315 |
+
Returns:
|
| 316 |
+
None
|
| 317 |
+
"""
|
| 318 |
+
bpy.ops.object.select_all(action="DESELECT")
|
| 319 |
+
bpy.context.view_layer.objects.active = [obj for obj in bpy.context.scene.objects if obj.type == "MESH"][0]
|
| 320 |
+
for obj in bpy.context.scene.objects:
|
| 321 |
+
obj.select_set(True)
|
| 322 |
+
bpy.ops.object.convert(target="MESH")
|
| 323 |
+
|
| 324 |
+
def triangulate_meshes() -> None:
|
| 325 |
+
"""Triangulates all meshes in the scene.
|
| 326 |
+
|
| 327 |
+
Returns:
|
| 328 |
+
None
|
| 329 |
+
"""
|
| 330 |
+
bpy.ops.object.select_all(action="DESELECT")
|
| 331 |
+
objs = [obj for obj in bpy.context.scene.objects if obj.type == "MESH"]
|
| 332 |
+
bpy.context.view_layer.objects.active = objs[0]
|
| 333 |
+
for obj in objs:
|
| 334 |
+
obj.select_set(True)
|
| 335 |
+
bpy.ops.object.mode_set(mode="EDIT")
|
| 336 |
+
bpy.ops.mesh.reveal()
|
| 337 |
+
bpy.ops.mesh.select_all(action="SELECT")
|
| 338 |
+
bpy.ops.mesh.quads_convert_to_tris(quad_method="BEAUTY", ngon_method="BEAUTY")
|
| 339 |
+
bpy.ops.object.mode_set(mode="OBJECT")
|
| 340 |
+
bpy.ops.object.select_all(action="DESELECT")
|
| 341 |
+
|
| 342 |
+
def scene_bbox() -> Tuple[Vector, Vector]:
|
| 343 |
+
"""Returns the bounding box of the scene.
|
| 344 |
+
|
| 345 |
+
Taken from Shap-E rendering script
|
| 346 |
+
(https://github.com/openai/shap-e/blob/main/shap_e/rendering/blender/blender_script.py#L68-L82)
|
| 347 |
+
|
| 348 |
+
Returns:
|
| 349 |
+
Tuple[Vector, Vector]: The minimum and maximum coordinates of the bounding box.
|
| 350 |
+
"""
|
| 351 |
+
bbox_min = (math.inf,) * 3
|
| 352 |
+
bbox_max = (-math.inf,) * 3
|
| 353 |
+
found = False
|
| 354 |
+
scene_meshes = [obj for obj in bpy.context.scene.objects.values() if isinstance(obj.data, bpy.types.Mesh)]
|
| 355 |
+
for obj in scene_meshes:
|
| 356 |
+
found = True
|
| 357 |
+
for coord in obj.bound_box:
|
| 358 |
+
coord = Vector(coord)
|
| 359 |
+
coord = obj.matrix_world @ coord
|
| 360 |
+
bbox_min = tuple(min(x, y) for x, y in zip(bbox_min, coord))
|
| 361 |
+
bbox_max = tuple(max(x, y) for x, y in zip(bbox_max, coord))
|
| 362 |
+
if not found:
|
| 363 |
+
raise RuntimeError("no objects in scene to compute bounding box for")
|
| 364 |
+
return Vector(bbox_min), Vector(bbox_max)
|
| 365 |
+
|
| 366 |
+
def normalize_scene() -> Tuple[float, Vector]:
|
| 367 |
+
"""Normalizes the scene by scaling and translating it to fit in a unit cube centered
|
| 368 |
+
at the origin.
|
| 369 |
+
|
| 370 |
+
Mostly taken from the Point-E / Shap-E rendering script
|
| 371 |
+
(https://github.com/openai/point-e/blob/main/point_e/evals/scripts/blender_script.py#L97-L112),
|
| 372 |
+
but fix for multiple root objects: (see bug report here:
|
| 373 |
+
https://github.com/openai/shap-e/pull/60).
|
| 374 |
+
|
| 375 |
+
Returns:
|
| 376 |
+
Tuple[float, Vector]: The scale factor and the offset applied to the scene.
|
| 377 |
+
"""
|
| 378 |
+
scene_root_objects = [obj for obj in bpy.context.scene.objects.values() if not obj.parent]
|
| 379 |
+
if len(scene_root_objects) > 1:
|
| 380 |
+
# create an empty object to be used as a parent for all root objects
|
| 381 |
+
scene = bpy.data.objects.new("ParentEmpty", None)
|
| 382 |
+
bpy.context.scene.collection.objects.link(scene)
|
| 383 |
+
|
| 384 |
+
# parent all root objects to the empty object
|
| 385 |
+
for obj in scene_root_objects:
|
| 386 |
+
obj.parent = scene
|
| 387 |
+
else:
|
| 388 |
+
scene = scene_root_objects[0]
|
| 389 |
+
|
| 390 |
+
bbox_min, bbox_max = scene_bbox()
|
| 391 |
+
scale = 1 / max(bbox_max - bbox_min)
|
| 392 |
+
scene.scale = scene.scale * scale
|
| 393 |
+
|
| 394 |
+
# Apply scale to matrix_world.
|
| 395 |
+
bpy.context.view_layer.update()
|
| 396 |
+
bbox_min, bbox_max = scene_bbox()
|
| 397 |
+
offset = -(bbox_min + bbox_max) / 2
|
| 398 |
+
scene.matrix_world.translation += offset
|
| 399 |
+
bpy.ops.object.select_all(action="DESELECT")
|
| 400 |
+
|
| 401 |
+
return scale, offset
|
| 402 |
+
|
| 403 |
+
def get_transform_matrix(obj: bpy.types.Object) -> list:
|
| 404 |
+
pos, rt, _ = obj.matrix_world.decompose()
|
| 405 |
+
rt = rt.to_matrix()
|
| 406 |
+
matrix = []
|
| 407 |
+
for ii in range(3):
|
| 408 |
+
a = []
|
| 409 |
+
for jj in range(3):
|
| 410 |
+
a.append(rt[ii][jj])
|
| 411 |
+
a.append(pos[ii])
|
| 412 |
+
matrix.append(a)
|
| 413 |
+
matrix.append([0, 0, 0, 1])
|
| 414 |
+
return matrix
|
| 415 |
+
|
| 416 |
+
def main(arg):
|
| 417 |
+
os.makedirs(arg.output_folder, exist_ok=True)
|
| 418 |
+
|
| 419 |
+
# Initialize context
|
| 420 |
+
init_render(engine=arg.engine, resolution=arg.resolution, geo_mode=arg.geo_mode)
|
| 421 |
+
outputs, spec_nodes = init_nodes(
|
| 422 |
+
save_depth=arg.save_depth,
|
| 423 |
+
save_normal=arg.save_normal,
|
| 424 |
+
save_albedo=arg.save_albedo,
|
| 425 |
+
save_mist=arg.save_mist
|
| 426 |
+
)
|
| 427 |
+
if arg.object.endswith(".blend"):
|
| 428 |
+
delete_invisible_objects()
|
| 429 |
+
else:
|
| 430 |
+
init_scene()
|
| 431 |
+
load_object(arg.object)
|
| 432 |
+
if arg.split_normal:
|
| 433 |
+
split_mesh_normal()
|
| 434 |
+
# delete_custom_normals()
|
| 435 |
+
print('[INFO] Scene initialized.')
|
| 436 |
+
|
| 437 |
+
# normalize scene
|
| 438 |
+
scale, offset = normalize_scene()
|
| 439 |
+
print('[INFO] Scene normalized.')
|
| 440 |
+
|
| 441 |
+
# Initialize camera and lighting
|
| 442 |
+
cam = init_camera()
|
| 443 |
+
init_lighting()
|
| 444 |
+
print('[INFO] Camera and lighting initialized.')
|
| 445 |
+
|
| 446 |
+
# Override material
|
| 447 |
+
if arg.geo_mode:
|
| 448 |
+
override_material()
|
| 449 |
+
|
| 450 |
+
# Create a list of views
|
| 451 |
+
to_export = {
|
| 452 |
+
"aabb": [[-0.5, -0.5, -0.5], [0.5, 0.5, 0.5]],
|
| 453 |
+
"scale": scale,
|
| 454 |
+
"offset": [offset.x, offset.y, offset.z],
|
| 455 |
+
"frames": []
|
| 456 |
+
}
|
| 457 |
+
views = json.loads(arg.views)
|
| 458 |
+
for i, view in enumerate(views):
|
| 459 |
+
cam.location = (
|
| 460 |
+
view['radius'] * np.cos(view['yaw']) * np.cos(view['pitch']),
|
| 461 |
+
view['radius'] * np.sin(view['yaw']) * np.cos(view['pitch']),
|
| 462 |
+
view['radius'] * np.sin(view['pitch'])
|
| 463 |
+
)
|
| 464 |
+
cam.data.lens = 16 / np.tan(view['fov'] / 2)
|
| 465 |
+
|
| 466 |
+
if arg.save_depth:
|
| 467 |
+
spec_nodes['depth_map'].inputs[1].default_value = view['radius'] - 0.5 * np.sqrt(3)
|
| 468 |
+
spec_nodes['depth_map'].inputs[2].default_value = view['radius'] + 0.5 * np.sqrt(3)
|
| 469 |
+
|
| 470 |
+
bpy.context.scene.render.filepath = os.path.join(arg.output_folder, f'{i:03d}.png')
|
| 471 |
+
for name, output in outputs.items():
|
| 472 |
+
output.file_slots[0].path = os.path.join(arg.output_folder, f'{i:03d}_{name}')
|
| 473 |
+
|
| 474 |
+
# Render the scene
|
| 475 |
+
bpy.ops.render.render(write_still=True)
|
| 476 |
+
bpy.context.view_layer.update()
|
| 477 |
+
for name, output in outputs.items():
|
| 478 |
+
ext = EXT[output.format.file_format]
|
| 479 |
+
path = glob.glob(f'{output.file_slots[0].path}*.{ext}')[0]
|
| 480 |
+
os.rename(path, f'{output.file_slots[0].path}.{ext}')
|
| 481 |
+
|
| 482 |
+
# Save camera parameters
|
| 483 |
+
metadata = {
|
| 484 |
+
"file_path": f'{i:03d}.png',
|
| 485 |
+
"camera_angle_x": view['fov'],
|
| 486 |
+
"transform_matrix": get_transform_matrix(cam)
|
| 487 |
+
}
|
| 488 |
+
if arg.save_depth:
|
| 489 |
+
metadata['depth'] = {
|
| 490 |
+
'min': view['radius'] - 0.5 * np.sqrt(3),
|
| 491 |
+
'max': view['radius'] + 0.5 * np.sqrt(3)
|
| 492 |
+
}
|
| 493 |
+
to_export["frames"].append(metadata)
|
| 494 |
+
|
| 495 |
+
# Save the camera parameters
|
| 496 |
+
with open(os.path.join(arg.output_folder, 'transforms.json'), 'w') as f:
|
| 497 |
+
json.dump(to_export, f, indent=4)
|
| 498 |
+
|
| 499 |
+
if arg.save_mesh:
|
| 500 |
+
# triangulate meshes
|
| 501 |
+
unhide_all_objects()
|
| 502 |
+
convert_to_meshes()
|
| 503 |
+
triangulate_meshes()
|
| 504 |
+
print('[INFO] Meshes triangulated.')
|
| 505 |
+
|
| 506 |
+
# export ply mesh
|
| 507 |
+
bpy.ops.export_mesh.ply(filepath=os.path.join(arg.output_folder, 'mesh.ply'))
|
| 508 |
+
|
| 509 |
+
|
| 510 |
+
if __name__ == '__main__':
|
| 511 |
+
parser = argparse.ArgumentParser(description='Renders given obj file by rotation a camera around it.')
|
| 512 |
+
parser.add_argument('--views', type=str, help='JSON string of views. Contains a list of {yaw, pitch, radius, fov} object.')
|
| 513 |
+
parser.add_argument('--object', type=str, help='Path to the 3D model file to be rendered.')
|
| 514 |
+
parser.add_argument('--output_folder', type=str, default='/tmp', help='The path the output will be dumped to.')
|
| 515 |
+
parser.add_argument('--resolution', type=int, default=512, help='Resolution of the images.')
|
| 516 |
+
parser.add_argument('--engine', type=str, default='CYCLES', help='Blender internal engine for rendering. E.g. CYCLES, BLENDER_EEVEE, ...')
|
| 517 |
+
parser.add_argument('--geo_mode', action='store_true', help='Geometry mode for rendering.')
|
| 518 |
+
parser.add_argument('--save_depth', action='store_true', help='Save the depth maps.')
|
| 519 |
+
parser.add_argument('--save_normal', action='store_true', help='Save the normal maps.')
|
| 520 |
+
parser.add_argument('--save_albedo', action='store_true', help='Save the albedo maps.')
|
| 521 |
+
parser.add_argument('--save_mist', action='store_true', help='Save the mist distance maps.')
|
| 522 |
+
parser.add_argument('--split_normal', action='store_true', help='Split the normals of the mesh.')
|
| 523 |
+
parser.add_argument('--save_mesh', action='store_true', help='Save the mesh as a .ply file.')
|
| 524 |
+
argv = sys.argv[sys.argv.index("--") + 1:]
|
| 525 |
+
args = parser.parse_args(argv)
|
| 526 |
+
|
| 527 |
+
main(args)
|
| 528 |
+
|
OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/build_metadata.py
ADDED
|
@@ -0,0 +1,270 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import shutil
|
| 3 |
+
import sys
|
| 4 |
+
import time
|
| 5 |
+
import importlib
|
| 6 |
+
import argparse
|
| 7 |
+
import numpy as np
|
| 8 |
+
import pandas as pd
|
| 9 |
+
from tqdm import tqdm
|
| 10 |
+
from easydict import EasyDict as edict
|
| 11 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 12 |
+
import utils3d
|
| 13 |
+
|
| 14 |
+
def get_first_directory(path):
|
| 15 |
+
with os.scandir(path) as it:
|
| 16 |
+
for entry in it:
|
| 17 |
+
if entry.is_dir():
|
| 18 |
+
return entry.name
|
| 19 |
+
return None
|
| 20 |
+
|
| 21 |
+
def need_process(key):
|
| 22 |
+
return key in opt.field or opt.field == ['all']
|
| 23 |
+
|
| 24 |
+
if __name__ == '__main__':
|
| 25 |
+
dataset_utils = importlib.import_module(f'datasets.{sys.argv[1]}')
|
| 26 |
+
|
| 27 |
+
parser = argparse.ArgumentParser()
|
| 28 |
+
parser.add_argument('--output_dir', type=str, required=True,
|
| 29 |
+
help='Directory to save the metadata')
|
| 30 |
+
parser.add_argument('--field', type=str, default='all',
|
| 31 |
+
help='Fields to process, separated by commas')
|
| 32 |
+
parser.add_argument('--from_file', action='store_true',
|
| 33 |
+
help='Build metadata from file instead of from records of processings.' +
|
| 34 |
+
'Useful when some processing fail to generate records but file already exists.')
|
| 35 |
+
dataset_utils.add_args(parser)
|
| 36 |
+
opt = parser.parse_args(sys.argv[2:])
|
| 37 |
+
opt = edict(vars(opt))
|
| 38 |
+
|
| 39 |
+
os.makedirs(opt.output_dir, exist_ok=True)
|
| 40 |
+
os.makedirs(os.path.join(opt.output_dir, 'merged_records'), exist_ok=True)
|
| 41 |
+
|
| 42 |
+
opt.field = opt.field.split(',')
|
| 43 |
+
|
| 44 |
+
timestamp = str(int(time.time()))
|
| 45 |
+
|
| 46 |
+
# get file list
|
| 47 |
+
if os.path.exists(os.path.join(opt.output_dir, 'metadata.csv')):
|
| 48 |
+
print('Loading previous metadata...')
|
| 49 |
+
metadata = pd.read_csv(os.path.join(opt.output_dir, 'metadata.csv'))
|
| 50 |
+
else:
|
| 51 |
+
metadata = dataset_utils.get_metadata(**opt)
|
| 52 |
+
metadata.set_index('sha256', inplace=True)
|
| 53 |
+
|
| 54 |
+
# merge downloaded
|
| 55 |
+
df_files = [f for f in os.listdir(opt.output_dir) if f.startswith('downloaded_') and f.endswith('.csv')]
|
| 56 |
+
df_parts = []
|
| 57 |
+
for f in df_files:
|
| 58 |
+
try:
|
| 59 |
+
df_parts.append(pd.read_csv(os.path.join(opt.output_dir, f)))
|
| 60 |
+
except:
|
| 61 |
+
pass
|
| 62 |
+
if len(df_parts) > 0:
|
| 63 |
+
df = pd.concat(df_parts)
|
| 64 |
+
df.set_index('sha256', inplace=True)
|
| 65 |
+
if 'local_path' in metadata.columns:
|
| 66 |
+
metadata.update(df, overwrite=True)
|
| 67 |
+
else:
|
| 68 |
+
metadata = metadata.join(df, on='sha256', how='left')
|
| 69 |
+
for f in df_files:
|
| 70 |
+
shutil.move(os.path.join(opt.output_dir, f), os.path.join(opt.output_dir, 'merged_records', f'{timestamp}_{f}'))
|
| 71 |
+
|
| 72 |
+
# detect models
|
| 73 |
+
image_models = []
|
| 74 |
+
if os.path.exists(os.path.join(opt.output_dir, 'features')):
|
| 75 |
+
image_models = os.listdir(os.path.join(opt.output_dir, 'features'))
|
| 76 |
+
latent_models = []
|
| 77 |
+
if os.path.exists(os.path.join(opt.output_dir, 'latents')):
|
| 78 |
+
latent_models = os.listdir(os.path.join(opt.output_dir, 'latents'))
|
| 79 |
+
ss_latent_models = []
|
| 80 |
+
if os.path.exists(os.path.join(opt.output_dir, 'ss_latents')):
|
| 81 |
+
ss_latent_models = os.listdir(os.path.join(opt.output_dir, 'ss_latents'))
|
| 82 |
+
print(f'Image models: {image_models}')
|
| 83 |
+
print(f'Latent models: {latent_models}')
|
| 84 |
+
print(f'Sparse Structure latent models: {ss_latent_models}')
|
| 85 |
+
|
| 86 |
+
if 'rendered' not in metadata.columns:
|
| 87 |
+
metadata['rendered'] = [False] * len(metadata)
|
| 88 |
+
if 'voxelized' not in metadata.columns:
|
| 89 |
+
metadata['voxelized'] = [False] * len(metadata)
|
| 90 |
+
if 'num_voxels' not in metadata.columns:
|
| 91 |
+
metadata['num_voxels'] = [0] * len(metadata)
|
| 92 |
+
if 'cond_rendered' not in metadata.columns:
|
| 93 |
+
metadata['cond_rendered'] = [False] * len(metadata)
|
| 94 |
+
for model in image_models:
|
| 95 |
+
if f'feature_{model}' not in metadata.columns:
|
| 96 |
+
metadata[f'feature_{model}'] = [False] * len(metadata)
|
| 97 |
+
for model in latent_models:
|
| 98 |
+
if f'latent_{model}' not in metadata.columns:
|
| 99 |
+
metadata[f'latent_{model}'] = [False] * len(metadata)
|
| 100 |
+
for model in ss_latent_models:
|
| 101 |
+
if f'ss_latent_{model}' not in metadata.columns:
|
| 102 |
+
metadata[f'ss_latent_{model}'] = [False] * len(metadata)
|
| 103 |
+
|
| 104 |
+
# merge rendered
|
| 105 |
+
df_files = [f for f in os.listdir(opt.output_dir) if f.startswith('rendered_') and f.endswith('.csv')]
|
| 106 |
+
df_parts = []
|
| 107 |
+
for f in df_files:
|
| 108 |
+
try:
|
| 109 |
+
df_parts.append(pd.read_csv(os.path.join(opt.output_dir, f)))
|
| 110 |
+
except:
|
| 111 |
+
pass
|
| 112 |
+
if len(df_parts) > 0:
|
| 113 |
+
df = pd.concat(df_parts)
|
| 114 |
+
df.set_index('sha256', inplace=True)
|
| 115 |
+
metadata.update(df, overwrite=True)
|
| 116 |
+
for f in df_files:
|
| 117 |
+
shutil.move(os.path.join(opt.output_dir, f), os.path.join(opt.output_dir, 'merged_records', f'{timestamp}_{f}'))
|
| 118 |
+
|
| 119 |
+
# merge voxelized
|
| 120 |
+
df_files = [f for f in os.listdir(opt.output_dir) if f.startswith('voxelized_') and f.endswith('.csv')]
|
| 121 |
+
df_parts = []
|
| 122 |
+
for f in df_files:
|
| 123 |
+
try:
|
| 124 |
+
df_parts.append(pd.read_csv(os.path.join(opt.output_dir, f)))
|
| 125 |
+
except:
|
| 126 |
+
pass
|
| 127 |
+
if len(df_parts) > 0:
|
| 128 |
+
df = pd.concat(df_parts)
|
| 129 |
+
df.set_index('sha256', inplace=True)
|
| 130 |
+
metadata.update(df, overwrite=True)
|
| 131 |
+
for f in df_files:
|
| 132 |
+
shutil.move(os.path.join(opt.output_dir, f), os.path.join(opt.output_dir, 'merged_records', f'{timestamp}_{f}'))
|
| 133 |
+
|
| 134 |
+
# merge cond_rendered
|
| 135 |
+
df_files = [f for f in os.listdir(opt.output_dir) if f.startswith('cond_rendered_') and f.endswith('.csv')]
|
| 136 |
+
df_parts = []
|
| 137 |
+
for f in df_files:
|
| 138 |
+
try:
|
| 139 |
+
df_parts.append(pd.read_csv(os.path.join(opt.output_dir, f)))
|
| 140 |
+
except:
|
| 141 |
+
pass
|
| 142 |
+
if len(df_parts) > 0:
|
| 143 |
+
df = pd.concat(df_parts)
|
| 144 |
+
df.set_index('sha256', inplace=True)
|
| 145 |
+
metadata.update(df, overwrite=True)
|
| 146 |
+
for f in df_files:
|
| 147 |
+
shutil.move(os.path.join(opt.output_dir, f), os.path.join(opt.output_dir, 'merged_records', f'{timestamp}_{f}'))
|
| 148 |
+
|
| 149 |
+
# merge features
|
| 150 |
+
for model in image_models:
|
| 151 |
+
df_files = [f for f in os.listdir(opt.output_dir) if f.startswith(f'feature_{model}_') and f.endswith('.csv')]
|
| 152 |
+
df_parts = []
|
| 153 |
+
for f in df_files:
|
| 154 |
+
try:
|
| 155 |
+
df_parts.append(pd.read_csv(os.path.join(opt.output_dir, f)))
|
| 156 |
+
except:
|
| 157 |
+
pass
|
| 158 |
+
if len(df_parts) > 0:
|
| 159 |
+
df = pd.concat(df_parts)
|
| 160 |
+
df.set_index('sha256', inplace=True)
|
| 161 |
+
metadata.update(df, overwrite=True)
|
| 162 |
+
for f in df_files:
|
| 163 |
+
shutil.move(os.path.join(opt.output_dir, f), os.path.join(opt.output_dir, 'merged_records', f'{timestamp}_{f}'))
|
| 164 |
+
|
| 165 |
+
# merge latents
|
| 166 |
+
for model in latent_models:
|
| 167 |
+
df_files = [f for f in os.listdir(opt.output_dir) if f.startswith(f'latent_{model}_') and f.endswith('.csv')]
|
| 168 |
+
df_parts = []
|
| 169 |
+
for f in df_files:
|
| 170 |
+
try:
|
| 171 |
+
df_parts.append(pd.read_csv(os.path.join(opt.output_dir, f)))
|
| 172 |
+
except:
|
| 173 |
+
pass
|
| 174 |
+
if len(df_parts) > 0:
|
| 175 |
+
df = pd.concat(df_parts)
|
| 176 |
+
df.set_index('sha256', inplace=True)
|
| 177 |
+
metadata.update(df, overwrite=True)
|
| 178 |
+
for f in df_files:
|
| 179 |
+
shutil.move(os.path.join(opt.output_dir, f), os.path.join(opt.output_dir, 'merged_records', f'{timestamp}_{f}'))
|
| 180 |
+
|
| 181 |
+
# merge sparse structure latents
|
| 182 |
+
for model in ss_latent_models:
|
| 183 |
+
df_files = [f for f in os.listdir(opt.output_dir) if f.startswith(f'ss_latent_{model}_') and f.endswith('.csv')]
|
| 184 |
+
df_parts = []
|
| 185 |
+
for f in df_files:
|
| 186 |
+
try:
|
| 187 |
+
df_parts.append(pd.read_csv(os.path.join(opt.output_dir, f)))
|
| 188 |
+
except:
|
| 189 |
+
pass
|
| 190 |
+
if len(df_parts) > 0:
|
| 191 |
+
df = pd.concat(df_parts)
|
| 192 |
+
df.set_index('sha256', inplace=True)
|
| 193 |
+
metadata.update(df, overwrite=True)
|
| 194 |
+
for f in df_files:
|
| 195 |
+
shutil.move(os.path.join(opt.output_dir, f), os.path.join(opt.output_dir, 'merged_records', f'{timestamp}_{f}'))
|
| 196 |
+
|
| 197 |
+
# build metadata from files
|
| 198 |
+
if opt.from_file:
|
| 199 |
+
with ThreadPoolExecutor(max_workers=os.cpu_count()) as executor, \
|
| 200 |
+
tqdm(total=len(metadata), desc="Building metadata") as pbar:
|
| 201 |
+
def worker(sha256):
|
| 202 |
+
try:
|
| 203 |
+
if need_process('rendered') and metadata.loc[sha256, 'rendered'] == False and \
|
| 204 |
+
os.path.exists(os.path.join(opt.output_dir, 'renders', sha256, 'transforms.json')):
|
| 205 |
+
metadata.loc[sha256, 'rendered'] = True
|
| 206 |
+
if need_process('voxelized') and metadata.loc[sha256, 'rendered'] == True and metadata.loc[sha256, 'voxelized'] == False and \
|
| 207 |
+
os.path.exists(os.path.join(opt.output_dir, 'voxels', f'{sha256}.ply')):
|
| 208 |
+
try:
|
| 209 |
+
pts = utils3d.io.read_ply(os.path.join(opt.output_dir, 'voxels', f'{sha256}.ply'))[0]
|
| 210 |
+
metadata.loc[sha256, 'voxelized'] = True
|
| 211 |
+
metadata.loc[sha256, 'num_voxels'] = len(pts)
|
| 212 |
+
except Exception as e:
|
| 213 |
+
pass
|
| 214 |
+
if need_process('cond_rendered') and metadata.loc[sha256, 'cond_rendered'] == False and \
|
| 215 |
+
os.path.exists(os.path.join(opt.output_dir, 'renders_cond', sha256, 'transforms.json')):
|
| 216 |
+
metadata.loc[sha256, 'cond_rendered'] = True
|
| 217 |
+
for model in image_models:
|
| 218 |
+
if need_process(f'feature_{model}') and \
|
| 219 |
+
metadata.loc[sha256, f'feature_{model}'] == False and \
|
| 220 |
+
metadata.loc[sha256, 'rendered'] == True and \
|
| 221 |
+
metadata.loc[sha256, 'voxelized'] == True and \
|
| 222 |
+
os.path.exists(os.path.join(opt.output_dir, 'features', model, f'{sha256}.npz')):
|
| 223 |
+
metadata.loc[sha256, f'feature_{model}'] = True
|
| 224 |
+
for model in latent_models:
|
| 225 |
+
if need_process(f'latent_{model}') and \
|
| 226 |
+
metadata.loc[sha256, f'latent_{model}'] == False and \
|
| 227 |
+
metadata.loc[sha256, 'rendered'] == True and \
|
| 228 |
+
metadata.loc[sha256, 'voxelized'] == True and \
|
| 229 |
+
os.path.exists(os.path.join(opt.output_dir, 'latents', model, f'{sha256}.npz')):
|
| 230 |
+
metadata.loc[sha256, f'latent_{model}'] = True
|
| 231 |
+
for model in ss_latent_models:
|
| 232 |
+
if need_process(f'ss_latent_{model}') and \
|
| 233 |
+
metadata.loc[sha256, f'ss_latent_{model}'] == False and \
|
| 234 |
+
metadata.loc[sha256, 'voxelized'] == True and \
|
| 235 |
+
os.path.exists(os.path.join(opt.output_dir, 'ss_latents', model, f'{sha256}.npz')):
|
| 236 |
+
metadata.loc[sha256, f'ss_latent_{model}'] = True
|
| 237 |
+
pbar.update()
|
| 238 |
+
except Exception as e:
|
| 239 |
+
print(f'Error processing {sha256}: {e}')
|
| 240 |
+
pbar.update()
|
| 241 |
+
|
| 242 |
+
executor.map(worker, metadata.index)
|
| 243 |
+
executor.shutdown(wait=True)
|
| 244 |
+
|
| 245 |
+
# statistics
|
| 246 |
+
metadata.to_csv(os.path.join(opt.output_dir, 'metadata.csv'))
|
| 247 |
+
num_downloaded = metadata['local_path'].count() if 'local_path' in metadata.columns else 0
|
| 248 |
+
with open(os.path.join(opt.output_dir, 'statistics.txt'), 'w') as f:
|
| 249 |
+
f.write('Statistics:\n')
|
| 250 |
+
f.write(f' - Number of assets: {len(metadata)}\n')
|
| 251 |
+
f.write(f' - Number of assets downloaded: {num_downloaded}\n')
|
| 252 |
+
f.write(f' - Number of assets rendered: {metadata["rendered"].sum()}\n')
|
| 253 |
+
f.write(f' - Number of assets voxelized: {metadata["voxelized"].sum()}\n')
|
| 254 |
+
if len(image_models) != 0:
|
| 255 |
+
f.write(f' - Number of assets with image features extracted:\n')
|
| 256 |
+
for model in image_models:
|
| 257 |
+
f.write(f' - {model}: {metadata[f"feature_{model}"].sum()}\n')
|
| 258 |
+
if len(latent_models) != 0:
|
| 259 |
+
f.write(f' - Number of assets with latents extracted:\n')
|
| 260 |
+
for model in latent_models:
|
| 261 |
+
f.write(f' - {model}: {metadata[f"latent_{model}"].sum()}\n')
|
| 262 |
+
if len(ss_latent_models) != 0:
|
| 263 |
+
f.write(f' - Number of assets with sparse structure latents extracted:\n')
|
| 264 |
+
for model in ss_latent_models:
|
| 265 |
+
f.write(f' - {model}: {metadata[f"ss_latent_{model}"].sum()}\n')
|
| 266 |
+
f.write(f' - Number of assets with captions: {metadata["captions"].count()}\n')
|
| 267 |
+
f.write(f' - Number of assets with image conditions: {metadata["cond_rendered"].sum()}\n')
|
| 268 |
+
|
| 269 |
+
with open(os.path.join(opt.output_dir, 'statistics.txt'), 'r') as f:
|
| 270 |
+
print(f.read())
|
OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/datasets/3D-FUTURE.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import re
|
| 3 |
+
import argparse
|
| 4 |
+
import zipfile
|
| 5 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 6 |
+
from tqdm import tqdm
|
| 7 |
+
import pandas as pd
|
| 8 |
+
from utils import get_file_hash
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def add_args(parser: argparse.ArgumentParser):
|
| 12 |
+
pass
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def get_metadata(**kwargs):
|
| 16 |
+
metadata = pd.read_csv("hf://datasets/JeffreyXiang/TRELLIS-500K/3D-FUTURE.csv")
|
| 17 |
+
return metadata
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def download(metadata, output_dir, **kwargs):
|
| 21 |
+
os.makedirs(output_dir, exist_ok=True)
|
| 22 |
+
|
| 23 |
+
if not os.path.exists(os.path.join(output_dir, 'raw', '3D-FUTURE-model.zip')):
|
| 24 |
+
print("\033[93m")
|
| 25 |
+
print("3D-FUTURE have to be downloaded manually")
|
| 26 |
+
print(f"Please download the 3D-FUTURE-model.zip file and place it in the {output_dir}/raw directory")
|
| 27 |
+
print("Visit https://tianchi.aliyun.com/specials/promotion/alibaba-3d-future for more information")
|
| 28 |
+
print("\033[0m")
|
| 29 |
+
raise FileNotFoundError("3D-FUTURE-model.zip not found")
|
| 30 |
+
|
| 31 |
+
downloaded = {}
|
| 32 |
+
metadata = metadata.set_index("file_identifier")
|
| 33 |
+
with zipfile.ZipFile(os.path.join(output_dir, 'raw', '3D-FUTURE-model.zip')) as zip_ref:
|
| 34 |
+
all_names = zip_ref.namelist()
|
| 35 |
+
instances = [instance[:-1] for instance in all_names if re.match(r"^3D-FUTURE-model/[^/]+/$", instance)]
|
| 36 |
+
instances = list(filter(lambda x: x in metadata.index, instances))
|
| 37 |
+
|
| 38 |
+
with ThreadPoolExecutor(max_workers=os.cpu_count()) as executor, \
|
| 39 |
+
tqdm(total=len(instances), desc="Extracting") as pbar:
|
| 40 |
+
def worker(instance: str) -> str:
|
| 41 |
+
try:
|
| 42 |
+
instance_files = list(filter(lambda x: x.startswith(f"{instance}/") and not x.endswith("/"), all_names))
|
| 43 |
+
zip_ref.extractall(os.path.join(output_dir, 'raw'), members=instance_files)
|
| 44 |
+
sha256 = get_file_hash(os.path.join(output_dir, 'raw', f"{instance}/image.jpg"))
|
| 45 |
+
pbar.update()
|
| 46 |
+
return sha256
|
| 47 |
+
except Exception as e:
|
| 48 |
+
pbar.update()
|
| 49 |
+
print(f"Error extracting for {instance}: {e}")
|
| 50 |
+
return None
|
| 51 |
+
|
| 52 |
+
sha256s = executor.map(worker, instances)
|
| 53 |
+
executor.shutdown(wait=True)
|
| 54 |
+
|
| 55 |
+
for k, sha256 in zip(instances, sha256s):
|
| 56 |
+
if sha256 is not None:
|
| 57 |
+
if sha256 == metadata.loc[k, "sha256"]:
|
| 58 |
+
downloaded[sha256] = os.path.join("raw", f"{k}/raw_model.obj")
|
| 59 |
+
else:
|
| 60 |
+
print(f"Error downloading {k}: sha256s do not match")
|
| 61 |
+
|
| 62 |
+
return pd.DataFrame(downloaded.items(), columns=['sha256', 'local_path'])
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def foreach_instance(metadata, output_dir, func, max_workers=None, desc='Processing objects') -> pd.DataFrame:
|
| 66 |
+
import os
|
| 67 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 68 |
+
from tqdm import tqdm
|
| 69 |
+
|
| 70 |
+
# load metadata
|
| 71 |
+
metadata = metadata.to_dict('records')
|
| 72 |
+
|
| 73 |
+
# processing objects
|
| 74 |
+
records = []
|
| 75 |
+
max_workers = max_workers or os.cpu_count()
|
| 76 |
+
try:
|
| 77 |
+
with ThreadPoolExecutor(max_workers=max_workers) as executor, \
|
| 78 |
+
tqdm(total=len(metadata), desc=desc) as pbar:
|
| 79 |
+
def worker(metadatum):
|
| 80 |
+
try:
|
| 81 |
+
local_path = metadatum['local_path']
|
| 82 |
+
sha256 = metadatum['sha256']
|
| 83 |
+
file = os.path.join(output_dir, local_path)
|
| 84 |
+
record = func(file, sha256)
|
| 85 |
+
if record is not None:
|
| 86 |
+
records.append(record)
|
| 87 |
+
pbar.update()
|
| 88 |
+
except Exception as e:
|
| 89 |
+
print(f"Error processing object {sha256}: {e}")
|
| 90 |
+
pbar.update()
|
| 91 |
+
|
| 92 |
+
executor.map(worker, metadata)
|
| 93 |
+
executor.shutdown(wait=True)
|
| 94 |
+
except:
|
| 95 |
+
print("Error happened during processing.")
|
| 96 |
+
|
| 97 |
+
return pd.DataFrame.from_records(records)
|
OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/datasets/ABO.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import re
|
| 3 |
+
import argparse
|
| 4 |
+
import tarfile
|
| 5 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 6 |
+
from tqdm import tqdm
|
| 7 |
+
import pandas as pd
|
| 8 |
+
from utils import get_file_hash
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def add_args(parser: argparse.ArgumentParser):
|
| 12 |
+
pass
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def get_metadata(**kwargs):
|
| 16 |
+
metadata = pd.read_csv("hf://datasets/JeffreyXiang/TRELLIS-500K/ABO.csv")
|
| 17 |
+
return metadata
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def download(metadata, output_dir, **kwargs):
|
| 21 |
+
os.makedirs(os.path.join(output_dir, 'raw'), exist_ok=True)
|
| 22 |
+
|
| 23 |
+
if not os.path.exists(os.path.join(output_dir, 'raw', 'abo-3dmodels.tar')):
|
| 24 |
+
try:
|
| 25 |
+
os.makedirs(os.path.join(output_dir, 'raw'), exist_ok=True)
|
| 26 |
+
os.system(f"wget -O {output_dir}/raw/abo-3dmodels.tar https://amazon-berkeley-objects.s3.amazonaws.com/archives/abo-3dmodels.tar")
|
| 27 |
+
except:
|
| 28 |
+
print("\033[93m")
|
| 29 |
+
print("Error downloading ABO dataset. Please check your internet connection and try again.")
|
| 30 |
+
print("Or, you can manually download the abo-3dmodels.tar file and place it in the {output_dir}/raw directory")
|
| 31 |
+
print("Visit https://amazon-berkeley-objects.s3.amazonaws.com/index.html for more information")
|
| 32 |
+
print("\033[0m")
|
| 33 |
+
raise FileNotFoundError("Error downloading ABO dataset")
|
| 34 |
+
|
| 35 |
+
downloaded = {}
|
| 36 |
+
metadata = metadata.set_index("file_identifier")
|
| 37 |
+
with tarfile.open(os.path.join(output_dir, 'raw', 'abo-3dmodels.tar')) as tar:
|
| 38 |
+
with ThreadPoolExecutor(max_workers=1) as executor, \
|
| 39 |
+
tqdm(total=len(metadata), desc="Extracting") as pbar:
|
| 40 |
+
def worker(instance: str) -> str:
|
| 41 |
+
try:
|
| 42 |
+
tar.extract(f"3dmodels/original/{instance}", path=os.path.join(output_dir, 'raw'))
|
| 43 |
+
sha256 = get_file_hash(os.path.join(output_dir, 'raw/3dmodels/original', instance))
|
| 44 |
+
pbar.update()
|
| 45 |
+
return sha256
|
| 46 |
+
except Exception as e:
|
| 47 |
+
pbar.update()
|
| 48 |
+
print(f"Error extracting for {instance}: {e}")
|
| 49 |
+
return None
|
| 50 |
+
|
| 51 |
+
sha256s = executor.map(worker, metadata.index)
|
| 52 |
+
executor.shutdown(wait=True)
|
| 53 |
+
|
| 54 |
+
for k, sha256 in zip(metadata.index, sha256s):
|
| 55 |
+
if sha256 is not None:
|
| 56 |
+
if sha256 == metadata.loc[k, "sha256"]:
|
| 57 |
+
downloaded[sha256] = os.path.join('raw/3dmodels/original', k)
|
| 58 |
+
else:
|
| 59 |
+
print(f"Error downloading {k}: sha256s do not match")
|
| 60 |
+
|
| 61 |
+
return pd.DataFrame(downloaded.items(), columns=['sha256', 'local_path'])
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def foreach_instance(metadata, output_dir, func, max_workers=None, desc='Processing objects') -> pd.DataFrame:
|
| 65 |
+
import os
|
| 66 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 67 |
+
from tqdm import tqdm
|
| 68 |
+
|
| 69 |
+
# load metadata
|
| 70 |
+
metadata = metadata.to_dict('records')
|
| 71 |
+
|
| 72 |
+
# processing objects
|
| 73 |
+
records = []
|
| 74 |
+
max_workers = max_workers or os.cpu_count()
|
| 75 |
+
try:
|
| 76 |
+
with ThreadPoolExecutor(max_workers=max_workers) as executor, \
|
| 77 |
+
tqdm(total=len(metadata), desc=desc) as pbar:
|
| 78 |
+
def worker(metadatum):
|
| 79 |
+
try:
|
| 80 |
+
local_path = metadatum['local_path']
|
| 81 |
+
sha256 = metadatum['sha256']
|
| 82 |
+
file = os.path.join(output_dir, local_path)
|
| 83 |
+
record = func(file, sha256)
|
| 84 |
+
if record is not None:
|
| 85 |
+
records.append(record)
|
| 86 |
+
pbar.update()
|
| 87 |
+
except Exception as e:
|
| 88 |
+
print(f"Error processing object {sha256}: {e}")
|
| 89 |
+
pbar.update()
|
| 90 |
+
|
| 91 |
+
executor.map(worker, metadata)
|
| 92 |
+
executor.shutdown(wait=True)
|
| 93 |
+
except:
|
| 94 |
+
print("Error happened during processing.")
|
| 95 |
+
|
| 96 |
+
return pd.DataFrame.from_records(records)
|
OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/datasets/HSSD.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import re
|
| 3 |
+
import argparse
|
| 4 |
+
import tarfile
|
| 5 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 6 |
+
from tqdm import tqdm
|
| 7 |
+
import pandas as pd
|
| 8 |
+
import huggingface_hub
|
| 9 |
+
from utils import get_file_hash
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def add_args(parser: argparse.ArgumentParser):
|
| 13 |
+
pass
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def get_metadata(**kwargs):
|
| 17 |
+
metadata = pd.read_csv("hf://datasets/JeffreyXiang/TRELLIS-500K/HSSD.csv")
|
| 18 |
+
return metadata
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def download(metadata, output_dir, **kwargs):
|
| 22 |
+
os.makedirs(os.path.join(output_dir, 'raw'), exist_ok=True)
|
| 23 |
+
|
| 24 |
+
# check login
|
| 25 |
+
try:
|
| 26 |
+
huggingface_hub.whoami()
|
| 27 |
+
except:
|
| 28 |
+
print("\033[93m")
|
| 29 |
+
print("Haven't logged in to the Hugging Face Hub.")
|
| 30 |
+
print("Visit https://huggingface.co/settings/tokens to get a token.")
|
| 31 |
+
print("\033[0m")
|
| 32 |
+
huggingface_hub.login()
|
| 33 |
+
|
| 34 |
+
try:
|
| 35 |
+
huggingface_hub.hf_hub_download(repo_id="hssd/hssd-models", filename="README.md", repo_type="dataset")
|
| 36 |
+
except:
|
| 37 |
+
print("\033[93m")
|
| 38 |
+
print("Error downloading HSSD dataset.")
|
| 39 |
+
print("Check if you have access to the HSSD dataset.")
|
| 40 |
+
print("Visit https://huggingface.co/datasets/hssd/hssd-models for more information")
|
| 41 |
+
print("\033[0m")
|
| 42 |
+
|
| 43 |
+
downloaded = {}
|
| 44 |
+
metadata = metadata.set_index("file_identifier")
|
| 45 |
+
with ThreadPoolExecutor(max_workers=os.cpu_count()) as executor, \
|
| 46 |
+
tqdm(total=len(metadata), desc="Downloading") as pbar:
|
| 47 |
+
def worker(instance: str) -> str:
|
| 48 |
+
try:
|
| 49 |
+
huggingface_hub.hf_hub_download(repo_id="hssd/hssd-models", filename=instance, repo_type="dataset", local_dir=os.path.join(output_dir, 'raw'))
|
| 50 |
+
sha256 = get_file_hash(os.path.join(output_dir, 'raw', instance))
|
| 51 |
+
pbar.update()
|
| 52 |
+
return sha256
|
| 53 |
+
except Exception as e:
|
| 54 |
+
pbar.update()
|
| 55 |
+
print(f"Error extracting for {instance}: {e}")
|
| 56 |
+
return None
|
| 57 |
+
|
| 58 |
+
sha256s = executor.map(worker, metadata.index)
|
| 59 |
+
executor.shutdown(wait=True)
|
| 60 |
+
|
| 61 |
+
for k, sha256 in zip(metadata.index, sha256s):
|
| 62 |
+
if sha256 is not None:
|
| 63 |
+
if sha256 == metadata.loc[k, "sha256"]:
|
| 64 |
+
downloaded[sha256] = os.path.join('raw', k)
|
| 65 |
+
else:
|
| 66 |
+
print(f"Error downloading {k}: sha256s do not match")
|
| 67 |
+
|
| 68 |
+
return pd.DataFrame(downloaded.items(), columns=['sha256', 'local_path'])
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def foreach_instance(metadata, output_dir, func, max_workers=None, desc='Processing objects') -> pd.DataFrame:
|
| 72 |
+
import os
|
| 73 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 74 |
+
from tqdm import tqdm
|
| 75 |
+
|
| 76 |
+
# load metadata
|
| 77 |
+
metadata = metadata.to_dict('records')
|
| 78 |
+
|
| 79 |
+
# processing objects
|
| 80 |
+
records = []
|
| 81 |
+
max_workers = max_workers or os.cpu_count()
|
| 82 |
+
try:
|
| 83 |
+
with ThreadPoolExecutor(max_workers=max_workers) as executor, \
|
| 84 |
+
tqdm(total=len(metadata), desc=desc) as pbar:
|
| 85 |
+
def worker(metadatum):
|
| 86 |
+
try:
|
| 87 |
+
local_path = metadatum['local_path']
|
| 88 |
+
sha256 = metadatum['sha256']
|
| 89 |
+
file = os.path.join(output_dir, local_path)
|
| 90 |
+
record = func(file, sha256)
|
| 91 |
+
if record is not None:
|
| 92 |
+
records.append(record)
|
| 93 |
+
pbar.update()
|
| 94 |
+
except Exception as e:
|
| 95 |
+
print(f"Error processing object {sha256}: {e}")
|
| 96 |
+
pbar.update()
|
| 97 |
+
|
| 98 |
+
executor.map(worker, metadata)
|
| 99 |
+
executor.shutdown(wait=True)
|
| 100 |
+
except:
|
| 101 |
+
print("Error happened during processing.")
|
| 102 |
+
|
| 103 |
+
return pd.DataFrame.from_records(records)
|
OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/datasets/ObjaverseXL.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import argparse
|
| 3 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 4 |
+
from tqdm import tqdm
|
| 5 |
+
import pandas as pd
|
| 6 |
+
import objaverse.xl as oxl
|
| 7 |
+
from utils import get_file_hash
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def add_args(parser: argparse.ArgumentParser):
|
| 11 |
+
parser.add_argument('--source', type=str, default='sketchfab',
|
| 12 |
+
help='Data source to download annotations from (github, sketchfab)')
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def get_metadata(source, **kwargs):
|
| 16 |
+
if source == 'sketchfab':
|
| 17 |
+
metadata = pd.read_csv("hf://datasets/JeffreyXiang/TRELLIS-500K/ObjaverseXL_sketchfab.csv")
|
| 18 |
+
elif source == 'github':
|
| 19 |
+
metadata = pd.read_csv("hf://datasets/JeffreyXiang/TRELLIS-500K/ObjaverseXL_github.csv")
|
| 20 |
+
else:
|
| 21 |
+
raise ValueError(f"Invalid source: {source}")
|
| 22 |
+
return metadata
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def download(metadata, output_dir, **kwargs):
|
| 26 |
+
os.makedirs(os.path.join(output_dir, 'raw'), exist_ok=True)
|
| 27 |
+
|
| 28 |
+
# download annotations
|
| 29 |
+
annotations = oxl.get_annotations()
|
| 30 |
+
annotations = annotations[annotations['sha256'].isin(metadata['sha256'].values)]
|
| 31 |
+
|
| 32 |
+
# download and render objects
|
| 33 |
+
file_paths = oxl.download_objects(
|
| 34 |
+
annotations,
|
| 35 |
+
download_dir=os.path.join(output_dir, "raw"),
|
| 36 |
+
save_repo_format="zip",
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
downloaded = {}
|
| 40 |
+
metadata = metadata.set_index("file_identifier")
|
| 41 |
+
for k, v in file_paths.items():
|
| 42 |
+
sha256 = metadata.loc[k, "sha256"]
|
| 43 |
+
downloaded[sha256] = os.path.relpath(v, output_dir)
|
| 44 |
+
|
| 45 |
+
return pd.DataFrame(downloaded.items(), columns=['sha256', 'local_path'])
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def foreach_instance(metadata, output_dir, func, max_workers=None, desc='Processing objects') -> pd.DataFrame:
|
| 49 |
+
import os
|
| 50 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 51 |
+
from tqdm import tqdm
|
| 52 |
+
import tempfile
|
| 53 |
+
import zipfile
|
| 54 |
+
|
| 55 |
+
# load metadata
|
| 56 |
+
metadata = metadata.to_dict('records')
|
| 57 |
+
|
| 58 |
+
# processing objects
|
| 59 |
+
records = []
|
| 60 |
+
max_workers = max_workers or os.cpu_count()
|
| 61 |
+
try:
|
| 62 |
+
with ThreadPoolExecutor(max_workers=max_workers) as executor, \
|
| 63 |
+
tqdm(total=len(metadata), desc=desc) as pbar:
|
| 64 |
+
def worker(metadatum):
|
| 65 |
+
try:
|
| 66 |
+
local_path = metadatum['local_path']
|
| 67 |
+
sha256 = metadatum['sha256']
|
| 68 |
+
if local_path.startswith('raw/github/repos/'):
|
| 69 |
+
path_parts = local_path.split('/')
|
| 70 |
+
file_name = os.path.join(*path_parts[5:])
|
| 71 |
+
zip_file = os.path.join(output_dir, *path_parts[:5])
|
| 72 |
+
with tempfile.TemporaryDirectory() as tmp_dir:
|
| 73 |
+
with zipfile.ZipFile(zip_file, 'r') as zip_ref:
|
| 74 |
+
zip_ref.extractall(tmp_dir)
|
| 75 |
+
file = os.path.join(tmp_dir, file_name)
|
| 76 |
+
record = func(file, sha256)
|
| 77 |
+
else:
|
| 78 |
+
file = os.path.join(output_dir, local_path)
|
| 79 |
+
record = func(file, sha256)
|
| 80 |
+
if record is not None:
|
| 81 |
+
records.append(record)
|
| 82 |
+
pbar.update()
|
| 83 |
+
except Exception as e:
|
| 84 |
+
print(f"Error processing object {sha256}: {e}")
|
| 85 |
+
pbar.update()
|
| 86 |
+
|
| 87 |
+
executor.map(worker, metadata)
|
| 88 |
+
executor.shutdown(wait=True)
|
| 89 |
+
except:
|
| 90 |
+
print("Error happened during processing.")
|
| 91 |
+
|
| 92 |
+
return pd.DataFrame.from_records(records)
|
OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/datasets/Toys4k.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import re
|
| 3 |
+
import argparse
|
| 4 |
+
import zipfile
|
| 5 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 6 |
+
from tqdm import tqdm
|
| 7 |
+
import pandas as pd
|
| 8 |
+
from utils import get_file_hash
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def add_args(parser: argparse.ArgumentParser):
|
| 12 |
+
pass
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def get_metadata(**kwargs):
|
| 16 |
+
metadata = pd.read_csv("hf://datasets/JeffreyXiang/TRELLIS-500K/Toys4k.csv")
|
| 17 |
+
return metadata
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def download(metadata, output_dir, **kwargs):
|
| 21 |
+
os.makedirs(output_dir, exist_ok=True)
|
| 22 |
+
|
| 23 |
+
if not os.path.exists(os.path.join(output_dir, 'raw', 'toys4k_blend_files.zip')):
|
| 24 |
+
print("\033[93m")
|
| 25 |
+
print("Toys4k have to be downloaded manually")
|
| 26 |
+
print(f"Please download the toys4k_blend_files.zip file and place it in the {output_dir}/raw directory")
|
| 27 |
+
print("Visit https://github.com/rehg-lab/lowshot-shapebias/tree/main/toys4k for more information")
|
| 28 |
+
print("\033[0m")
|
| 29 |
+
raise FileNotFoundError("toys4k_blend_files.zip not found")
|
| 30 |
+
|
| 31 |
+
downloaded = {}
|
| 32 |
+
metadata = metadata.set_index("file_identifier")
|
| 33 |
+
with zipfile.ZipFile(os.path.join(output_dir, 'raw', 'toys4k_blend_files.zip')) as zip_ref:
|
| 34 |
+
with ThreadPoolExecutor(max_workers=os.cpu_count()) as executor, \
|
| 35 |
+
tqdm(total=len(metadata), desc="Extracting") as pbar:
|
| 36 |
+
def worker(instance: str) -> str:
|
| 37 |
+
try:
|
| 38 |
+
zip_ref.extract(os.path.join('toys4k_blend_files', instance), os.path.join(output_dir, 'raw'))
|
| 39 |
+
sha256 = get_file_hash(os.path.join(output_dir, 'raw/toys4k_blend_files', instance))
|
| 40 |
+
pbar.update()
|
| 41 |
+
return sha256
|
| 42 |
+
except Exception as e:
|
| 43 |
+
pbar.update()
|
| 44 |
+
print(f"Error extracting for {instance}: {e}")
|
| 45 |
+
return None
|
| 46 |
+
|
| 47 |
+
sha256s = executor.map(worker, metadata.index)
|
| 48 |
+
executor.shutdown(wait=True)
|
| 49 |
+
|
| 50 |
+
for k, sha256 in zip(metadata.index, sha256s):
|
| 51 |
+
if sha256 is not None:
|
| 52 |
+
if sha256 == metadata.loc[k, "sha256"]:
|
| 53 |
+
downloaded[sha256] = os.path.join("raw/toys4k_blend_files", k)
|
| 54 |
+
else:
|
| 55 |
+
print(f"Error downloading {k}: sha256s do not match")
|
| 56 |
+
|
| 57 |
+
return pd.DataFrame(downloaded.items(), columns=['sha256', 'local_path'])
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def foreach_instance(metadata, output_dir, func, max_workers=None, desc='Processing objects') -> pd.DataFrame:
|
| 61 |
+
import os
|
| 62 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 63 |
+
from tqdm import tqdm
|
| 64 |
+
|
| 65 |
+
# load metadata
|
| 66 |
+
metadata = metadata.to_dict('records')
|
| 67 |
+
|
| 68 |
+
# processing objects
|
| 69 |
+
records = []
|
| 70 |
+
max_workers = max_workers or os.cpu_count()
|
| 71 |
+
try:
|
| 72 |
+
with ThreadPoolExecutor(max_workers=max_workers) as executor, \
|
| 73 |
+
tqdm(total=len(metadata), desc=desc) as pbar:
|
| 74 |
+
def worker(metadatum):
|
| 75 |
+
try:
|
| 76 |
+
local_path = metadatum['local_path']
|
| 77 |
+
sha256 = metadatum['sha256']
|
| 78 |
+
file = os.path.join(output_dir, local_path)
|
| 79 |
+
record = func(file, sha256)
|
| 80 |
+
if record is not None:
|
| 81 |
+
records.append(record)
|
| 82 |
+
pbar.update()
|
| 83 |
+
except Exception as e:
|
| 84 |
+
print(f"Error processing object {sha256}: {e}")
|
| 85 |
+
pbar.update()
|
| 86 |
+
|
| 87 |
+
executor.map(worker, metadata)
|
| 88 |
+
executor.shutdown(wait=True)
|
| 89 |
+
except:
|
| 90 |
+
print("Error happened during processing.")
|
| 91 |
+
|
| 92 |
+
return pd.DataFrame.from_records(records)
|
OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/download.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import copy
|
| 3 |
+
import sys
|
| 4 |
+
import importlib
|
| 5 |
+
import argparse
|
| 6 |
+
import pandas as pd
|
| 7 |
+
from easydict import EasyDict as edict
|
| 8 |
+
|
| 9 |
+
if __name__ == '__main__':
|
| 10 |
+
dataset_utils = importlib.import_module(f'datasets.{sys.argv[1]}')
|
| 11 |
+
|
| 12 |
+
parser = argparse.ArgumentParser()
|
| 13 |
+
parser.add_argument('--output_dir', type=str, required=True,
|
| 14 |
+
help='Directory to save the metadata')
|
| 15 |
+
parser.add_argument('--filter_low_aesthetic_score', type=float, default=None,
|
| 16 |
+
help='Filter objects with aesthetic score lower than this value')
|
| 17 |
+
parser.add_argument('--instances', type=str, default=None,
|
| 18 |
+
help='Instances to process')
|
| 19 |
+
dataset_utils.add_args(parser)
|
| 20 |
+
parser.add_argument('--rank', type=int, default=0)
|
| 21 |
+
parser.add_argument('--world_size', type=int, default=1)
|
| 22 |
+
opt = parser.parse_args(sys.argv[2:])
|
| 23 |
+
opt = edict(vars(opt))
|
| 24 |
+
|
| 25 |
+
os.makedirs(opt.output_dir, exist_ok=True)
|
| 26 |
+
|
| 27 |
+
# get file list
|
| 28 |
+
if not os.path.exists(os.path.join(opt.output_dir, 'metadata.csv')):
|
| 29 |
+
raise ValueError('metadata.csv not found')
|
| 30 |
+
metadata = pd.read_csv(os.path.join(opt.output_dir, 'metadata.csv'))
|
| 31 |
+
if opt.instances is None:
|
| 32 |
+
if opt.filter_low_aesthetic_score is not None:
|
| 33 |
+
metadata = metadata[metadata['aesthetic_score'] >= opt.filter_low_aesthetic_score]
|
| 34 |
+
if 'local_path' in metadata.columns:
|
| 35 |
+
metadata = metadata[metadata['local_path'].isna()]
|
| 36 |
+
else:
|
| 37 |
+
if os.path.exists(opt.instances):
|
| 38 |
+
with open(opt.instances, 'r') as f:
|
| 39 |
+
instances = f.read().splitlines()
|
| 40 |
+
else:
|
| 41 |
+
instances = opt.instances.split(',')
|
| 42 |
+
metadata = metadata[metadata['sha256'].isin(instances)]
|
| 43 |
+
|
| 44 |
+
start = len(metadata) * opt.rank // opt.world_size
|
| 45 |
+
end = len(metadata) * (opt.rank + 1) // opt.world_size
|
| 46 |
+
metadata = metadata[start:end]
|
| 47 |
+
|
| 48 |
+
print(f'Processing {len(metadata)} objects...')
|
| 49 |
+
|
| 50 |
+
# process objects
|
| 51 |
+
downloaded = dataset_utils.download(metadata, **opt)
|
| 52 |
+
downloaded.to_csv(os.path.join(opt.output_dir, f'downloaded_{opt.rank}.csv'), index=False)
|
OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/encode_latent.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
|
| 4 |
+
import copy
|
| 5 |
+
import json
|
| 6 |
+
import argparse
|
| 7 |
+
import torch
|
| 8 |
+
import numpy as np
|
| 9 |
+
import pandas as pd
|
| 10 |
+
from tqdm import tqdm
|
| 11 |
+
from easydict import EasyDict as edict
|
| 12 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 13 |
+
from queue import Queue
|
| 14 |
+
|
| 15 |
+
import trellis.models as models
|
| 16 |
+
import trellis.modules.sparse as sp
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
torch.set_grad_enabled(False)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
if __name__ == '__main__':
|
| 23 |
+
parser = argparse.ArgumentParser()
|
| 24 |
+
parser.add_argument('--output_dir', type=str, required=True,
|
| 25 |
+
help='Directory to save the metadata')
|
| 26 |
+
parser.add_argument('--filter_low_aesthetic_score', type=float, default=None,
|
| 27 |
+
help='Filter objects with aesthetic score lower than this value')
|
| 28 |
+
parser.add_argument('--feat_model', type=str, default='dinov2_vitl14_reg',
|
| 29 |
+
help='Feature model')
|
| 30 |
+
parser.add_argument('--enc_pretrained', type=str, default='microsoft/TRELLIS-image-large/ckpts/slat_enc_swin8_B_64l8_fp16',
|
| 31 |
+
help='Pretrained encoder model')
|
| 32 |
+
parser.add_argument('--model_root', type=str, default='results',
|
| 33 |
+
help='Root directory of models')
|
| 34 |
+
parser.add_argument('--enc_model', type=str, default=None,
|
| 35 |
+
help='Encoder model. if specified, use this model instead of pretrained model')
|
| 36 |
+
parser.add_argument('--ckpt', type=str, default=None,
|
| 37 |
+
help='Checkpoint to load')
|
| 38 |
+
parser.add_argument('--instances', type=str, default=None,
|
| 39 |
+
help='Instances to process')
|
| 40 |
+
parser.add_argument('--rank', type=int, default=0)
|
| 41 |
+
parser.add_argument('--world_size', type=int, default=1)
|
| 42 |
+
opt = parser.parse_args()
|
| 43 |
+
opt = edict(vars(opt))
|
| 44 |
+
|
| 45 |
+
if opt.enc_model is None:
|
| 46 |
+
latent_name = f'{opt.feat_model}_{opt.enc_pretrained.split("/")[-1]}'
|
| 47 |
+
encoder = models.from_pretrained(opt.enc_pretrained).eval().cuda()
|
| 48 |
+
else:
|
| 49 |
+
latent_name = f'{opt.feat_model}_{opt.enc_model}_{opt.ckpt}'
|
| 50 |
+
cfg = edict(json.load(open(os.path.join(opt.model_root, opt.enc_model, 'config.json'), 'r')))
|
| 51 |
+
encoder = getattr(models, cfg.models.encoder.name)(**cfg.models.encoder.args).cuda()
|
| 52 |
+
ckpt_path = os.path.join(opt.model_root, opt.enc_model, 'ckpts', f'encoder_{opt.ckpt}.pt')
|
| 53 |
+
encoder.load_state_dict(torch.load(ckpt_path), strict=False)
|
| 54 |
+
encoder.eval()
|
| 55 |
+
print(f'Loaded model from {ckpt_path}')
|
| 56 |
+
|
| 57 |
+
os.makedirs(os.path.join(opt.output_dir, 'latents', latent_name), exist_ok=True)
|
| 58 |
+
|
| 59 |
+
# get file list
|
| 60 |
+
if os.path.exists(os.path.join(opt.output_dir, 'metadata.csv')):
|
| 61 |
+
metadata = pd.read_csv(os.path.join(opt.output_dir, 'metadata.csv'))
|
| 62 |
+
else:
|
| 63 |
+
raise ValueError('metadata.csv not found')
|
| 64 |
+
if opt.instances is not None:
|
| 65 |
+
with open(opt.instances, 'r') as f:
|
| 66 |
+
sha256s = [line.strip() for line in f]
|
| 67 |
+
metadata = metadata[metadata['sha256'].isin(sha256s)]
|
| 68 |
+
else:
|
| 69 |
+
if opt.filter_low_aesthetic_score is not None:
|
| 70 |
+
metadata = metadata[metadata['aesthetic_score'] >= opt.filter_low_aesthetic_score]
|
| 71 |
+
metadata = metadata[metadata[f'feature_{opt.feat_model}'] == True]
|
| 72 |
+
if f'latent_{latent_name}' in metadata.columns:
|
| 73 |
+
metadata = metadata[metadata[f'latent_{latent_name}'] == False]
|
| 74 |
+
|
| 75 |
+
start = len(metadata) * opt.rank // opt.world_size
|
| 76 |
+
end = len(metadata) * (opt.rank + 1) // opt.world_size
|
| 77 |
+
metadata = metadata[start:end]
|
| 78 |
+
records = []
|
| 79 |
+
|
| 80 |
+
# filter out objects that are already processed
|
| 81 |
+
sha256s = list(metadata['sha256'].values)
|
| 82 |
+
for sha256 in copy.copy(sha256s):
|
| 83 |
+
if os.path.exists(os.path.join(opt.output_dir, 'latents', latent_name, f'{sha256}.npz')):
|
| 84 |
+
records.append({'sha256': sha256, f'latent_{latent_name}': True})
|
| 85 |
+
sha256s.remove(sha256)
|
| 86 |
+
|
| 87 |
+
# encode latents
|
| 88 |
+
load_queue = Queue(maxsize=4)
|
| 89 |
+
try:
|
| 90 |
+
with ThreadPoolExecutor(max_workers=32) as loader_executor, \
|
| 91 |
+
ThreadPoolExecutor(max_workers=32) as saver_executor:
|
| 92 |
+
def loader(sha256):
|
| 93 |
+
try:
|
| 94 |
+
feats = np.load(os.path.join(opt.output_dir, 'features', opt.feat_model, f'{sha256}.npz'))
|
| 95 |
+
load_queue.put((sha256, feats))
|
| 96 |
+
except Exception as e:
|
| 97 |
+
print(f"Error loading features for {sha256}: {e}")
|
| 98 |
+
loader_executor.map(loader, sha256s)
|
| 99 |
+
|
| 100 |
+
def saver(sha256, pack):
|
| 101 |
+
save_path = os.path.join(opt.output_dir, 'latents', latent_name, f'{sha256}.npz')
|
| 102 |
+
np.savez_compressed(save_path, **pack)
|
| 103 |
+
records.append({'sha256': sha256, f'latent_{latent_name}': True})
|
| 104 |
+
|
| 105 |
+
for _ in tqdm(range(len(sha256s)), desc="Extracting latents"):
|
| 106 |
+
sha256, feats = load_queue.get()
|
| 107 |
+
feats = sp.SparseTensor(
|
| 108 |
+
feats = torch.from_numpy(feats['patchtokens']).float(),
|
| 109 |
+
coords = torch.cat([
|
| 110 |
+
torch.zeros(feats['patchtokens'].shape[0], 1).int(),
|
| 111 |
+
torch.from_numpy(feats['indices']).int(),
|
| 112 |
+
], dim=1),
|
| 113 |
+
).cuda()
|
| 114 |
+
latent = encoder(feats, sample_posterior=False)
|
| 115 |
+
assert torch.isfinite(latent.feats).all(), "Non-finite latent"
|
| 116 |
+
pack = {
|
| 117 |
+
'feats': latent.feats.cpu().numpy().astype(np.float32),
|
| 118 |
+
'coords': latent.coords[:, 1:].cpu().numpy().astype(np.uint8),
|
| 119 |
+
}
|
| 120 |
+
saver_executor.submit(saver, sha256, pack)
|
| 121 |
+
|
| 122 |
+
saver_executor.shutdown(wait=True)
|
| 123 |
+
except:
|
| 124 |
+
print("Error happened during processing.")
|
| 125 |
+
|
| 126 |
+
records = pd.DataFrame.from_records(records)
|
| 127 |
+
records.to_csv(os.path.join(opt.output_dir, f'latent_{latent_name}_{opt.rank}.csv'), index=False)
|
OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/encode_ss_latent.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
|
| 4 |
+
import copy
|
| 5 |
+
import json
|
| 6 |
+
import argparse
|
| 7 |
+
import torch
|
| 8 |
+
import numpy as np
|
| 9 |
+
import pandas as pd
|
| 10 |
+
import utils3d
|
| 11 |
+
from tqdm import tqdm
|
| 12 |
+
from easydict import EasyDict as edict
|
| 13 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 14 |
+
from queue import Queue
|
| 15 |
+
|
| 16 |
+
import trellis.models as models
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
torch.set_grad_enabled(False)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def get_voxels(instance):
|
| 23 |
+
position = utils3d.io.read_ply(os.path.join(opt.output_dir, 'voxels', f'{instance}.ply'))[0]
|
| 24 |
+
coords = ((torch.tensor(position) + 0.5) * opt.resolution).int().contiguous()
|
| 25 |
+
ss = torch.zeros(1, opt.resolution, opt.resolution, opt.resolution, dtype=torch.long)
|
| 26 |
+
ss[:, coords[:, 0], coords[:, 1], coords[:, 2]] = 1
|
| 27 |
+
return ss
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
if __name__ == '__main__':
|
| 31 |
+
parser = argparse.ArgumentParser()
|
| 32 |
+
parser.add_argument('--output_dir', type=str, required=True,
|
| 33 |
+
help='Directory to save the metadata')
|
| 34 |
+
parser.add_argument('--filter_low_aesthetic_score', type=float, default=None,
|
| 35 |
+
help='Filter objects with aesthetic score lower than this value')
|
| 36 |
+
parser.add_argument('--enc_pretrained', type=str, default='microsoft/TRELLIS-image-large/ckpts/ss_enc_conv3d_16l8_fp16',
|
| 37 |
+
help='Pretrained encoder model')
|
| 38 |
+
parser.add_argument('--model_root', type=str, default='results',
|
| 39 |
+
help='Root directory of models')
|
| 40 |
+
parser.add_argument('--enc_model', type=str, default=None,
|
| 41 |
+
help='Encoder model. if specified, use this model instead of pretrained model')
|
| 42 |
+
parser.add_argument('--ckpt', type=str, default=None,
|
| 43 |
+
help='Checkpoint to load')
|
| 44 |
+
parser.add_argument('--resolution', type=int, default=64,
|
| 45 |
+
help='Resolution')
|
| 46 |
+
parser.add_argument('--instances', type=str, default=None,
|
| 47 |
+
help='Instances to process')
|
| 48 |
+
parser.add_argument('--rank', type=int, default=0)
|
| 49 |
+
parser.add_argument('--world_size', type=int, default=1)
|
| 50 |
+
opt = parser.parse_args()
|
| 51 |
+
opt = edict(vars(opt))
|
| 52 |
+
|
| 53 |
+
if opt.enc_model is None:
|
| 54 |
+
latent_name = f'{opt.enc_pretrained.split("/")[-1]}'
|
| 55 |
+
encoder = models.from_pretrained(opt.enc_pretrained).eval().cuda()
|
| 56 |
+
else:
|
| 57 |
+
latent_name = f'{opt.enc_model}_{opt.ckpt}'
|
| 58 |
+
cfg = edict(json.load(open(os.path.join(opt.model_root, opt.enc_model, 'config.json'), 'r')))
|
| 59 |
+
encoder = getattr(models, cfg.models.encoder.name)(**cfg.models.encoder.args).cuda()
|
| 60 |
+
ckpt_path = os.path.join(opt.model_root, opt.enc_model, 'ckpts', f'encoder_{opt.ckpt}.pt')
|
| 61 |
+
encoder.load_state_dict(torch.load(ckpt_path), strict=False)
|
| 62 |
+
encoder.eval()
|
| 63 |
+
print(f'Loaded model from {ckpt_path}')
|
| 64 |
+
|
| 65 |
+
os.makedirs(os.path.join(opt.output_dir, 'ss_latents', latent_name), exist_ok=True)
|
| 66 |
+
|
| 67 |
+
# get file list
|
| 68 |
+
if os.path.exists(os.path.join(opt.output_dir, 'metadata.csv')):
|
| 69 |
+
metadata = pd.read_csv(os.path.join(opt.output_dir, 'metadata.csv'))
|
| 70 |
+
else:
|
| 71 |
+
raise ValueError('metadata.csv not found')
|
| 72 |
+
if opt.instances is not None:
|
| 73 |
+
with open(opt.instances, 'r') as f:
|
| 74 |
+
instances = f.read().splitlines()
|
| 75 |
+
metadata = metadata[metadata['sha256'].isin(instances)]
|
| 76 |
+
else:
|
| 77 |
+
if opt.filter_low_aesthetic_score is not None:
|
| 78 |
+
metadata = metadata[metadata['aesthetic_score'] >= opt.filter_low_aesthetic_score]
|
| 79 |
+
metadata = metadata[metadata['voxelized'] == True]
|
| 80 |
+
if f'ss_latent_{latent_name}' in metadata.columns:
|
| 81 |
+
metadata = metadata[metadata[f'ss_latent_{latent_name}'] == False]
|
| 82 |
+
|
| 83 |
+
start = len(metadata) * opt.rank // opt.world_size
|
| 84 |
+
end = len(metadata) * (opt.rank + 1) // opt.world_size
|
| 85 |
+
metadata = metadata[start:end]
|
| 86 |
+
records = []
|
| 87 |
+
|
| 88 |
+
# filter out objects that are already processed
|
| 89 |
+
sha256s = list(metadata['sha256'].values)
|
| 90 |
+
for sha256 in copy.copy(sha256s):
|
| 91 |
+
if os.path.exists(os.path.join(opt.output_dir, 'ss_latents', latent_name, f'{sha256}.npz')):
|
| 92 |
+
records.append({'sha256': sha256, f'ss_latent_{latent_name}': True})
|
| 93 |
+
sha256s.remove(sha256)
|
| 94 |
+
|
| 95 |
+
# encode latents
|
| 96 |
+
load_queue = Queue(maxsize=4)
|
| 97 |
+
try:
|
| 98 |
+
with ThreadPoolExecutor(max_workers=32) as loader_executor, \
|
| 99 |
+
ThreadPoolExecutor(max_workers=32) as saver_executor:
|
| 100 |
+
def loader(sha256):
|
| 101 |
+
try:
|
| 102 |
+
ss = get_voxels(sha256)[None].float()
|
| 103 |
+
load_queue.put((sha256, ss))
|
| 104 |
+
except Exception as e:
|
| 105 |
+
print(f"Error loading features for {sha256}: {e}")
|
| 106 |
+
loader_executor.map(loader, sha256s)
|
| 107 |
+
|
| 108 |
+
def saver(sha256, pack):
|
| 109 |
+
save_path = os.path.join(opt.output_dir, 'ss_latents', latent_name, f'{sha256}.npz')
|
| 110 |
+
np.savez_compressed(save_path, **pack)
|
| 111 |
+
records.append({'sha256': sha256, f'ss_latent_{latent_name}': True})
|
| 112 |
+
|
| 113 |
+
for _ in tqdm(range(len(sha256s)), desc="Extracting latents"):
|
| 114 |
+
sha256, ss = load_queue.get()
|
| 115 |
+
ss = ss.cuda().float()
|
| 116 |
+
latent = encoder(ss, sample_posterior=False)
|
| 117 |
+
assert torch.isfinite(latent).all(), "Non-finite latent"
|
| 118 |
+
pack = {
|
| 119 |
+
'mean': latent[0].cpu().numpy(),
|
| 120 |
+
}
|
| 121 |
+
saver_executor.submit(saver, sha256, pack)
|
| 122 |
+
|
| 123 |
+
saver_executor.shutdown(wait=True)
|
| 124 |
+
except:
|
| 125 |
+
print("Error happened during processing.")
|
| 126 |
+
|
| 127 |
+
records = pd.DataFrame.from_records(records)
|
| 128 |
+
records.to_csv(os.path.join(opt.output_dir, f'ss_latent_{latent_name}_{opt.rank}.csv'), index=False)
|
OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/extract_feature.py
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import copy
|
| 3 |
+
import sys
|
| 4 |
+
import json
|
| 5 |
+
import importlib
|
| 6 |
+
import argparse
|
| 7 |
+
import torch
|
| 8 |
+
import torch.nn.functional as F
|
| 9 |
+
import numpy as np
|
| 10 |
+
import pandas as pd
|
| 11 |
+
import utils3d
|
| 12 |
+
from tqdm import tqdm
|
| 13 |
+
from easydict import EasyDict as edict
|
| 14 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 15 |
+
from queue import Queue
|
| 16 |
+
from torchvision import transforms
|
| 17 |
+
from PIL import Image
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
torch.set_grad_enabled(False)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def get_data(frames, sha256):
|
| 24 |
+
with ThreadPoolExecutor(max_workers=16) as executor:
|
| 25 |
+
def worker(view):
|
| 26 |
+
image_path = os.path.join(opt.output_dir, 'renders', sha256, view['file_path'])
|
| 27 |
+
try:
|
| 28 |
+
image = Image.open(image_path)
|
| 29 |
+
except:
|
| 30 |
+
print(f"Error loading image {image_path}")
|
| 31 |
+
return None
|
| 32 |
+
image = image.resize((518, 518), Image.Resampling.LANCZOS)
|
| 33 |
+
image = np.array(image).astype(np.float32) / 255
|
| 34 |
+
image = image[:, :, :3] * image[:, :, 3:]
|
| 35 |
+
image = torch.from_numpy(image).permute(2, 0, 1).float()
|
| 36 |
+
|
| 37 |
+
c2w = torch.tensor(view['transform_matrix'])
|
| 38 |
+
c2w[:3, 1:3] *= -1
|
| 39 |
+
extrinsics = torch.inverse(c2w)
|
| 40 |
+
fov = view['camera_angle_x']
|
| 41 |
+
intrinsics = utils3d.torch.intrinsics_from_fov_xy(torch.tensor(fov), torch.tensor(fov))
|
| 42 |
+
|
| 43 |
+
return {
|
| 44 |
+
'image': image,
|
| 45 |
+
'extrinsics': extrinsics,
|
| 46 |
+
'intrinsics': intrinsics
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
datas = executor.map(worker, frames)
|
| 50 |
+
for data in datas:
|
| 51 |
+
if data is not None:
|
| 52 |
+
yield data
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
if __name__ == '__main__':
|
| 56 |
+
parser = argparse.ArgumentParser()
|
| 57 |
+
parser.add_argument('--output_dir', type=str, required=True,
|
| 58 |
+
help='Directory to save the metadata')
|
| 59 |
+
parser.add_argument('--filter_low_aesthetic_score', type=float, default=None,
|
| 60 |
+
help='Filter objects with aesthetic score lower than this value')
|
| 61 |
+
parser.add_argument('--model', type=str, default='dinov2_vitl14_reg',
|
| 62 |
+
help='Feature extraction model')
|
| 63 |
+
parser.add_argument('--instances', type=str, default=None,
|
| 64 |
+
help='Instances to process')
|
| 65 |
+
parser.add_argument('--batch_size', type=int, default=16)
|
| 66 |
+
parser.add_argument('--rank', type=int, default=0)
|
| 67 |
+
parser.add_argument('--world_size', type=int, default=1)
|
| 68 |
+
opt = parser.parse_args()
|
| 69 |
+
opt = edict(vars(opt))
|
| 70 |
+
|
| 71 |
+
feature_name = opt.model
|
| 72 |
+
os.makedirs(os.path.join(opt.output_dir, 'features', feature_name), exist_ok=True)
|
| 73 |
+
|
| 74 |
+
# load model
|
| 75 |
+
dinov2_model = torch.hub.load('facebookresearch/dinov2', opt.model)
|
| 76 |
+
dinov2_model.eval().cuda()
|
| 77 |
+
transform = transforms.Compose([
|
| 78 |
+
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
|
| 79 |
+
])
|
| 80 |
+
n_patch = 518 // 14
|
| 81 |
+
|
| 82 |
+
# get file list
|
| 83 |
+
if os.path.exists(os.path.join(opt.output_dir, 'metadata.csv')):
|
| 84 |
+
metadata = pd.read_csv(os.path.join(opt.output_dir, 'metadata.csv'))
|
| 85 |
+
else:
|
| 86 |
+
raise ValueError('metadata.csv not found')
|
| 87 |
+
if opt.instances is not None:
|
| 88 |
+
with open(opt.instances, 'r') as f:
|
| 89 |
+
instances = f.read().splitlines()
|
| 90 |
+
metadata = metadata[metadata['sha256'].isin(instances)]
|
| 91 |
+
else:
|
| 92 |
+
if opt.filter_low_aesthetic_score is not None:
|
| 93 |
+
metadata = metadata[metadata['aesthetic_score'] >= opt.filter_low_aesthetic_score]
|
| 94 |
+
if f'feature_{feature_name}' in metadata.columns:
|
| 95 |
+
metadata = metadata[metadata[f'feature_{feature_name}'] == False]
|
| 96 |
+
metadata = metadata[metadata['voxelized'] == True]
|
| 97 |
+
metadata = metadata[metadata['rendered'] == True]
|
| 98 |
+
|
| 99 |
+
start = len(metadata) * opt.rank // opt.world_size
|
| 100 |
+
end = len(metadata) * (opt.rank + 1) // opt.world_size
|
| 101 |
+
metadata = metadata[start:end]
|
| 102 |
+
records = []
|
| 103 |
+
|
| 104 |
+
# filter out objects that are already processed
|
| 105 |
+
sha256s = list(metadata['sha256'].values)
|
| 106 |
+
for sha256 in copy.copy(sha256s):
|
| 107 |
+
if os.path.exists(os.path.join(opt.output_dir, 'features', feature_name, f'{sha256}.npz')):
|
| 108 |
+
records.append({'sha256': sha256, f'feature_{feature_name}' : True})
|
| 109 |
+
sha256s.remove(sha256)
|
| 110 |
+
|
| 111 |
+
# extract features
|
| 112 |
+
load_queue = Queue(maxsize=4)
|
| 113 |
+
try:
|
| 114 |
+
with ThreadPoolExecutor(max_workers=8) as loader_executor, \
|
| 115 |
+
ThreadPoolExecutor(max_workers=8) as saver_executor:
|
| 116 |
+
def loader(sha256):
|
| 117 |
+
try:
|
| 118 |
+
with open(os.path.join(opt.output_dir, 'renders', sha256, 'transforms.json'), 'r') as f:
|
| 119 |
+
metadata = json.load(f)
|
| 120 |
+
frames = metadata['frames']
|
| 121 |
+
data = []
|
| 122 |
+
for datum in get_data(frames, sha256):
|
| 123 |
+
datum['image'] = transform(datum['image'])
|
| 124 |
+
data.append(datum)
|
| 125 |
+
positions = utils3d.io.read_ply(os.path.join(opt.output_dir, 'voxels', f'{sha256}.ply'))[0]
|
| 126 |
+
load_queue.put((sha256, data, positions))
|
| 127 |
+
except Exception as e:
|
| 128 |
+
print(f"Error loading data for {sha256}: {e}")
|
| 129 |
+
|
| 130 |
+
loader_executor.map(loader, sha256s)
|
| 131 |
+
|
| 132 |
+
def saver(sha256, pack, patchtokens, uv):
|
| 133 |
+
pack['patchtokens'] = F.grid_sample(
|
| 134 |
+
patchtokens,
|
| 135 |
+
uv.unsqueeze(1),
|
| 136 |
+
mode='bilinear',
|
| 137 |
+
align_corners=False,
|
| 138 |
+
).squeeze(2).permute(0, 2, 1).cpu().numpy()
|
| 139 |
+
pack['patchtokens'] = np.mean(pack['patchtokens'], axis=0).astype(np.float16)
|
| 140 |
+
save_path = os.path.join(opt.output_dir, 'features', feature_name, f'{sha256}.npz')
|
| 141 |
+
np.savez_compressed(save_path, **pack)
|
| 142 |
+
records.append({'sha256': sha256, f'feature_{feature_name}' : True})
|
| 143 |
+
|
| 144 |
+
for _ in tqdm(range(len(sha256s)), desc="Extracting features"):
|
| 145 |
+
sha256, data, positions = load_queue.get()
|
| 146 |
+
positions = torch.from_numpy(positions).float().cuda()
|
| 147 |
+
indices = ((positions + 0.5) * 64).long()
|
| 148 |
+
assert torch.all(indices >= 0) and torch.all(indices < 64), "Some vertices are out of bounds"
|
| 149 |
+
n_views = len(data)
|
| 150 |
+
N = positions.shape[0]
|
| 151 |
+
pack = {
|
| 152 |
+
'indices': indices.cpu().numpy().astype(np.uint8),
|
| 153 |
+
}
|
| 154 |
+
patchtokens_lst = []
|
| 155 |
+
uv_lst = []
|
| 156 |
+
for i in range(0, n_views, opt.batch_size):
|
| 157 |
+
batch_data = data[i:i+opt.batch_size]
|
| 158 |
+
bs = len(batch_data)
|
| 159 |
+
batch_images = torch.stack([d['image'] for d in batch_data]).cuda()
|
| 160 |
+
batch_extrinsics = torch.stack([d['extrinsics'] for d in batch_data]).cuda()
|
| 161 |
+
batch_intrinsics = torch.stack([d['intrinsics'] for d in batch_data]).cuda()
|
| 162 |
+
features = dinov2_model(batch_images, is_training=True)
|
| 163 |
+
uv = utils3d.torch.project_cv(positions, batch_extrinsics, batch_intrinsics)[0] * 2 - 1
|
| 164 |
+
patchtokens = features['x_prenorm'][:, dinov2_model.num_register_tokens + 1:].permute(0, 2, 1).reshape(bs, 1024, n_patch, n_patch)
|
| 165 |
+
patchtokens_lst.append(patchtokens)
|
| 166 |
+
uv_lst.append(uv)
|
| 167 |
+
patchtokens = torch.cat(patchtokens_lst, dim=0)
|
| 168 |
+
uv = torch.cat(uv_lst, dim=0)
|
| 169 |
+
|
| 170 |
+
# save features
|
| 171 |
+
saver_executor.submit(saver, sha256, pack, patchtokens, uv)
|
| 172 |
+
|
| 173 |
+
saver_executor.shutdown(wait=True)
|
| 174 |
+
except:
|
| 175 |
+
print("Error happened during processing.")
|
| 176 |
+
|
| 177 |
+
records = pd.DataFrame.from_records(records)
|
| 178 |
+
records.to_csv(os.path.join(opt.output_dir, f'feature_{feature_name}_{opt.rank}.csv'), index=False)
|
| 179 |
+
|
OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/render.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import copy
|
| 4 |
+
import sys
|
| 5 |
+
import importlib
|
| 6 |
+
import argparse
|
| 7 |
+
import pandas as pd
|
| 8 |
+
from easydict import EasyDict as edict
|
| 9 |
+
from functools import partial
|
| 10 |
+
from subprocess import DEVNULL, call
|
| 11 |
+
import numpy as np
|
| 12 |
+
from utils import sphere_hammersley_sequence
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
BLENDER_LINK = 'https://download.blender.org/release/Blender3.0/blender-3.0.1-linux-x64.tar.xz'
|
| 16 |
+
BLENDER_INSTALLATION_PATH = '/tmp'
|
| 17 |
+
BLENDER_PATH = f'{BLENDER_INSTALLATION_PATH}/blender-3.0.1-linux-x64/blender'
|
| 18 |
+
|
| 19 |
+
def _install_blender():
|
| 20 |
+
if not os.path.exists(BLENDER_PATH):
|
| 21 |
+
os.system('sudo apt-get update')
|
| 22 |
+
os.system('sudo apt-get install -y libxrender1 libxi6 libxkbcommon-x11-0 libsm6')
|
| 23 |
+
os.system(f'wget {BLENDER_LINK} -P {BLENDER_INSTALLATION_PATH}')
|
| 24 |
+
os.system(f'tar -xvf {BLENDER_INSTALLATION_PATH}/blender-3.0.1-linux-x64.tar.xz -C {BLENDER_INSTALLATION_PATH}')
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _render(file_path, sha256, output_dir, num_views):
|
| 28 |
+
output_folder = os.path.join(output_dir, 'renders', sha256)
|
| 29 |
+
|
| 30 |
+
# Build camera {yaw, pitch, radius, fov}
|
| 31 |
+
yaws = []
|
| 32 |
+
pitchs = []
|
| 33 |
+
offset = (np.random.rand(), np.random.rand())
|
| 34 |
+
for i in range(num_views):
|
| 35 |
+
y, p = sphere_hammersley_sequence(i, num_views, offset)
|
| 36 |
+
yaws.append(y)
|
| 37 |
+
pitchs.append(p)
|
| 38 |
+
radius = [2] * num_views
|
| 39 |
+
fov = [40 / 180 * np.pi] * num_views
|
| 40 |
+
views = [{'yaw': y, 'pitch': p, 'radius': r, 'fov': f} for y, p, r, f in zip(yaws, pitchs, radius, fov)]
|
| 41 |
+
|
| 42 |
+
args = [
|
| 43 |
+
BLENDER_PATH, '-b', '-P', os.path.join(os.path.dirname(__file__), 'blender_script', 'render.py'),
|
| 44 |
+
'--',
|
| 45 |
+
'--views', json.dumps(views),
|
| 46 |
+
'--object', os.path.expanduser(file_path),
|
| 47 |
+
'--resolution', '512',
|
| 48 |
+
'--output_folder', output_folder,
|
| 49 |
+
'--engine', 'CYCLES',
|
| 50 |
+
'--save_mesh',
|
| 51 |
+
]
|
| 52 |
+
if file_path.endswith('.blend'):
|
| 53 |
+
args.insert(1, file_path)
|
| 54 |
+
|
| 55 |
+
call(args, stdout=DEVNULL, stderr=DEVNULL)
|
| 56 |
+
|
| 57 |
+
if os.path.exists(os.path.join(output_folder, 'transforms.json')):
|
| 58 |
+
return {'sha256': sha256, 'rendered': True}
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
if __name__ == '__main__':
|
| 62 |
+
dataset_utils = importlib.import_module(f'datasets.{sys.argv[1]}')
|
| 63 |
+
|
| 64 |
+
parser = argparse.ArgumentParser()
|
| 65 |
+
parser.add_argument('--output_dir', type=str, required=True,
|
| 66 |
+
help='Directory to save the metadata')
|
| 67 |
+
parser.add_argument('--filter_low_aesthetic_score', type=float, default=None,
|
| 68 |
+
help='Filter objects with aesthetic score lower than this value')
|
| 69 |
+
parser.add_argument('--instances', type=str, default=None,
|
| 70 |
+
help='Instances to process')
|
| 71 |
+
parser.add_argument('--num_views', type=int, default=150,
|
| 72 |
+
help='Number of views to render')
|
| 73 |
+
dataset_utils.add_args(parser)
|
| 74 |
+
parser.add_argument('--rank', type=int, default=0)
|
| 75 |
+
parser.add_argument('--world_size', type=int, default=1)
|
| 76 |
+
parser.add_argument('--max_workers', type=int, default=8)
|
| 77 |
+
opt = parser.parse_args(sys.argv[2:])
|
| 78 |
+
opt = edict(vars(opt))
|
| 79 |
+
|
| 80 |
+
os.makedirs(os.path.join(opt.output_dir, 'renders'), exist_ok=True)
|
| 81 |
+
|
| 82 |
+
# install blender
|
| 83 |
+
print('Checking blender...', flush=True)
|
| 84 |
+
_install_blender()
|
| 85 |
+
|
| 86 |
+
# get file list
|
| 87 |
+
if not os.path.exists(os.path.join(opt.output_dir, 'metadata.csv')):
|
| 88 |
+
raise ValueError('metadata.csv not found')
|
| 89 |
+
metadata = pd.read_csv(os.path.join(opt.output_dir, 'metadata.csv'))
|
| 90 |
+
if opt.instances is None:
|
| 91 |
+
metadata = metadata[metadata['local_path'].notna()]
|
| 92 |
+
if opt.filter_low_aesthetic_score is not None:
|
| 93 |
+
metadata = metadata[metadata['aesthetic_score'] >= opt.filter_low_aesthetic_score]
|
| 94 |
+
if 'rendered' in metadata.columns:
|
| 95 |
+
metadata = metadata[metadata['rendered'] == False]
|
| 96 |
+
else:
|
| 97 |
+
if os.path.exists(opt.instances):
|
| 98 |
+
with open(opt.instances, 'r') as f:
|
| 99 |
+
instances = f.read().splitlines()
|
| 100 |
+
else:
|
| 101 |
+
instances = opt.instances.split(',')
|
| 102 |
+
metadata = metadata[metadata['sha256'].isin(instances)]
|
| 103 |
+
|
| 104 |
+
start = len(metadata) * opt.rank // opt.world_size
|
| 105 |
+
end = len(metadata) * (opt.rank + 1) // opt.world_size
|
| 106 |
+
metadata = metadata[start:end]
|
| 107 |
+
records = []
|
| 108 |
+
|
| 109 |
+
# filter out objects that are already processed
|
| 110 |
+
for sha256 in copy.copy(metadata['sha256'].values):
|
| 111 |
+
if os.path.exists(os.path.join(opt.output_dir, 'renders', sha256, 'transforms.json')):
|
| 112 |
+
records.append({'sha256': sha256, 'rendered': True})
|
| 113 |
+
metadata = metadata[metadata['sha256'] != sha256]
|
| 114 |
+
|
| 115 |
+
print(f'Processing {len(metadata)} objects...')
|
| 116 |
+
|
| 117 |
+
# process objects
|
| 118 |
+
func = partial(_render, output_dir=opt.output_dir, num_views=opt.num_views)
|
| 119 |
+
rendered = dataset_utils.foreach_instance(metadata, opt.output_dir, func, max_workers=opt.max_workers, desc='Rendering objects')
|
| 120 |
+
rendered = pd.concat([rendered, pd.DataFrame.from_records(records)])
|
| 121 |
+
rendered.to_csv(os.path.join(opt.output_dir, f'rendered_{opt.rank}.csv'), index=False)
|
OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/render_cond.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import copy
|
| 4 |
+
import sys
|
| 5 |
+
import importlib
|
| 6 |
+
import argparse
|
| 7 |
+
import pandas as pd
|
| 8 |
+
from easydict import EasyDict as edict
|
| 9 |
+
from functools import partial
|
| 10 |
+
from subprocess import DEVNULL, call
|
| 11 |
+
import numpy as np
|
| 12 |
+
from utils import sphere_hammersley_sequence
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
BLENDER_LINK = 'https://download.blender.org/release/Blender3.0/blender-3.0.1-linux-x64.tar.xz'
|
| 16 |
+
BLENDER_INSTALLATION_PATH = '/tmp'
|
| 17 |
+
BLENDER_PATH = f'{BLENDER_INSTALLATION_PATH}/blender-3.0.1-linux-x64/blender'
|
| 18 |
+
|
| 19 |
+
def _install_blender():
|
| 20 |
+
if not os.path.exists(BLENDER_PATH):
|
| 21 |
+
os.system('sudo apt-get update')
|
| 22 |
+
os.system('sudo apt-get install -y libxrender1 libxi6 libxkbcommon-x11-0 libsm6')
|
| 23 |
+
os.system(f'wget {BLENDER_LINK} -P {BLENDER_INSTALLATION_PATH}')
|
| 24 |
+
os.system(f'tar -xvf {BLENDER_INSTALLATION_PATH}/blender-3.0.1-linux-x64.tar.xz -C {BLENDER_INSTALLATION_PATH}')
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _render_cond(file_path, sha256, output_dir, num_views):
|
| 28 |
+
output_folder = os.path.join(output_dir, 'renders_cond', sha256)
|
| 29 |
+
|
| 30 |
+
# Build camera {yaw, pitch, radius, fov}
|
| 31 |
+
yaws = []
|
| 32 |
+
pitchs = []
|
| 33 |
+
offset = (np.random.rand(), np.random.rand())
|
| 34 |
+
for i in range(num_views):
|
| 35 |
+
y, p = sphere_hammersley_sequence(i, num_views, offset)
|
| 36 |
+
yaws.append(y)
|
| 37 |
+
pitchs.append(p)
|
| 38 |
+
fov_min, fov_max = 10, 70
|
| 39 |
+
radius_min = np.sqrt(3) / 2 / np.sin(fov_max / 360 * np.pi)
|
| 40 |
+
radius_max = np.sqrt(3) / 2 / np.sin(fov_min / 360 * np.pi)
|
| 41 |
+
k_min = 1 / radius_max**2
|
| 42 |
+
k_max = 1 / radius_min**2
|
| 43 |
+
ks = np.random.uniform(k_min, k_max, (1000000,))
|
| 44 |
+
radius = [1 / np.sqrt(k) for k in ks]
|
| 45 |
+
fov = [2 * np.arcsin(np.sqrt(3) / 2 / r) for r in radius]
|
| 46 |
+
views = [{'yaw': y, 'pitch': p, 'radius': r, 'fov': f} for y, p, r, f in zip(yaws, pitchs, radius, fov)]
|
| 47 |
+
|
| 48 |
+
args = [
|
| 49 |
+
BLENDER_PATH, '-b', '-P', os.path.join(os.path.dirname(__file__), 'blender_script', 'render.py'),
|
| 50 |
+
'--',
|
| 51 |
+
'--views', json.dumps(views),
|
| 52 |
+
'--object', os.path.expanduser(file_path),
|
| 53 |
+
'--output_folder', os.path.expanduser(output_folder),
|
| 54 |
+
'--resolution', '1024',
|
| 55 |
+
]
|
| 56 |
+
if file_path.endswith('.blend'):
|
| 57 |
+
args.insert(1, file_path)
|
| 58 |
+
|
| 59 |
+
call(args, stdout=DEVNULL)
|
| 60 |
+
|
| 61 |
+
if os.path.exists(os.path.join(output_folder, 'transforms.json')):
|
| 62 |
+
return {'sha256': sha256, 'cond_rendered': True}
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
if __name__ == '__main__':
|
| 66 |
+
dataset_utils = importlib.import_module(f'datasets.{sys.argv[1]}')
|
| 67 |
+
|
| 68 |
+
parser = argparse.ArgumentParser()
|
| 69 |
+
parser.add_argument('--output_dir', type=str, required=True,
|
| 70 |
+
help='Directory to save the metadata')
|
| 71 |
+
parser.add_argument('--filter_low_aesthetic_score', type=float, default=None,
|
| 72 |
+
help='Filter objects with aesthetic score lower than this value')
|
| 73 |
+
parser.add_argument('--instances', type=str, default=None,
|
| 74 |
+
help='Instances to process')
|
| 75 |
+
parser.add_argument('--num_views', type=int, default=24,
|
| 76 |
+
help='Number of views to render')
|
| 77 |
+
dataset_utils.add_args(parser)
|
| 78 |
+
parser.add_argument('--rank', type=int, default=0)
|
| 79 |
+
parser.add_argument('--world_size', type=int, default=1)
|
| 80 |
+
parser.add_argument('--max_workers', type=int, default=8)
|
| 81 |
+
opt = parser.parse_args(sys.argv[2:])
|
| 82 |
+
opt = edict(vars(opt))
|
| 83 |
+
|
| 84 |
+
os.makedirs(os.path.join(opt.output_dir, 'renders_cond'), exist_ok=True)
|
| 85 |
+
|
| 86 |
+
# install blender
|
| 87 |
+
print('Checking blender...', flush=True)
|
| 88 |
+
_install_blender()
|
| 89 |
+
|
| 90 |
+
# get file list
|
| 91 |
+
if not os.path.exists(os.path.join(opt.output_dir, 'metadata.csv')):
|
| 92 |
+
raise ValueError('metadata.csv not found')
|
| 93 |
+
metadata = pd.read_csv(os.path.join(opt.output_dir, 'metadata.csv'))
|
| 94 |
+
if opt.instances is None:
|
| 95 |
+
metadata = metadata[metadata['local_path'].notna()]
|
| 96 |
+
if opt.filter_low_aesthetic_score is not None:
|
| 97 |
+
metadata = metadata[metadata['aesthetic_score'] >= opt.filter_low_aesthetic_score]
|
| 98 |
+
if 'cond_rendered' in metadata.columns:
|
| 99 |
+
metadata = metadata[metadata['cond_rendered'] == False]
|
| 100 |
+
else:
|
| 101 |
+
if os.path.exists(opt.instances):
|
| 102 |
+
with open(opt.instances, 'r') as f:
|
| 103 |
+
instances = f.read().splitlines()
|
| 104 |
+
else:
|
| 105 |
+
instances = opt.instances.split(',')
|
| 106 |
+
metadata = metadata[metadata['sha256'].isin(instances)]
|
| 107 |
+
|
| 108 |
+
start = len(metadata) * opt.rank // opt.world_size
|
| 109 |
+
end = len(metadata) * (opt.rank + 1) // opt.world_size
|
| 110 |
+
metadata = metadata[start:end]
|
| 111 |
+
records = []
|
| 112 |
+
|
| 113 |
+
# filter out objects that are already processed
|
| 114 |
+
for sha256 in copy.copy(metadata['sha256'].values):
|
| 115 |
+
if os.path.exists(os.path.join(opt.output_dir, 'renders_cond', sha256, 'transforms.json')):
|
| 116 |
+
records.append({'sha256': sha256, 'cond_rendered': True})
|
| 117 |
+
metadata = metadata[metadata['sha256'] != sha256]
|
| 118 |
+
|
| 119 |
+
print(f'Processing {len(metadata)} objects...')
|
| 120 |
+
|
| 121 |
+
# process objects
|
| 122 |
+
func = partial(_render_cond, output_dir=opt.output_dir, num_views=opt.num_views)
|
| 123 |
+
cond_rendered = dataset_utils.foreach_instance(metadata, opt.output_dir, func, max_workers=opt.max_workers, desc='Rendering objects')
|
| 124 |
+
cond_rendered = pd.concat([cond_rendered, pd.DataFrame.from_records(records)])
|
| 125 |
+
cond_rendered.to_csv(os.path.join(opt.output_dir, f'cond_rendered_{opt.rank}.csv'), index=False)
|
OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/setup.sh
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
pip install pillow imageio imageio-ffmpeg tqdm easydict opencv-python-headless pandas open3d objaverse huggingface_hub
|
OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/stat_latent.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import argparse
|
| 4 |
+
import numpy as np
|
| 5 |
+
import pandas as pd
|
| 6 |
+
from tqdm import tqdm
|
| 7 |
+
from easydict import EasyDict as edict
|
| 8 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
if __name__ == '__main__':
|
| 12 |
+
parser = argparse.ArgumentParser()
|
| 13 |
+
parser.add_argument('--output_dir', type=str, required=True,
|
| 14 |
+
help='Directory to save the metadata')
|
| 15 |
+
parser.add_argument('--filter_low_aesthetic_score', type=float, default=None,
|
| 16 |
+
help='Filter objects with aesthetic score lower than this value')
|
| 17 |
+
parser.add_argument('--model', type=str, default='dinov2_vitl14_reg_slat_enc_swin8_B_64l8_fp16',
|
| 18 |
+
help='Latent model to use')
|
| 19 |
+
parser.add_argument('--num_samples', type=int, default=50000,
|
| 20 |
+
help='Number of samples to use for calculating stats')
|
| 21 |
+
opt = parser.parse_args()
|
| 22 |
+
opt = edict(vars(opt))
|
| 23 |
+
|
| 24 |
+
# get file list
|
| 25 |
+
if os.path.exists(os.path.join(opt.output_dir, 'metadata.csv')):
|
| 26 |
+
metadata = pd.read_csv(os.path.join(opt.output_dir, 'metadata.csv'))
|
| 27 |
+
else:
|
| 28 |
+
raise ValueError('metadata.csv not found')
|
| 29 |
+
if opt.filter_low_aesthetic_score is not None:
|
| 30 |
+
metadata = metadata[metadata['aesthetic_score'] >= opt.filter_low_aesthetic_score]
|
| 31 |
+
metadata = metadata[metadata[f'latent_{opt.model}'] == True]
|
| 32 |
+
sha256s = metadata['sha256'].values
|
| 33 |
+
sha256s = np.random.choice(sha256s, min(opt.num_samples, len(sha256s)), replace=False)
|
| 34 |
+
|
| 35 |
+
# stats
|
| 36 |
+
means = []
|
| 37 |
+
mean2s = []
|
| 38 |
+
with ThreadPoolExecutor(max_workers=16) as executor, \
|
| 39 |
+
tqdm(total=len(sha256s), desc="Extracting features") as pbar:
|
| 40 |
+
def worker(sha256):
|
| 41 |
+
try:
|
| 42 |
+
feats = np.load(os.path.join(opt.output_dir, 'latents', opt.model, f'{sha256}.npz'))
|
| 43 |
+
feats = feats['feats']
|
| 44 |
+
means.append(feats.mean(axis=0))
|
| 45 |
+
mean2s.append((feats ** 2).mean(axis=0))
|
| 46 |
+
pbar.update()
|
| 47 |
+
except Exception as e:
|
| 48 |
+
print(f"Error extracting features for {sha256}: {e}")
|
| 49 |
+
pbar.update()
|
| 50 |
+
|
| 51 |
+
executor.map(worker, sha256s)
|
| 52 |
+
executor.shutdown(wait=True)
|
| 53 |
+
|
| 54 |
+
mean = np.array(means).mean(axis=0)
|
| 55 |
+
mean2 = np.array(mean2s).mean(axis=0)
|
| 56 |
+
std = np.sqrt(mean2 - mean ** 2)
|
| 57 |
+
|
| 58 |
+
print('mean:', mean)
|
| 59 |
+
print('std:', std)
|
| 60 |
+
|
| 61 |
+
with open(os.path.join(opt.output_dir, 'latents', opt.model, 'stats.json'), 'w') as f:
|
| 62 |
+
json.dump({
|
| 63 |
+
'mean': mean.tolist(),
|
| 64 |
+
'std': std.tolist(),
|
| 65 |
+
}, f, indent=4)
|
| 66 |
+
|
OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/utils.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import *
|
| 2 |
+
import hashlib
|
| 3 |
+
import numpy as np
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def get_file_hash(file: str) -> str:
|
| 7 |
+
sha256 = hashlib.sha256()
|
| 8 |
+
# Read the file from the path
|
| 9 |
+
with open(file, "rb") as f:
|
| 10 |
+
# Update the hash with the file content
|
| 11 |
+
for byte_block in iter(lambda: f.read(4096), b""):
|
| 12 |
+
sha256.update(byte_block)
|
| 13 |
+
return sha256.hexdigest()
|
| 14 |
+
|
| 15 |
+
# ===============LOW DISCREPANCY SEQUENCES================
|
| 16 |
+
|
| 17 |
+
PRIMES = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53]
|
| 18 |
+
|
| 19 |
+
def radical_inverse(base, n):
|
| 20 |
+
val = 0
|
| 21 |
+
inv_base = 1.0 / base
|
| 22 |
+
inv_base_n = inv_base
|
| 23 |
+
while n > 0:
|
| 24 |
+
digit = n % base
|
| 25 |
+
val += digit * inv_base_n
|
| 26 |
+
n //= base
|
| 27 |
+
inv_base_n *= inv_base
|
| 28 |
+
return val
|
| 29 |
+
|
| 30 |
+
def halton_sequence(dim, n):
|
| 31 |
+
return [radical_inverse(PRIMES[dim], n) for dim in range(dim)]
|
| 32 |
+
|
| 33 |
+
def hammersley_sequence(dim, n, num_samples):
|
| 34 |
+
return [n / num_samples] + halton_sequence(dim - 1, n)
|
| 35 |
+
|
| 36 |
+
def sphere_hammersley_sequence(n, num_samples, offset=(0, 0)):
|
| 37 |
+
u, v = hammersley_sequence(2, n, num_samples)
|
| 38 |
+
u += offset[0] / num_samples
|
| 39 |
+
v += offset[1]
|
| 40 |
+
u = 2 * u if u < 0.25 else 2 / 3 * u + 1 / 3
|
| 41 |
+
theta = np.arccos(1 - 2 * u) - np.pi / 2
|
| 42 |
+
phi = v * 2 * np.pi
|
| 43 |
+
return [phi, theta]
|
OVOW/engine/oneposeviagen/Amodal3R/dataset_toolkits/voxelize.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import copy
|
| 3 |
+
import sys
|
| 4 |
+
import importlib
|
| 5 |
+
import argparse
|
| 6 |
+
import pandas as pd
|
| 7 |
+
from easydict import EasyDict as edict
|
| 8 |
+
from functools import partial
|
| 9 |
+
import numpy as np
|
| 10 |
+
import open3d as o3d
|
| 11 |
+
import utils3d
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def _voxelize(file, sha256, output_dir):
|
| 15 |
+
mesh = o3d.io.read_triangle_mesh(os.path.join(output_dir, 'renders', sha256, 'mesh.ply'))
|
| 16 |
+
# clamp vertices to the range [-0.5, 0.5]
|
| 17 |
+
vertices = np.clip(np.asarray(mesh.vertices), -0.5 + 1e-6, 0.5 - 1e-6)
|
| 18 |
+
mesh.vertices = o3d.utility.Vector3dVector(vertices)
|
| 19 |
+
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))
|
| 20 |
+
vertices = np.array([voxel.grid_index for voxel in voxel_grid.get_voxels()])
|
| 21 |
+
assert np.all(vertices >= 0) and np.all(vertices < 64), "Some vertices are out of bounds"
|
| 22 |
+
vertices = (vertices + 0.5) / 64 - 0.5
|
| 23 |
+
utils3d.io.write_ply(os.path.join(output_dir, 'voxels', f'{sha256}.ply'), vertices)
|
| 24 |
+
return {'sha256': sha256, 'voxelized': True, 'num_voxels': len(vertices)}
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
if __name__ == '__main__':
|
| 28 |
+
dataset_utils = importlib.import_module(f'datasets.{sys.argv[1]}')
|
| 29 |
+
|
| 30 |
+
parser = argparse.ArgumentParser()
|
| 31 |
+
parser.add_argument('--output_dir', type=str, required=True,
|
| 32 |
+
help='Directory to save the metadata')
|
| 33 |
+
parser.add_argument('--filter_low_aesthetic_score', type=float, default=None,
|
| 34 |
+
help='Filter objects with aesthetic score lower than this value')
|
| 35 |
+
parser.add_argument('--instances', type=str, default=None,
|
| 36 |
+
help='Instances to process')
|
| 37 |
+
parser.add_argument('--num_views', type=int, default=150,
|
| 38 |
+
help='Number of views to render')
|
| 39 |
+
dataset_utils.add_args(parser)
|
| 40 |
+
parser.add_argument('--rank', type=int, default=0)
|
| 41 |
+
parser.add_argument('--world_size', type=int, default=1)
|
| 42 |
+
parser.add_argument('--max_workers', type=int, default=None)
|
| 43 |
+
opt = parser.parse_args(sys.argv[2:])
|
| 44 |
+
opt = edict(vars(opt))
|
| 45 |
+
|
| 46 |
+
os.makedirs(os.path.join(opt.output_dir, 'voxels'), exist_ok=True)
|
| 47 |
+
|
| 48 |
+
# get file list
|
| 49 |
+
if not os.path.exists(os.path.join(opt.output_dir, 'metadata.csv')):
|
| 50 |
+
raise ValueError('metadata.csv not found')
|
| 51 |
+
metadata = pd.read_csv(os.path.join(opt.output_dir, 'metadata.csv'))
|
| 52 |
+
if opt.instances is None:
|
| 53 |
+
if opt.filter_low_aesthetic_score is not None:
|
| 54 |
+
metadata = metadata[metadata['aesthetic_score'] >= opt.filter_low_aesthetic_score]
|
| 55 |
+
if 'rendered' not in metadata.columns:
|
| 56 |
+
raise ValueError('metadata.csv does not have "rendered" column, please run "build_metadata.py" first')
|
| 57 |
+
metadata = metadata[metadata['rendered'] == True]
|
| 58 |
+
if 'voxelized' in metadata.columns:
|
| 59 |
+
metadata = metadata[metadata['voxelized'] == False]
|
| 60 |
+
else:
|
| 61 |
+
if os.path.exists(opt.instances):
|
| 62 |
+
with open(opt.instances, 'r') as f:
|
| 63 |
+
instances = f.read().splitlines()
|
| 64 |
+
else:
|
| 65 |
+
instances = opt.instances.split(',')
|
| 66 |
+
metadata = metadata[metadata['sha256'].isin(instances)]
|
| 67 |
+
|
| 68 |
+
start = len(metadata) * opt.rank // opt.world_size
|
| 69 |
+
end = len(metadata) * (opt.rank + 1) // opt.world_size
|
| 70 |
+
metadata = metadata[start:end]
|
| 71 |
+
records = []
|
| 72 |
+
|
| 73 |
+
# filter out objects that are already processed
|
| 74 |
+
for sha256 in copy.copy(metadata['sha256'].values):
|
| 75 |
+
if os.path.exists(os.path.join(opt.output_dir, 'voxels', f'{sha256}.ply')):
|
| 76 |
+
pts = utils3d.io.read_ply(os.path.join(opt.output_dir, 'voxels', f'{sha256}.ply'))[0]
|
| 77 |
+
records.append({'sha256': sha256, 'voxelized': True, 'num_voxels': len(pts)})
|
| 78 |
+
metadata = metadata[metadata['sha256'] != sha256]
|
| 79 |
+
|
| 80 |
+
print(f'Processing {len(metadata)} objects...')
|
| 81 |
+
|
| 82 |
+
# process objects
|
| 83 |
+
func = partial(_voxelize, output_dir=opt.output_dir)
|
| 84 |
+
voxelized = dataset_utils.foreach_instance(metadata, opt.output_dir, func, max_workers=opt.max_workers, desc='Voxelizing')
|
| 85 |
+
voxelized = pd.concat([voxelized, pd.DataFrame.from_records(records)])
|
| 86 |
+
voxelized.to_csv(os.path.join(opt.output_dir, f'voxelized_{opt.rank}.csv'), index=False)
|
OVOW/engine/oneposeviagen/Amodal3R/dit/diffusion_slat.py
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch.nn as nn
|
| 2 |
+
import torch
|
| 3 |
+
import numpy as np
|
| 4 |
+
from amodal3r.modules.sparse import SparseTensor
|
| 5 |
+
|
| 6 |
+
def get_betas(schedule_type, b_start, b_end, time_num):
|
| 7 |
+
if schedule_type == 'linear':
|
| 8 |
+
betas = np.linspace(b_start, b_end, time_num)
|
| 9 |
+
elif schedule_type == 'warm0.1':
|
| 10 |
+
|
| 11 |
+
betas = b_end * np.ones(time_num, dtype=np.float64)
|
| 12 |
+
warmup_time = int(time_num * 0.1)
|
| 13 |
+
betas[:warmup_time] = np.linspace(b_start, b_end, warmup_time, dtype=np.float64)
|
| 14 |
+
elif schedule_type == 'warm0.2':
|
| 15 |
+
|
| 16 |
+
betas = b_end * np.ones(time_num, dtype=np.float64)
|
| 17 |
+
warmup_time = int(time_num * 0.2)
|
| 18 |
+
betas[:warmup_time] = np.linspace(b_start, b_end, warmup_time, dtype=np.float64)
|
| 19 |
+
elif schedule_type == 'warm0.5':
|
| 20 |
+
|
| 21 |
+
betas = b_end * np.ones(time_num, dtype=np.float64)
|
| 22 |
+
warmup_time = int(time_num * 0.5)
|
| 23 |
+
betas[:warmup_time] = np.linspace(b_start, b_end, warmup_time, dtype=np.float64)
|
| 24 |
+
else:
|
| 25 |
+
raise NotImplementedError(schedule_type)
|
| 26 |
+
return betas
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class GaussianDiffusion:
|
| 30 |
+
def __init__(self,betas, loss_type, model_mean_type, model_var_type):
|
| 31 |
+
self.loss_type = loss_type
|
| 32 |
+
self.model_mean_type = model_mean_type
|
| 33 |
+
self.model_var_type = model_var_type
|
| 34 |
+
assert isinstance(betas, np.ndarray)
|
| 35 |
+
self.np_betas = betas = betas.astype(np.float64) # computations here in float64 for accuracy
|
| 36 |
+
assert (betas > 0).all() and (betas <= 1).all()
|
| 37 |
+
timesteps, = betas.shape
|
| 38 |
+
self.num_timesteps = int(timesteps)
|
| 39 |
+
|
| 40 |
+
# initialize twice the actual length so we can keep running for eval
|
| 41 |
+
# betas = np.concatenate([betas, np.full_like(betas[:int(0.2*len(betas))], betas[-1])])
|
| 42 |
+
|
| 43 |
+
alphas = 1. - betas
|
| 44 |
+
alphas_cumprod = torch.from_numpy(np.cumprod(alphas, axis=0)).float()
|
| 45 |
+
alphas_cumprod_prev = torch.from_numpy(np.append(1., alphas_cumprod[:-1])).float()
|
| 46 |
+
|
| 47 |
+
self.betas = torch.from_numpy(betas).float()
|
| 48 |
+
self.alphas_cumprod = alphas_cumprod.float()
|
| 49 |
+
self.alphas_cumprod_prev = alphas_cumprod_prev.float()
|
| 50 |
+
|
| 51 |
+
# calculations for diffusion q(x_t | x_{t-1}) and others
|
| 52 |
+
self.sqrt_alphas_cumprod = torch.sqrt(alphas_cumprod).float()
|
| 53 |
+
self.sqrt_one_minus_alphas_cumprod = torch.sqrt(1. - alphas_cumprod).float()
|
| 54 |
+
self.log_one_minus_alphas_cumprod = torch.log(1. - alphas_cumprod).float()
|
| 55 |
+
self.sqrt_recip_alphas_cumprod = torch.sqrt(1. / alphas_cumprod).float()
|
| 56 |
+
self.sqrt_recipm1_alphas_cumprod = torch.sqrt(1. / alphas_cumprod - 1).float()
|
| 57 |
+
|
| 58 |
+
betas = torch.from_numpy(betas).float()
|
| 59 |
+
alphas = torch.from_numpy(alphas).float()
|
| 60 |
+
# calculations for posterior q(x_{t-1} | x_t, x_0)
|
| 61 |
+
posterior_variance = betas * (1. - alphas_cumprod_prev) / (1. - alphas_cumprod)
|
| 62 |
+
# above: equal to 1. / (1. / (1. - alpha_cumprod_tm1) + alpha_t / beta_t)
|
| 63 |
+
self.posterior_variance = posterior_variance
|
| 64 |
+
# below: log calculation clipped because the posterior variance is 0 at the beginning of the diffusion chain
|
| 65 |
+
self.posterior_log_variance_clipped = torch.log(torch.max(posterior_variance, 1e-20 * torch.ones_like(posterior_variance)))
|
| 66 |
+
self.posterior_mean_coef1 = betas * torch.sqrt(alphas_cumprod_prev) / (1. - alphas_cumprod)
|
| 67 |
+
self.posterior_mean_coef2 = (1. - alphas_cumprod_prev) * torch.sqrt(alphas) / (1. - alphas_cumprod)
|
| 68 |
+
|
| 69 |
+
self.sigma_min = 1e-5
|
| 70 |
+
|
| 71 |
+
@staticmethod
|
| 72 |
+
def _extract(a, t, x_shape):
|
| 73 |
+
"""
|
| 74 |
+
Extract some coefficients at specified timesteps,
|
| 75 |
+
then reshape to [batch_size, 1, 1, 1, 1, ...] for broadcasting purposes.
|
| 76 |
+
"""
|
| 77 |
+
bs, = t.shape
|
| 78 |
+
assert x_shape[0] == bs
|
| 79 |
+
out = torch.gather(a, 0, t)
|
| 80 |
+
assert out.shape == torch.Size([bs])
|
| 81 |
+
return torch.reshape(out, [bs] + ((len(x_shape) - 1) * [1]))
|
| 82 |
+
|
| 83 |
+
def q_mean_variance(self, x_start, t):
|
| 84 |
+
mean = self._extract(self.sqrt_alphas_cumprod.to(x_start.device), t, x_start.shape) * x_start
|
| 85 |
+
variance = self._extract(1. - self.alphas_cumprod.to(x_start.device), t, x_start.shape)
|
| 86 |
+
log_variance = self._extract(self.log_one_minus_alphas_cumprod.to(x_start.device), t, x_start.shape)
|
| 87 |
+
return mean, variance, log_variance
|
| 88 |
+
|
| 89 |
+
def q_sample(self, x_start, t, noise=None):
|
| 90 |
+
"""
|
| 91 |
+
Diffuse the data (t == 0 means diffused for 1 step)
|
| 92 |
+
"""
|
| 93 |
+
if noise is None:
|
| 94 |
+
noise = torch.randn(x_start.shape, device=x_start.device)
|
| 95 |
+
assert noise.shape == x_start.shape
|
| 96 |
+
return (
|
| 97 |
+
self._extract(self.sqrt_alphas_cumprod.to(x_start.device), t, x_start.shape) * x_start +
|
| 98 |
+
self._extract(self.sqrt_one_minus_alphas_cumprod.to(x_start.device), t, x_start.shape) * noise
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
def q_sample_linear(self, x_start, t, noise=None):
|
| 102 |
+
"""
|
| 103 |
+
x_t = (1 - t) * x0 + t * noise
|
| 104 |
+
"""
|
| 105 |
+
if noise is None:
|
| 106 |
+
noise = torch.randn_like(x_start)
|
| 107 |
+
t_shape = [x_start.shape[0]] + [1] * (len(x_start.shape) - 1)
|
| 108 |
+
t = t.view(*t_shape)
|
| 109 |
+
return (1 - t) * x_start + t * noise
|
| 110 |
+
|
| 111 |
+
def _predict_xstart_from_eps(self, x_t, t, eps):
|
| 112 |
+
assert x_t.shape == eps.shape
|
| 113 |
+
return (
|
| 114 |
+
self._extract(self.sqrt_recip_alphas_cumprod.to(x_t.device), t, x_t.shape) * x_t -
|
| 115 |
+
self._extract(self.sqrt_recipm1_alphas_cumprod.to(x_t.device), t, x_t.shape) * eps
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
'''losses'''
|
| 121 |
+
|
| 122 |
+
def p_losses(self, denoise_fn, data_start, t, noise=None, y=None, multi_t=False):
|
| 123 |
+
"""
|
| 124 |
+
Training loss calculation
|
| 125 |
+
"""
|
| 126 |
+
# print(data_start.shape)
|
| 127 |
+
if multi_t:
|
| 128 |
+
B = len(data_start['feats'])
|
| 129 |
+
assert t.shape == torch.Size([B])
|
| 130 |
+
|
| 131 |
+
noise, data_feats_t = [], []
|
| 132 |
+
for idx, feat in enumerate(data_start['feats']):
|
| 133 |
+
noise_single = torch.randn(feat.shape, dtype=feat.dtype, device=feat.device)
|
| 134 |
+
noise.append(noise_single)
|
| 135 |
+
assert noise_single.shape == feat.shape and noise_single.dtype == feat.dtype
|
| 136 |
+
data_feat_t = self.q_sample_linear(x_start=feat.unsqueeze(0), t=t[idx:idx+1], noise=noise_single.unsqueeze(0))
|
| 137 |
+
data_feats_t.append(data_feat_t.squeeze(0))
|
| 138 |
+
data_feats_t = torch.cat(data_feats_t, dim=0)
|
| 139 |
+
data_coords_t = torch.cat(data_start['coords'], dim=0)
|
| 140 |
+
|
| 141 |
+
data_t = SparseTensor(
|
| 142 |
+
feats=data_feats_t.half().contiguous(),
|
| 143 |
+
coords=data_coords_t.contiguous()
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
# predict the noise instead of x_start. seems to be weighted naturally like SNR
|
| 147 |
+
eps_recon = denoise_fn(data_t, t, y).feats
|
| 148 |
+
target = torch.cat(noise, dim=0) - torch.cat(data_start['feats'], dim=0)
|
| 149 |
+
losses = ((eps_recon - target)**2).mean()
|
| 150 |
+
|
| 151 |
+
# assert losses.shape == torch.Size([B])
|
| 152 |
+
return losses, {'data_t': data_t, 'eps_recon': eps_recon}
|
| 153 |
+
else:
|
| 154 |
+
B = 1
|
| 155 |
+
assert t.shape == torch.Size([B])
|
| 156 |
+
|
| 157 |
+
if noise is None:
|
| 158 |
+
for idx, feat in enumerate(data_start['feats']):
|
| 159 |
+
noise_single = torch.randn(feat.shape, dtype=feat.dtype, device=feat.device)
|
| 160 |
+
noises.append(noise_single)
|
| 161 |
+
noise = torch.cat(noises, dim=0)
|
| 162 |
+
|
| 163 |
+
data_start_sp = SparseTensor(
|
| 164 |
+
feats=torch.cat(data_start['feats'], dim=0).contiguous(),
|
| 165 |
+
coords=torch.cat(data_start['coords'], dim=0).contiguous()
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
assert noise.shape == data_start_sp.feats.shape and noise.dtype == data_start_sp.feats.dtype
|
| 169 |
+
|
| 170 |
+
data_t_feats = self.q_sample_linear(x_start=data_start_sp.feats.unsqueeze(0), t=t, noise=noise.unsqueeze(0))
|
| 171 |
+
data_t = SparseTensor(
|
| 172 |
+
feats=data_t_feats.squeeze(0).contiguous(),
|
| 173 |
+
coords=data_start_sp.coords.contiguous()
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
eps_recon = denoise_fn(data_t, t, y).feats
|
| 177 |
+
target = noise - torch.cat(data_start['feats'], dim=0)
|
| 178 |
+
losses = ((eps_recon - target)**2).mean()
|
| 179 |
+
|
| 180 |
+
# assert losses.shape == torch.Size([B])
|
| 181 |
+
return losses, {'data_t': data_t, 'eps_recon': eps_recon}
|
OVOW/engine/oneposeviagen/Amodal3R/dit/diffusion_ss.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import numpy as np
|
| 3 |
+
|
| 4 |
+
def get_betas(schedule_type, b_start, b_end, time_num):
|
| 5 |
+
if schedule_type == 'linear':
|
| 6 |
+
betas = np.linspace(b_start, b_end, time_num)
|
| 7 |
+
elif schedule_type == 'warm0.1':
|
| 8 |
+
|
| 9 |
+
betas = b_end * np.ones(time_num, dtype=np.float64)
|
| 10 |
+
warmup_time = int(time_num * 0.1)
|
| 11 |
+
betas[:warmup_time] = np.linspace(b_start, b_end, warmup_time, dtype=np.float64)
|
| 12 |
+
elif schedule_type == 'warm0.2':
|
| 13 |
+
|
| 14 |
+
betas = b_end * np.ones(time_num, dtype=np.float64)
|
| 15 |
+
warmup_time = int(time_num * 0.2)
|
| 16 |
+
betas[:warmup_time] = np.linspace(b_start, b_end, warmup_time, dtype=np.float64)
|
| 17 |
+
elif schedule_type == 'warm0.5':
|
| 18 |
+
|
| 19 |
+
betas = b_end * np.ones(time_num, dtype=np.float64)
|
| 20 |
+
warmup_time = int(time_num * 0.5)
|
| 21 |
+
betas[:warmup_time] = np.linspace(b_start, b_end, warmup_time, dtype=np.float64)
|
| 22 |
+
else:
|
| 23 |
+
raise NotImplementedError(schedule_type)
|
| 24 |
+
return betas
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class GaussianDiffusion:
|
| 28 |
+
def __init__(self,betas, loss_type, model_mean_type, model_var_type):
|
| 29 |
+
self.loss_type = loss_type
|
| 30 |
+
self.model_mean_type = model_mean_type
|
| 31 |
+
self.model_var_type = model_var_type
|
| 32 |
+
assert isinstance(betas, np.ndarray)
|
| 33 |
+
self.np_betas = betas = betas.astype(np.float64) # computations here in float64 for accuracy
|
| 34 |
+
assert (betas > 0).all() and (betas <= 1).all()
|
| 35 |
+
timesteps, = betas.shape
|
| 36 |
+
self.num_timesteps = int(timesteps)
|
| 37 |
+
|
| 38 |
+
# initialize twice the actual length so we can keep running for eval
|
| 39 |
+
# betas = np.concatenate([betas, np.full_like(betas[:int(0.2*len(betas))], betas[-1])])
|
| 40 |
+
|
| 41 |
+
alphas = 1. - betas
|
| 42 |
+
alphas_cumprod = torch.from_numpy(np.cumprod(alphas, axis=0)).float()
|
| 43 |
+
alphas_cumprod_prev = torch.from_numpy(np.append(1., alphas_cumprod[:-1])).float()
|
| 44 |
+
|
| 45 |
+
self.betas = torch.from_numpy(betas).float()
|
| 46 |
+
self.alphas_cumprod = alphas_cumprod.float()
|
| 47 |
+
self.alphas_cumprod_prev = alphas_cumprod_prev.float()
|
| 48 |
+
|
| 49 |
+
# calculations for diffusion q(x_t | x_{t-1}) and others
|
| 50 |
+
self.sqrt_alphas_cumprod = torch.sqrt(alphas_cumprod).float()
|
| 51 |
+
self.sqrt_one_minus_alphas_cumprod = torch.sqrt(1. - alphas_cumprod).float()
|
| 52 |
+
self.log_one_minus_alphas_cumprod = torch.log(1. - alphas_cumprod).float()
|
| 53 |
+
self.sqrt_recip_alphas_cumprod = torch.sqrt(1. / alphas_cumprod).float()
|
| 54 |
+
self.sqrt_recipm1_alphas_cumprod = torch.sqrt(1. / alphas_cumprod - 1).float()
|
| 55 |
+
|
| 56 |
+
betas = torch.from_numpy(betas).float()
|
| 57 |
+
alphas = torch.from_numpy(alphas).float()
|
| 58 |
+
# calculations for posterior q(x_{t-1} | x_t, x_0)
|
| 59 |
+
posterior_variance = betas * (1. - alphas_cumprod_prev) / (1. - alphas_cumprod)
|
| 60 |
+
# above: equal to 1. / (1. / (1. - alpha_cumprod_tm1) + alpha_t / beta_t)
|
| 61 |
+
self.posterior_variance = posterior_variance
|
| 62 |
+
# below: log calculation clipped because the posterior variance is 0 at the beginning of the diffusion chain
|
| 63 |
+
self.posterior_log_variance_clipped = torch.log(torch.max(posterior_variance, 1e-20 * torch.ones_like(posterior_variance)))
|
| 64 |
+
self.posterior_mean_coef1 = betas * torch.sqrt(alphas_cumprod_prev) / (1. - alphas_cumprod)
|
| 65 |
+
self.posterior_mean_coef2 = (1. - alphas_cumprod_prev) * torch.sqrt(alphas) / (1. - alphas_cumprod)
|
| 66 |
+
|
| 67 |
+
@staticmethod
|
| 68 |
+
def _extract(a, t, x_shape):
|
| 69 |
+
"""
|
| 70 |
+
Extract some coefficients at specified timesteps,
|
| 71 |
+
then reshape to [batch_size, 1, 1, 1, 1, ...] for broadcasting purposes.
|
| 72 |
+
"""
|
| 73 |
+
bs, = t.shape
|
| 74 |
+
assert x_shape[0] == bs
|
| 75 |
+
out = torch.gather(a, 0, t)
|
| 76 |
+
assert out.shape == torch.Size([bs])
|
| 77 |
+
return torch.reshape(out, [bs] + ((len(x_shape) - 1) * [1]))
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def q_mean_variance(self, x_start, t):
|
| 81 |
+
mean = self._extract(self.sqrt_alphas_cumprod.to(x_start.device), t, x_start.shape) * x_start
|
| 82 |
+
variance = self._extract(1. - self.alphas_cumprod.to(x_start.device), t, x_start.shape)
|
| 83 |
+
log_variance = self._extract(self.log_one_minus_alphas_cumprod.to(x_start.device), t, x_start.shape)
|
| 84 |
+
return mean, variance, log_variance
|
| 85 |
+
|
| 86 |
+
def q_sample(self, x_start, t, noise=None):
|
| 87 |
+
"""
|
| 88 |
+
Diffuse the data (t == 0 means diffused for 1 step)
|
| 89 |
+
"""
|
| 90 |
+
if noise is None:
|
| 91 |
+
noise = torch.randn(x_start.shape, device=x_start.device)
|
| 92 |
+
assert noise.shape == x_start.shape
|
| 93 |
+
return (
|
| 94 |
+
self._extract(self.sqrt_alphas_cumprod.to(x_start.device), t, x_start.shape) * x_start +
|
| 95 |
+
self._extract(self.sqrt_one_minus_alphas_cumprod.to(x_start.device), t, x_start.shape) * noise
|
| 96 |
+
)
|
| 97 |
+
|
| 98 |
+
def q_sample_linear(self, x_start, t, noise=None):
|
| 99 |
+
"""
|
| 100 |
+
Linearly interpolate x_t = (1 - t) * x_0 + t * ϵ
|
| 101 |
+
"""
|
| 102 |
+
if noise is None:
|
| 103 |
+
noise = torch.randn(x_start.shape, device=x_start.device)
|
| 104 |
+
assert noise.shape == x_start.shape
|
| 105 |
+
|
| 106 |
+
t = t.view(-1, *([1] * (len(x_start.shape) - 1))) # (B, 1, 1, ...)
|
| 107 |
+
|
| 108 |
+
x_t = (1 - t) * x_start + t * noise
|
| 109 |
+
return x_t
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
'''losses'''
|
| 113 |
+
|
| 114 |
+
def p_losses(self, denoise_fn, data_start, t, noise=None, y=None):
|
| 115 |
+
"""
|
| 116 |
+
Training loss calculation
|
| 117 |
+
"""
|
| 118 |
+
B = data_start.shape[0]
|
| 119 |
+
assert t.shape == torch.Size([B])
|
| 120 |
+
|
| 121 |
+
if noise is None:
|
| 122 |
+
noise = torch.randn(data_start.shape, dtype=data_start.dtype, device=data_start.device)
|
| 123 |
+
assert noise.shape == data_start.shape and noise.dtype == data_start.dtype
|
| 124 |
+
|
| 125 |
+
data_t = self.q_sample_linear(x_start=data_start, t=t, noise=noise)
|
| 126 |
+
|
| 127 |
+
eps_recon = denoise_fn(data_t, t, y)
|
| 128 |
+
assert data_t.shape == data_start.shape
|
| 129 |
+
# assert eps_recon.shape == torch.Size([B, N, 3])
|
| 130 |
+
assert eps_recon.shape == data_start.shape
|
| 131 |
+
target = noise - data_start
|
| 132 |
+
losses = ((eps_recon - target)**2).mean(dim=list(range(1, len(data_start.shape))))
|
| 133 |
+
|
| 134 |
+
assert losses.shape == torch.Size([B])
|
| 135 |
+
return losses, {'data_t': data_t, 'eps_recon': eps_recon}
|
OVOW/engine/oneposeviagen/Amodal3R/dit/utils.py
ADDED
|
@@ -0,0 +1,881 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# https://raw.githubusercontent.com/facebookresearch/dino/main/utils.py
|
| 2 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""
|
| 16 |
+
Misc functions.
|
| 17 |
+
|
| 18 |
+
Mostly copy-paste from torchvision references or other public repos like DETR:
|
| 19 |
+
https://github.com/facebookresearch/detr/blob/master/util/misc.py
|
| 20 |
+
"""
|
| 21 |
+
import os
|
| 22 |
+
import sys
|
| 23 |
+
import time
|
| 24 |
+
import math
|
| 25 |
+
import random
|
| 26 |
+
import datetime
|
| 27 |
+
import subprocess
|
| 28 |
+
from collections import defaultdict, deque
|
| 29 |
+
|
| 30 |
+
import numpy as np
|
| 31 |
+
import torch
|
| 32 |
+
from torch import nn
|
| 33 |
+
import torch.distributed as dist
|
| 34 |
+
from PIL import ImageFilter, ImageOps
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class GaussianBlur(object):
|
| 38 |
+
"""
|
| 39 |
+
Apply Gaussian Blur to the PIL image.
|
| 40 |
+
"""
|
| 41 |
+
def __init__(self, p=0.5, radius_min=0.1, radius_max=2.):
|
| 42 |
+
self.prob = p
|
| 43 |
+
self.radius_min = radius_min
|
| 44 |
+
self.radius_max = radius_max
|
| 45 |
+
|
| 46 |
+
def __call__(self, img):
|
| 47 |
+
do_it = random.random() <= self.prob
|
| 48 |
+
if not do_it:
|
| 49 |
+
return img
|
| 50 |
+
|
| 51 |
+
return img.filter(
|
| 52 |
+
ImageFilter.GaussianBlur(
|
| 53 |
+
radius=random.uniform(self.radius_min, self.radius_max)))
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class Solarization(object):
|
| 57 |
+
"""
|
| 58 |
+
Apply Solarization to the PIL image.
|
| 59 |
+
"""
|
| 60 |
+
def __init__(self, p):
|
| 61 |
+
self.p = p
|
| 62 |
+
|
| 63 |
+
def __call__(self, img):
|
| 64 |
+
if random.random() < self.p:
|
| 65 |
+
return ImageOps.solarize(img)
|
| 66 |
+
else:
|
| 67 |
+
return img
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def load_pretrained_weights(model, pretrained_weights, checkpoint_key,
|
| 71 |
+
model_name, patch_size):
|
| 72 |
+
if os.path.isfile(pretrained_weights):
|
| 73 |
+
state_dict = torch.load(pretrained_weights, map_location="cpu")
|
| 74 |
+
if checkpoint_key is not None and checkpoint_key in state_dict:
|
| 75 |
+
print(f"Take key {checkpoint_key} in provided checkpoint dict")
|
| 76 |
+
state_dict = state_dict[checkpoint_key]
|
| 77 |
+
# remove `module.` prefix
|
| 78 |
+
state_dict = {
|
| 79 |
+
k.replace("module.", ""): v
|
| 80 |
+
for k, v in state_dict.items()
|
| 81 |
+
}
|
| 82 |
+
# remove `backbone.` prefix induced by multicrop wrapper
|
| 83 |
+
state_dict = {
|
| 84 |
+
k.replace("backbone.", ""): v
|
| 85 |
+
for k, v in state_dict.items()
|
| 86 |
+
}
|
| 87 |
+
msg = model.load_state_dict(state_dict, strict=False)
|
| 88 |
+
print('Pretrained weights found at {} and loaded with msg: {}'.format(
|
| 89 |
+
pretrained_weights, msg))
|
| 90 |
+
else:
|
| 91 |
+
print(
|
| 92 |
+
"Please use the `--pretrained_weights` argument to indicate the path of the checkpoint to evaluate."
|
| 93 |
+
)
|
| 94 |
+
url = None
|
| 95 |
+
if model_name == "vit_small" and patch_size == 16:
|
| 96 |
+
url = "dino_deitsmall16_pretrain/dino_deitsmall16_pretrain.pth"
|
| 97 |
+
elif model_name == "vit_small" and patch_size == 8:
|
| 98 |
+
url = "dino_deitsmall8_pretrain/dino_deitsmall8_pretrain.pth"
|
| 99 |
+
elif model_name == "vit_base" and patch_size == 16:
|
| 100 |
+
url = "dino_vitbase16_pretrain/dino_vitbase16_pretrain.pth"
|
| 101 |
+
elif model_name == "vit_base" and patch_size == 8:
|
| 102 |
+
url = "dino_vitbase8_pretrain/dino_vitbase8_pretrain.pth"
|
| 103 |
+
elif model_name == "xcit_small_12_p16":
|
| 104 |
+
url = "dino_xcit_small_12_p16_pretrain/dino_xcit_small_12_p16_pretrain.pth"
|
| 105 |
+
elif model_name == "xcit_small_12_p8":
|
| 106 |
+
url = "dino_xcit_small_12_p8_pretrain/dino_xcit_small_12_p8_pretrain.pth"
|
| 107 |
+
elif model_name == "xcit_medium_24_p16":
|
| 108 |
+
url = "dino_xcit_medium_24_p16_pretrain/dino_xcit_medium_24_p16_pretrain.pth"
|
| 109 |
+
elif model_name == "xcit_medium_24_p8":
|
| 110 |
+
url = "dino_xcit_medium_24_p8_pretrain/dino_xcit_medium_24_p8_pretrain.pth"
|
| 111 |
+
elif model_name == "resnet50":
|
| 112 |
+
url = "dino_resnet50_pretrain/dino_resnet50_pretrain.pth"
|
| 113 |
+
if url is not None:
|
| 114 |
+
print(
|
| 115 |
+
"Since no pretrained weights have been provided, we load the reference pretrained DINO weights."
|
| 116 |
+
)
|
| 117 |
+
state_dict = torch.hub.load_state_dict_from_url(
|
| 118 |
+
url="https://dl.fbaipublicfiles.com/dino/" + url)
|
| 119 |
+
model.load_state_dict(state_dict, strict=True)
|
| 120 |
+
else:
|
| 121 |
+
print(
|
| 122 |
+
"There is no reference weights available for this model => We use random weights."
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def load_pretrained_linear_weights(linear_classifier, model_name, patch_size):
|
| 127 |
+
url = None
|
| 128 |
+
if model_name == "vit_small" and patch_size == 16:
|
| 129 |
+
url = "dino_deitsmall16_pretrain/dino_deitsmall16_linearweights.pth"
|
| 130 |
+
elif model_name == "vit_small" and patch_size == 8:
|
| 131 |
+
url = "dino_deitsmall8_pretrain/dino_deitsmall8_linearweights.pth"
|
| 132 |
+
elif model_name == "vit_base" and patch_size == 16:
|
| 133 |
+
url = "dino_vitbase16_pretrain/dino_vitbase16_linearweights.pth"
|
| 134 |
+
elif model_name == "vit_base" and patch_size == 8:
|
| 135 |
+
url = "dino_vitbase8_pretrain/dino_vitbase8_linearweights.pth"
|
| 136 |
+
elif model_name == "resnet50":
|
| 137 |
+
url = "dino_resnet50_pretrain/dino_resnet50_linearweights.pth"
|
| 138 |
+
if url is not None:
|
| 139 |
+
print("We load the reference pretrained linear weights.")
|
| 140 |
+
state_dict = torch.hub.load_state_dict_from_url(
|
| 141 |
+
url="https://dl.fbaipublicfiles.com/dino/" + url)["state_dict"]
|
| 142 |
+
linear_classifier.load_state_dict(state_dict, strict=True)
|
| 143 |
+
else:
|
| 144 |
+
print("We use random linear weights.")
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def clip_gradients(model, clip):
|
| 148 |
+
norms = []
|
| 149 |
+
for name, p in model.named_parameters():
|
| 150 |
+
if p.grad is not None:
|
| 151 |
+
param_norm = p.grad.data.norm(2)
|
| 152 |
+
norms.append(param_norm.item())
|
| 153 |
+
clip_coef = clip / (param_norm + 1e-6)
|
| 154 |
+
if clip_coef < 1:
|
| 155 |
+
p.grad.data.mul_(clip_coef)
|
| 156 |
+
return norms
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def cancel_gradients_last_layer(epoch, model, freeze_last_layer):
|
| 160 |
+
if epoch >= freeze_last_layer:
|
| 161 |
+
return
|
| 162 |
+
for n, p in model.named_parameters():
|
| 163 |
+
if "last_layer" in n:
|
| 164 |
+
p.grad = None
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def restart_from_checkpoint(ckp_path, run_variables=None, **kwargs):
|
| 168 |
+
"""
|
| 169 |
+
Re-start from checkpoint
|
| 170 |
+
"""
|
| 171 |
+
if not os.path.isfile(ckp_path):
|
| 172 |
+
return
|
| 173 |
+
print("Found checkpoint at {}".format(ckp_path))
|
| 174 |
+
|
| 175 |
+
# open checkpoint file
|
| 176 |
+
checkpoint = torch.load(ckp_path, map_location="cpu")
|
| 177 |
+
|
| 178 |
+
# key is what to look for in the checkpoint file
|
| 179 |
+
# value is the object to load
|
| 180 |
+
# example: {'state_dict': model}
|
| 181 |
+
for key, value in kwargs.items():
|
| 182 |
+
if key in checkpoint and value is not None:
|
| 183 |
+
try:
|
| 184 |
+
msg = value.load_state_dict(checkpoint[key], strict=False)
|
| 185 |
+
print("=> loaded '{}' from checkpoint '{}' with msg {}".format(
|
| 186 |
+
key, ckp_path, msg))
|
| 187 |
+
except TypeError:
|
| 188 |
+
try:
|
| 189 |
+
msg = value.load_state_dict(checkpoint[key])
|
| 190 |
+
print("=> loaded '{}' from checkpoint: '{}'".format(
|
| 191 |
+
key, ckp_path))
|
| 192 |
+
except ValueError:
|
| 193 |
+
print(
|
| 194 |
+
"=> failed to load '{}' from checkpoint: '{}'".format(
|
| 195 |
+
key, ckp_path))
|
| 196 |
+
else:
|
| 197 |
+
print("=> key '{}' not found in checkpoint: '{}'".format(
|
| 198 |
+
key, ckp_path))
|
| 199 |
+
|
| 200 |
+
# re load variable important for the run
|
| 201 |
+
if run_variables is not None:
|
| 202 |
+
for var_name in run_variables:
|
| 203 |
+
if var_name in checkpoint:
|
| 204 |
+
run_variables[var_name] = checkpoint[var_name]
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def cosine_scheduler(base_value,
|
| 208 |
+
final_value,
|
| 209 |
+
epochs,
|
| 210 |
+
niter_per_ep,
|
| 211 |
+
warmup_epochs=0,
|
| 212 |
+
start_warmup_value=0):
|
| 213 |
+
warmup_schedule = np.array([])
|
| 214 |
+
warmup_iters = warmup_epochs * niter_per_ep
|
| 215 |
+
if warmup_epochs > 0:
|
| 216 |
+
warmup_schedule = np.linspace(start_warmup_value, base_value,
|
| 217 |
+
warmup_iters)
|
| 218 |
+
|
| 219 |
+
iters = np.arange(epochs * niter_per_ep - warmup_iters)
|
| 220 |
+
schedule = final_value + 0.5 * (base_value - final_value) * (
|
| 221 |
+
1 + np.cos(np.pi * iters / len(iters)))
|
| 222 |
+
|
| 223 |
+
schedule = np.concatenate((warmup_schedule, schedule))
|
| 224 |
+
assert len(schedule) == epochs * niter_per_ep
|
| 225 |
+
return schedule
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
def bool_flag(s):
|
| 229 |
+
"""
|
| 230 |
+
Parse boolean arguments from the command line.
|
| 231 |
+
"""
|
| 232 |
+
FALSY_STRINGS = {"off", "false", "0"}
|
| 233 |
+
TRUTHY_STRINGS = {"on", "true", "1"}
|
| 234 |
+
if s.lower() in FALSY_STRINGS:
|
| 235 |
+
return False
|
| 236 |
+
elif s.lower() in TRUTHY_STRINGS:
|
| 237 |
+
return True
|
| 238 |
+
else:
|
| 239 |
+
raise argparse.ArgumentTypeError("invalid value for a boolean flag")
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def fix_random_seeds(seed=31):
|
| 243 |
+
"""
|
| 244 |
+
Fix random seeds.
|
| 245 |
+
"""
|
| 246 |
+
torch.manual_seed(seed)
|
| 247 |
+
torch.cuda.manual_seed_all(seed)
|
| 248 |
+
np.random.seed(seed)
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
class SmoothedValue(object):
|
| 252 |
+
"""Track a series of values and provide access to smoothed values over a
|
| 253 |
+
window or the global series average.
|
| 254 |
+
"""
|
| 255 |
+
def __init__(self, window_size=20, fmt=None):
|
| 256 |
+
if fmt is None:
|
| 257 |
+
fmt = "{median:.6f} ({global_avg:.6f})"
|
| 258 |
+
self.deque = deque(maxlen=window_size)
|
| 259 |
+
self.total = 0.0
|
| 260 |
+
self.count = 0
|
| 261 |
+
self.fmt = fmt
|
| 262 |
+
|
| 263 |
+
def update(self, value, n=1):
|
| 264 |
+
self.deque.append(value)
|
| 265 |
+
self.count += n
|
| 266 |
+
self.total += value * n
|
| 267 |
+
|
| 268 |
+
def synchronize_between_processes(self):
|
| 269 |
+
"""
|
| 270 |
+
Warning: does not synchronize the deque!
|
| 271 |
+
"""
|
| 272 |
+
if not is_dist_avail_and_initialized():
|
| 273 |
+
return
|
| 274 |
+
t = torch.tensor([self.count, self.total],
|
| 275 |
+
dtype=torch.float64,
|
| 276 |
+
device='cuda')
|
| 277 |
+
dist.barrier()
|
| 278 |
+
dist.all_reduce(t)
|
| 279 |
+
t = t.tolist()
|
| 280 |
+
self.count = int(t[0])
|
| 281 |
+
self.total = t[1]
|
| 282 |
+
|
| 283 |
+
@property
|
| 284 |
+
def median(self):
|
| 285 |
+
d = torch.tensor(list(self.deque))
|
| 286 |
+
return d.median().item()
|
| 287 |
+
|
| 288 |
+
@property
|
| 289 |
+
def avg(self):
|
| 290 |
+
d = torch.tensor(list(self.deque), dtype=torch.float32)
|
| 291 |
+
return d.mean().item()
|
| 292 |
+
|
| 293 |
+
@property
|
| 294 |
+
def global_avg(self):
|
| 295 |
+
return self.total / self.count
|
| 296 |
+
|
| 297 |
+
@property
|
| 298 |
+
def max(self):
|
| 299 |
+
return max(self.deque)
|
| 300 |
+
|
| 301 |
+
@property
|
| 302 |
+
def value(self):
|
| 303 |
+
return self.deque[-1]
|
| 304 |
+
|
| 305 |
+
def __str__(self):
|
| 306 |
+
return self.fmt.format(median=self.median,
|
| 307 |
+
avg=self.avg,
|
| 308 |
+
global_avg=self.global_avg,
|
| 309 |
+
max=self.max,
|
| 310 |
+
value=self.value)
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
def reduce_dict(input_dict, average=True):
|
| 314 |
+
"""
|
| 315 |
+
Args:
|
| 316 |
+
input_dict (dict): all the values will be reduced
|
| 317 |
+
average (bool): whether to do average or sum
|
| 318 |
+
Reduce the values in the dictionary from all processes so that all processes
|
| 319 |
+
have the averaged results. Returns a dict with the same fields as
|
| 320 |
+
input_dict, after reduction.
|
| 321 |
+
"""
|
| 322 |
+
world_size = get_world_size()
|
| 323 |
+
if world_size < 2:
|
| 324 |
+
return input_dict
|
| 325 |
+
with torch.no_grad():
|
| 326 |
+
names = []
|
| 327 |
+
values = []
|
| 328 |
+
# sort the keys so that they are consistent across processes
|
| 329 |
+
for k in sorted(input_dict.keys()):
|
| 330 |
+
names.append(k)
|
| 331 |
+
values.append(input_dict[k])
|
| 332 |
+
values = torch.stack(values, dim=0)
|
| 333 |
+
dist.all_reduce(values)
|
| 334 |
+
if average:
|
| 335 |
+
values /= world_size
|
| 336 |
+
reduced_dict = {k: v for k, v in zip(names, values)}
|
| 337 |
+
return reduced_dict
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
class MetricLogger(object):
|
| 341 |
+
def __init__(self, delimiter="\t"):
|
| 342 |
+
self.meters = defaultdict(SmoothedValue)
|
| 343 |
+
self.delimiter = delimiter
|
| 344 |
+
|
| 345 |
+
def update(self, **kwargs):
|
| 346 |
+
for k, v in kwargs.items():
|
| 347 |
+
if isinstance(v, torch.Tensor):
|
| 348 |
+
v = v.item()
|
| 349 |
+
assert isinstance(v, (float, int))
|
| 350 |
+
self.meters[k].update(v)
|
| 351 |
+
|
| 352 |
+
def __getattr__(self, attr):
|
| 353 |
+
if attr in self.meters:
|
| 354 |
+
return self.meters[attr]
|
| 355 |
+
if attr in self.__dict__:
|
| 356 |
+
return self.__dict__[attr]
|
| 357 |
+
raise AttributeError("'{}' object has no attribute '{}'".format(
|
| 358 |
+
type(self).__name__, attr))
|
| 359 |
+
|
| 360 |
+
def __str__(self):
|
| 361 |
+
loss_str = []
|
| 362 |
+
for name, meter in self.meters.items():
|
| 363 |
+
loss_str.append("{}: {}".format(name, str(meter)))
|
| 364 |
+
return self.delimiter.join(loss_str)
|
| 365 |
+
|
| 366 |
+
def synchronize_between_processes(self):
|
| 367 |
+
for meter in self.meters.values():
|
| 368 |
+
meter.synchronize_between_processes()
|
| 369 |
+
|
| 370 |
+
def add_meter(self, name, meter):
|
| 371 |
+
self.meters[name] = meter
|
| 372 |
+
|
| 373 |
+
def log_every(self, iterable, print_freq, header=None):
|
| 374 |
+
i = 0
|
| 375 |
+
if not header:
|
| 376 |
+
header = ''
|
| 377 |
+
start_time = time.time()
|
| 378 |
+
end = time.time()
|
| 379 |
+
iter_time = SmoothedValue(fmt='{avg:.6f}')
|
| 380 |
+
data_time = SmoothedValue(fmt='{avg:.6f}')
|
| 381 |
+
space_fmt = ':' + str(len(str(len(iterable)))) + 'd'
|
| 382 |
+
if torch.cuda.is_available():
|
| 383 |
+
log_msg = self.delimiter.join([
|
| 384 |
+
header, '[{0' + space_fmt + '}/{1}]', 'eta: {eta}', '{meters}',
|
| 385 |
+
'time: {time}', 'data: {data}', 'max mem: {memory:.0f}'
|
| 386 |
+
])
|
| 387 |
+
else:
|
| 388 |
+
log_msg = self.delimiter.join([
|
| 389 |
+
header, '[{0' + space_fmt + '}/{1}]', 'eta: {eta}', '{meters}',
|
| 390 |
+
'time: {time}', 'data: {data}'
|
| 391 |
+
])
|
| 392 |
+
MB = 1024.0 * 1024.0
|
| 393 |
+
for obj in iterable:
|
| 394 |
+
data_time.update(time.time() - end)
|
| 395 |
+
yield obj
|
| 396 |
+
iter_time.update(time.time() - end)
|
| 397 |
+
if i % print_freq == 0 or i == len(iterable) - 1:
|
| 398 |
+
eta_seconds = iter_time.global_avg * (len(iterable) - i)
|
| 399 |
+
eta_string = str(datetime.timedelta(seconds=int(eta_seconds)))
|
| 400 |
+
if torch.cuda.is_available():
|
| 401 |
+
print(
|
| 402 |
+
log_msg.format(
|
| 403 |
+
i,
|
| 404 |
+
len(iterable),
|
| 405 |
+
eta=eta_string,
|
| 406 |
+
meters=str(self),
|
| 407 |
+
time=str(iter_time),
|
| 408 |
+
data=str(data_time),
|
| 409 |
+
memory=torch.cuda.max_memory_allocated() / MB))
|
| 410 |
+
else:
|
| 411 |
+
print(
|
| 412 |
+
log_msg.format(i,
|
| 413 |
+
len(iterable),
|
| 414 |
+
eta=eta_string,
|
| 415 |
+
meters=str(self),
|
| 416 |
+
time=str(iter_time),
|
| 417 |
+
data=str(data_time)))
|
| 418 |
+
i += 1
|
| 419 |
+
end = time.time()
|
| 420 |
+
total_time = time.time() - start_time
|
| 421 |
+
total_time_str = str(datetime.timedelta(seconds=int(total_time)))
|
| 422 |
+
print('{} Total time: {} ({:.6f} s / it)'.format(
|
| 423 |
+
header, total_time_str, total_time / len(iterable)))
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
def get_sha():
|
| 427 |
+
cwd = os.path.dirname(os.path.abspath(__file__))
|
| 428 |
+
|
| 429 |
+
def _run(command):
|
| 430 |
+
return subprocess.check_output(command,
|
| 431 |
+
cwd=cwd).decode('ascii').strip()
|
| 432 |
+
|
| 433 |
+
sha = 'N/A'
|
| 434 |
+
diff = "clean"
|
| 435 |
+
branch = 'N/A'
|
| 436 |
+
try:
|
| 437 |
+
sha = _run(['git', 'rev-parse', 'HEAD'])
|
| 438 |
+
subprocess.check_output(['git', 'diff'], cwd=cwd)
|
| 439 |
+
diff = _run(['git', 'diff-index', 'HEAD'])
|
| 440 |
+
diff = "has uncommited changes" if diff else "clean"
|
| 441 |
+
branch = _run(['git', 'rev-parse', '--abbrev-ref', 'HEAD'])
|
| 442 |
+
except Exception:
|
| 443 |
+
pass
|
| 444 |
+
message = f"sha: {sha}, status: {diff}, branch: {branch}"
|
| 445 |
+
return message
|
| 446 |
+
|
| 447 |
+
|
| 448 |
+
def is_dist_avail_and_initialized():
|
| 449 |
+
if not dist.is_available():
|
| 450 |
+
return False
|
| 451 |
+
if not dist.is_initialized():
|
| 452 |
+
return False
|
| 453 |
+
return True
|
| 454 |
+
|
| 455 |
+
|
| 456 |
+
def get_world_size():
|
| 457 |
+
if not is_dist_avail_and_initialized():
|
| 458 |
+
return 1
|
| 459 |
+
return dist.get_world_size()
|
| 460 |
+
|
| 461 |
+
|
| 462 |
+
def get_rank():
|
| 463 |
+
if not is_dist_avail_and_initialized():
|
| 464 |
+
return 0
|
| 465 |
+
return dist.get_rank()
|
| 466 |
+
|
| 467 |
+
|
| 468 |
+
def is_main_process():
|
| 469 |
+
return get_rank() == 0
|
| 470 |
+
|
| 471 |
+
|
| 472 |
+
def save_on_master(*args, **kwargs):
|
| 473 |
+
if is_main_process():
|
| 474 |
+
torch.save(*args, **kwargs)
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
def setup_for_distributed(is_master):
|
| 478 |
+
"""
|
| 479 |
+
This function disables printing when not in master process
|
| 480 |
+
"""
|
| 481 |
+
import builtins as __builtin__
|
| 482 |
+
builtin_print = __builtin__.print
|
| 483 |
+
|
| 484 |
+
def print(*args, **kwargs):
|
| 485 |
+
force = kwargs.pop('force', False)
|
| 486 |
+
if is_master or force:
|
| 487 |
+
builtin_print(*args, **kwargs)
|
| 488 |
+
|
| 489 |
+
__builtin__.print = print
|
| 490 |
+
|
| 491 |
+
|
| 492 |
+
def init_distributed_mode(args):
|
| 493 |
+
# launched with torch.distributed.launch
|
| 494 |
+
if 'RANK' in os.environ and 'WORLD_SIZE' in os.environ:
|
| 495 |
+
args.rank = int(os.environ["RANK"])
|
| 496 |
+
args.world_size = int(os.environ['WORLD_SIZE'])
|
| 497 |
+
args.gpu = int(os.environ['LOCAL_RANK'])
|
| 498 |
+
# launched with submitit on a slurm cluster
|
| 499 |
+
elif 'SLURM_PROCID' in os.environ:
|
| 500 |
+
args.rank = int(os.environ['SLURM_PROCID'])
|
| 501 |
+
args.gpu = args.rank % torch.cuda.device_count()
|
| 502 |
+
# launched naively with `python main_dino.py`
|
| 503 |
+
# we manually add MASTER_ADDR and MASTER_PORT to env variables
|
| 504 |
+
elif torch.cuda.is_available():
|
| 505 |
+
print('Will run the code on one GPU.')
|
| 506 |
+
args.rank, args.gpu, args.world_size = 0, 0, 1
|
| 507 |
+
os.environ['MASTER_ADDR'] = '127.0.0.1'
|
| 508 |
+
os.environ['MASTER_PORT'] = '29500'
|
| 509 |
+
else:
|
| 510 |
+
print('Does not support training without GPU.')
|
| 511 |
+
sys.exit(1)
|
| 512 |
+
|
| 513 |
+
dist.init_process_group(
|
| 514 |
+
backend="nccl",
|
| 515 |
+
init_method=args.dist_url,
|
| 516 |
+
world_size=args.world_size,
|
| 517 |
+
rank=args.rank,
|
| 518 |
+
)
|
| 519 |
+
|
| 520 |
+
torch.cuda.set_device(args.gpu)
|
| 521 |
+
print('| distributed init (rank {}): {}'.format(args.rank, args.dist_url),
|
| 522 |
+
flush=True)
|
| 523 |
+
dist.barrier()
|
| 524 |
+
setup_for_distributed(args.rank == 0)
|
| 525 |
+
|
| 526 |
+
|
| 527 |
+
def accuracy(output, target, topk=(1, )):
|
| 528 |
+
"""Computes the accuracy over the k top predictions for the specified values of k"""
|
| 529 |
+
maxk = max(topk)
|
| 530 |
+
batch_size = target.size(0)
|
| 531 |
+
_, pred = output.topk(maxk, 1, True, True)
|
| 532 |
+
pred = pred.t()
|
| 533 |
+
correct = pred.eq(target.reshape(1, -1).expand_as(pred))
|
| 534 |
+
return [
|
| 535 |
+
correct[:k].reshape(-1).float().sum(0) * 100. / batch_size
|
| 536 |
+
for k in topk
|
| 537 |
+
]
|
| 538 |
+
|
| 539 |
+
|
| 540 |
+
def _no_grad_trunc_normal_(tensor, mean, std, a, b):
|
| 541 |
+
# Cut & paste from PyTorch official master until it's in a few official releases - RW
|
| 542 |
+
# Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf
|
| 543 |
+
def norm_cdf(x):
|
| 544 |
+
# Computes standard normal cumulative distribution function
|
| 545 |
+
return (1. + math.erf(x / math.sqrt(2.))) / 2.
|
| 546 |
+
|
| 547 |
+
if (mean < a - 2 * std) or (mean > b + 2 * std):
|
| 548 |
+
warnings.warn(
|
| 549 |
+
"mean is more than 2 std from [a, b] in nn.init.trunc_normal_. "
|
| 550 |
+
"The distribution of values may be incorrect.",
|
| 551 |
+
stacklevel=2)
|
| 552 |
+
|
| 553 |
+
with torch.no_grad():
|
| 554 |
+
# Values are generated by using a truncated uniform distribution and
|
| 555 |
+
# then using the inverse CDF for the normal distribution.
|
| 556 |
+
# Get upper and lower cdf values
|
| 557 |
+
l = norm_cdf((a - mean) / std)
|
| 558 |
+
u = norm_cdf((b - mean) / std)
|
| 559 |
+
|
| 560 |
+
# Uniformly fill tensor with values from [l, u], then translate to
|
| 561 |
+
# [2l-1, 2u-1].
|
| 562 |
+
tensor.uniform_(2 * l - 1, 2 * u - 1)
|
| 563 |
+
|
| 564 |
+
# Use inverse cdf transform for normal distribution to get truncated
|
| 565 |
+
# standard normal
|
| 566 |
+
tensor.erfinv_()
|
| 567 |
+
|
| 568 |
+
# Transform to proper mean, std
|
| 569 |
+
tensor.mul_(std * math.sqrt(2.))
|
| 570 |
+
tensor.add_(mean)
|
| 571 |
+
|
| 572 |
+
# Clamp to ensure it's in the proper range
|
| 573 |
+
tensor.clamp_(min=a, max=b)
|
| 574 |
+
return tensor
|
| 575 |
+
|
| 576 |
+
|
| 577 |
+
def trunc_normal_(tensor, mean=0., std=1., a=-2., b=2.):
|
| 578 |
+
# type: (Tensor, float, float, float, float) -> Tensor
|
| 579 |
+
return _no_grad_trunc_normal_(tensor, mean, std, a, b)
|
| 580 |
+
|
| 581 |
+
|
| 582 |
+
class LARS(torch.optim.Optimizer):
|
| 583 |
+
"""
|
| 584 |
+
Almost copy-paste from https://github.com/facebookresearch/barlowtwins/blob/main/main.py
|
| 585 |
+
"""
|
| 586 |
+
def __init__(self,
|
| 587 |
+
params,
|
| 588 |
+
lr=0,
|
| 589 |
+
weight_decay=0,
|
| 590 |
+
momentum=0.9,
|
| 591 |
+
eta=0.001,
|
| 592 |
+
weight_decay_filter=None,
|
| 593 |
+
lars_adaptation_filter=None):
|
| 594 |
+
defaults = dict(lr=lr,
|
| 595 |
+
weight_decay=weight_decay,
|
| 596 |
+
momentum=momentum,
|
| 597 |
+
eta=eta,
|
| 598 |
+
weight_decay_filter=weight_decay_filter,
|
| 599 |
+
lars_adaptation_filter=lars_adaptation_filter)
|
| 600 |
+
super().__init__(params, defaults)
|
| 601 |
+
|
| 602 |
+
@torch.no_grad()
|
| 603 |
+
def step(self):
|
| 604 |
+
for g in self.param_groups:
|
| 605 |
+
for p in g['params']:
|
| 606 |
+
dp = p.grad
|
| 607 |
+
|
| 608 |
+
if dp is None:
|
| 609 |
+
continue
|
| 610 |
+
|
| 611 |
+
if p.ndim != 1:
|
| 612 |
+
dp = dp.add(p, alpha=g['weight_decay'])
|
| 613 |
+
|
| 614 |
+
if p.ndim != 1:
|
| 615 |
+
param_norm = torch.norm(p)
|
| 616 |
+
update_norm = torch.norm(dp)
|
| 617 |
+
one = torch.ones_like(param_norm)
|
| 618 |
+
q = torch.where(
|
| 619 |
+
param_norm > 0.,
|
| 620 |
+
torch.where(update_norm > 0,
|
| 621 |
+
(g['eta'] * param_norm / update_norm),
|
| 622 |
+
one), one)
|
| 623 |
+
dp = dp.mul(q)
|
| 624 |
+
|
| 625 |
+
param_state = self.state[p]
|
| 626 |
+
if 'mu' not in param_state:
|
| 627 |
+
param_state['mu'] = torch.zeros_like(p)
|
| 628 |
+
mu = param_state['mu']
|
| 629 |
+
mu.mul_(g['momentum']).add_(dp)
|
| 630 |
+
|
| 631 |
+
p.add_(mu, alpha=-g['lr'])
|
| 632 |
+
|
| 633 |
+
|
| 634 |
+
class MultiCropWrapper(nn.Module):
|
| 635 |
+
"""
|
| 636 |
+
Perform forward pass separately on each resolution input.
|
| 637 |
+
The inputs corresponding to a single resolution are clubbed and single
|
| 638 |
+
forward is run on the same resolution inputs. Hence we do several
|
| 639 |
+
forward passes = number of different resolutions used. We then
|
| 640 |
+
concatenate all the output features and run the head forward on these
|
| 641 |
+
concatenated features.
|
| 642 |
+
"""
|
| 643 |
+
def __init__(self, backbone, head):
|
| 644 |
+
super(MultiCropWrapper, self).__init__()
|
| 645 |
+
# disable layers dedicated to ImageNet labels classification
|
| 646 |
+
backbone.fc, backbone.head = nn.Identity(), nn.Identity()
|
| 647 |
+
self.backbone = backbone
|
| 648 |
+
self.head = head
|
| 649 |
+
|
| 650 |
+
def forward(self, x):
|
| 651 |
+
# convert to list
|
| 652 |
+
if not isinstance(x, list):
|
| 653 |
+
x = [x]
|
| 654 |
+
idx_crops = torch.cumsum(
|
| 655 |
+
torch.unique_consecutive(
|
| 656 |
+
torch.tensor([inp.shape[-1] for inp in x]),
|
| 657 |
+
return_counts=True,
|
| 658 |
+
)[1], 0)
|
| 659 |
+
start_idx, output = 0, torch.empty(0).to(x[0].device)
|
| 660 |
+
for end_idx in idx_crops:
|
| 661 |
+
_out = self.backbone(torch.cat(x[start_idx:end_idx]))
|
| 662 |
+
# The output is a tuple with XCiT model. See:
|
| 663 |
+
# https://github.com/facebookresearch/xcit/blob/master/xcit.py#L404-L405
|
| 664 |
+
if isinstance(_out, tuple):
|
| 665 |
+
_out = _out[0]
|
| 666 |
+
# accumulate outputs
|
| 667 |
+
output = torch.cat((output, _out))
|
| 668 |
+
start_idx = end_idx
|
| 669 |
+
# Run the head forward on the concatenated features.
|
| 670 |
+
return self.head(output)
|
| 671 |
+
|
| 672 |
+
|
| 673 |
+
def get_params_groups(model):
|
| 674 |
+
regularized = []
|
| 675 |
+
not_regularized = []
|
| 676 |
+
for name, param in model.named_parameters():
|
| 677 |
+
if not param.requires_grad:
|
| 678 |
+
continue
|
| 679 |
+
# we do not regularize biases nor Norm parameters
|
| 680 |
+
if name.endswith(".bias") or len(param.shape) == 1:
|
| 681 |
+
not_regularized.append(param)
|
| 682 |
+
else:
|
| 683 |
+
regularized.append(param)
|
| 684 |
+
return [{
|
| 685 |
+
'params': regularized
|
| 686 |
+
}, {
|
| 687 |
+
'params': not_regularized,
|
| 688 |
+
'weight_decay': 0.
|
| 689 |
+
}]
|
| 690 |
+
|
| 691 |
+
|
| 692 |
+
def has_batchnorms(model):
|
| 693 |
+
bn_types = (nn.BatchNorm1d, nn.BatchNorm2d, nn.BatchNorm3d,
|
| 694 |
+
nn.SyncBatchNorm)
|
| 695 |
+
for name, module in model.named_modules():
|
| 696 |
+
if isinstance(module, bn_types):
|
| 697 |
+
return True
|
| 698 |
+
return False
|
| 699 |
+
|
| 700 |
+
|
| 701 |
+
class PCA():
|
| 702 |
+
"""
|
| 703 |
+
Class to compute and apply PCA.
|
| 704 |
+
"""
|
| 705 |
+
def __init__(self, dim=256, whit=0.5):
|
| 706 |
+
self.dim = dim
|
| 707 |
+
self.whit = whit
|
| 708 |
+
self.mean = None
|
| 709 |
+
|
| 710 |
+
def train_pca(self, cov):
|
| 711 |
+
"""
|
| 712 |
+
Takes a covariance matrix (np.ndarray) as input.
|
| 713 |
+
"""
|
| 714 |
+
d, v = np.linalg.eigh(cov)
|
| 715 |
+
eps = d.max() * 1e-5
|
| 716 |
+
n_0 = (d < eps).sum()
|
| 717 |
+
if n_0 > 0:
|
| 718 |
+
d[d < eps] = eps
|
| 719 |
+
|
| 720 |
+
# total energy
|
| 721 |
+
totenergy = d.sum()
|
| 722 |
+
|
| 723 |
+
# sort eigenvectors with eigenvalues order
|
| 724 |
+
idx = np.argsort(d)[::-1][:self.dim]
|
| 725 |
+
d = d[idx]
|
| 726 |
+
v = v[:, idx]
|
| 727 |
+
|
| 728 |
+
print("keeping %.2f %% of the energy" % (d.sum() / totenergy * 100.0))
|
| 729 |
+
|
| 730 |
+
# for the whitening
|
| 731 |
+
d = np.diag(1. / d**self.whit)
|
| 732 |
+
|
| 733 |
+
# principal components
|
| 734 |
+
self.dvt = np.dot(d, v.T)
|
| 735 |
+
|
| 736 |
+
def apply(self, x):
|
| 737 |
+
# input is from numpy
|
| 738 |
+
if isinstance(x, np.ndarray):
|
| 739 |
+
if self.mean is not None:
|
| 740 |
+
x -= self.mean
|
| 741 |
+
return np.dot(self.dvt, x.T).T
|
| 742 |
+
|
| 743 |
+
# input is from torch and is on GPU
|
| 744 |
+
if x.is_cuda:
|
| 745 |
+
if self.mean is not None:
|
| 746 |
+
x -= torch.cuda.FloatTensor(self.mean)
|
| 747 |
+
return torch.mm(torch.cuda.FloatTensor(self.dvt),
|
| 748 |
+
x.transpose(0, 1)).transpose(0, 1)
|
| 749 |
+
|
| 750 |
+
# input if from torch, on CPU
|
| 751 |
+
if self.mean is not None:
|
| 752 |
+
x -= torch.FloatTensor(self.mean)
|
| 753 |
+
return torch.mm(torch.FloatTensor(self.dvt),
|
| 754 |
+
x.transpose(0, 1)).transpose(0, 1)
|
| 755 |
+
|
| 756 |
+
|
| 757 |
+
def compute_ap(ranks, nres):
|
| 758 |
+
"""
|
| 759 |
+
Computes average precision for given ranked indexes.
|
| 760 |
+
Arguments
|
| 761 |
+
---------
|
| 762 |
+
ranks : zerro-based ranks of positive images
|
| 763 |
+
nres : number of positive images
|
| 764 |
+
Returns
|
| 765 |
+
-------
|
| 766 |
+
ap : average precision
|
| 767 |
+
"""
|
| 768 |
+
|
| 769 |
+
# number of images ranked by the system
|
| 770 |
+
nimgranks = len(ranks)
|
| 771 |
+
|
| 772 |
+
# accumulate trapezoids in PR-plot
|
| 773 |
+
ap = 0
|
| 774 |
+
|
| 775 |
+
recall_step = 1. / nres
|
| 776 |
+
|
| 777 |
+
for j in np.arange(nimgranks):
|
| 778 |
+
rank = ranks[j]
|
| 779 |
+
|
| 780 |
+
if rank == 0:
|
| 781 |
+
precision_0 = 1.
|
| 782 |
+
else:
|
| 783 |
+
precision_0 = float(j) / rank
|
| 784 |
+
|
| 785 |
+
precision_1 = float(j + 1) / (rank + 1)
|
| 786 |
+
|
| 787 |
+
ap += (precision_0 + precision_1) * recall_step / 2.
|
| 788 |
+
|
| 789 |
+
return ap
|
| 790 |
+
|
| 791 |
+
|
| 792 |
+
def compute_map(ranks, gnd, kappas=[]):
|
| 793 |
+
"""
|
| 794 |
+
Computes the mAP for a given set of returned results.
|
| 795 |
+
Usage:
|
| 796 |
+
map = compute_map (ranks, gnd)
|
| 797 |
+
computes mean average precsion (map) only
|
| 798 |
+
map, aps, pr, prs = compute_map (ranks, gnd, kappas)
|
| 799 |
+
computes mean average precision (map), average precision (aps) for each query
|
| 800 |
+
computes mean precision at kappas (pr), precision at kappas (prs) for each query
|
| 801 |
+
Notes:
|
| 802 |
+
1) ranks starts from 0, ranks.shape = db_size X #queries
|
| 803 |
+
2) The junk results (e.g., the query itself) should be declared in the gnd stuct array
|
| 804 |
+
3) If there are no positive images for some query, that query is excluded from the evaluation
|
| 805 |
+
"""
|
| 806 |
+
|
| 807 |
+
map = 0.
|
| 808 |
+
nq = len(gnd) # number of queries
|
| 809 |
+
aps = np.zeros(nq)
|
| 810 |
+
pr = np.zeros(len(kappas))
|
| 811 |
+
prs = np.zeros((nq, len(kappas)))
|
| 812 |
+
nempty = 0
|
| 813 |
+
|
| 814 |
+
for i in np.arange(nq):
|
| 815 |
+
qgnd = np.array(gnd[i]['ok'])
|
| 816 |
+
|
| 817 |
+
# no positive images, skip from the average
|
| 818 |
+
if qgnd.shape[0] == 0:
|
| 819 |
+
aps[i] = float('nan')
|
| 820 |
+
prs[i, :] = float('nan')
|
| 821 |
+
nempty += 1
|
| 822 |
+
continue
|
| 823 |
+
|
| 824 |
+
try:
|
| 825 |
+
qgndj = np.array(gnd[i]['junk'])
|
| 826 |
+
except:
|
| 827 |
+
qgndj = np.empty(0)
|
| 828 |
+
|
| 829 |
+
# sorted positions of positive and junk images (0 based)
|
| 830 |
+
pos = np.arange(ranks.shape[0])[np.in1d(ranks[:, i], qgnd)]
|
| 831 |
+
junk = np.arange(ranks.shape[0])[np.in1d(ranks[:, i], qgndj)]
|
| 832 |
+
|
| 833 |
+
k = 0
|
| 834 |
+
ij = 0
|
| 835 |
+
if len(junk):
|
| 836 |
+
# decrease positions of positives based on the number of
|
| 837 |
+
# junk images appearing before them
|
| 838 |
+
ip = 0
|
| 839 |
+
while (ip < len(pos)):
|
| 840 |
+
while (ij < len(junk) and pos[ip] > junk[ij]):
|
| 841 |
+
k += 1
|
| 842 |
+
ij += 1
|
| 843 |
+
pos[ip] = pos[ip] - k
|
| 844 |
+
ip += 1
|
| 845 |
+
|
| 846 |
+
# compute ap
|
| 847 |
+
ap = compute_ap(pos, len(qgnd))
|
| 848 |
+
map = map + ap
|
| 849 |
+
aps[i] = ap
|
| 850 |
+
|
| 851 |
+
# compute precision @ k
|
| 852 |
+
pos += 1 # get it to 1-based
|
| 853 |
+
for j in np.arange(len(kappas)):
|
| 854 |
+
kq = min(max(pos), kappas[j])
|
| 855 |
+
prs[i, j] = (pos <= kq).sum() / kq
|
| 856 |
+
pr = pr + prs[i, :]
|
| 857 |
+
|
| 858 |
+
map = map / (nq - nempty)
|
| 859 |
+
pr = pr / (nq - nempty)
|
| 860 |
+
|
| 861 |
+
return map, aps, pr, prs
|
| 862 |
+
|
| 863 |
+
|
| 864 |
+
def multi_scale(samples, model):
|
| 865 |
+
v = None
|
| 866 |
+
for s in [1, 1 / 2**(1 / 2), 1 / 2]: # we use 3 different scales
|
| 867 |
+
if s == 1:
|
| 868 |
+
inp = samples.clone()
|
| 869 |
+
else:
|
| 870 |
+
inp = nn.functional.interpolate(samples,
|
| 871 |
+
scale_factor=s,
|
| 872 |
+
mode='bilinear',
|
| 873 |
+
align_corners=False)
|
| 874 |
+
feats = model(inp).clone()
|
| 875 |
+
if v is None:
|
| 876 |
+
v = feats
|
| 877 |
+
else:
|
| 878 |
+
v += feats
|
| 879 |
+
v /= 3
|
| 880 |
+
v /= v.norm()
|
| 881 |
+
return v
|
OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/benchmark.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import time
|
| 2 |
+
import torch
|
| 3 |
+
import vox2seq
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
if __name__ == "__main__":
|
| 7 |
+
stats = {
|
| 8 |
+
'z_order_cuda': [],
|
| 9 |
+
'z_order_pytorch': [],
|
| 10 |
+
'hilbert_cuda': [],
|
| 11 |
+
'hilbert_pytorch': [],
|
| 12 |
+
}
|
| 13 |
+
RES = [16, 32, 64, 128, 256]
|
| 14 |
+
for res in RES:
|
| 15 |
+
coords = torch.meshgrid(torch.arange(res), torch.arange(res), torch.arange(res))
|
| 16 |
+
coords = torch.stack(coords, dim=-1).reshape(-1, 3).int().cuda()
|
| 17 |
+
|
| 18 |
+
start = time.time()
|
| 19 |
+
for _ in range(100):
|
| 20 |
+
code_z_cuda = vox2seq.encode(coords, mode='z_order').cuda()
|
| 21 |
+
torch.cuda.synchronize()
|
| 22 |
+
stats['z_order_cuda'].append((time.time() - start) / 100)
|
| 23 |
+
|
| 24 |
+
start = time.time()
|
| 25 |
+
for _ in range(100):
|
| 26 |
+
code_z_pytorch = vox2seq.pytorch.encode(coords, mode='z_order').cuda()
|
| 27 |
+
torch.cuda.synchronize()
|
| 28 |
+
stats['z_order_pytorch'].append((time.time() - start) / 100)
|
| 29 |
+
|
| 30 |
+
start = time.time()
|
| 31 |
+
for _ in range(100):
|
| 32 |
+
code_h_cuda = vox2seq.encode(coords, mode='hilbert').cuda()
|
| 33 |
+
torch.cuda.synchronize()
|
| 34 |
+
stats['hilbert_cuda'].append((time.time() - start) / 100)
|
| 35 |
+
|
| 36 |
+
start = time.time()
|
| 37 |
+
for _ in range(100):
|
| 38 |
+
code_h_pytorch = vox2seq.pytorch.encode(coords, mode='hilbert').cuda()
|
| 39 |
+
torch.cuda.synchronize()
|
| 40 |
+
stats['hilbert_pytorch'].append((time.time() - start) / 100)
|
| 41 |
+
|
| 42 |
+
print(f"{'Resolution':<12}{'Z-Order (CUDA)':<24}{'Z-Order (PyTorch)':<24}{'Hilbert (CUDA)':<24}{'Hilbert (PyTorch)':<24}")
|
| 43 |
+
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']):
|
| 44 |
+
print(f"{res:<12}{z_order_cuda:<24.6f}{z_order_pytorch:<24.6f}{hilbert_cuda:<24.6f}{hilbert_pytorch:<24.6f}")
|
| 45 |
+
|
OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/setup.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# Copyright (C) 2023, Inria
|
| 3 |
+
# GRAPHDECO research group, https://team.inria.fr/graphdeco
|
| 4 |
+
# All rights reserved.
|
| 5 |
+
#
|
| 6 |
+
# This software is free for non-commercial, research and evaluation use
|
| 7 |
+
# under the terms of the LICENSE.md file.
|
| 8 |
+
#
|
| 9 |
+
# For inquiries contact george.drettakis@inria.fr
|
| 10 |
+
#
|
| 11 |
+
|
| 12 |
+
from setuptools import setup
|
| 13 |
+
from torch.utils.cpp_extension import CUDAExtension, BuildExtension
|
| 14 |
+
import os
|
| 15 |
+
os.path.dirname(os.path.abspath(__file__))
|
| 16 |
+
|
| 17 |
+
setup(
|
| 18 |
+
name="vox2seq",
|
| 19 |
+
packages=['vox2seq', 'vox2seq.pytorch'],
|
| 20 |
+
ext_modules=[
|
| 21 |
+
CUDAExtension(
|
| 22 |
+
name="vox2seq._C",
|
| 23 |
+
sources=[
|
| 24 |
+
"src/api.cu",
|
| 25 |
+
"src/z_order.cu",
|
| 26 |
+
"src/hilbert.cu",
|
| 27 |
+
"src/ext.cpp",
|
| 28 |
+
],
|
| 29 |
+
)
|
| 30 |
+
],
|
| 31 |
+
cmdclass={
|
| 32 |
+
'build_ext': BuildExtension
|
| 33 |
+
}
|
| 34 |
+
)
|
OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/src/api.cu
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#include <torch/extension.h>
|
| 2 |
+
#include "api.h"
|
| 3 |
+
#include "z_order.h"
|
| 4 |
+
#include "hilbert.h"
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
torch::Tensor
|
| 8 |
+
z_order_encode(
|
| 9 |
+
const torch::Tensor& x,
|
| 10 |
+
const torch::Tensor& y,
|
| 11 |
+
const torch::Tensor& z
|
| 12 |
+
) {
|
| 13 |
+
// Allocate output tensor
|
| 14 |
+
torch::Tensor codes = torch::empty_like(x);
|
| 15 |
+
|
| 16 |
+
// Call CUDA kernel
|
| 17 |
+
z_order_encode_cuda<<<(x.size(0) + BLOCK_SIZE - 1) / BLOCK_SIZE, BLOCK_SIZE>>>(
|
| 18 |
+
x.size(0),
|
| 19 |
+
reinterpret_cast<uint32_t*>(x.contiguous().data_ptr<int>()),
|
| 20 |
+
reinterpret_cast<uint32_t*>(y.contiguous().data_ptr<int>()),
|
| 21 |
+
reinterpret_cast<uint32_t*>(z.contiguous().data_ptr<int>()),
|
| 22 |
+
reinterpret_cast<uint32_t*>(codes.data_ptr<int>())
|
| 23 |
+
);
|
| 24 |
+
|
| 25 |
+
return codes;
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
std::tuple<torch::Tensor, torch::Tensor, torch::Tensor>
|
| 30 |
+
z_order_decode(
|
| 31 |
+
const torch::Tensor& codes
|
| 32 |
+
) {
|
| 33 |
+
// Allocate output tensors
|
| 34 |
+
torch::Tensor x = torch::empty_like(codes);
|
| 35 |
+
torch::Tensor y = torch::empty_like(codes);
|
| 36 |
+
torch::Tensor z = torch::empty_like(codes);
|
| 37 |
+
|
| 38 |
+
// Call CUDA kernel
|
| 39 |
+
z_order_decode_cuda<<<(codes.size(0) + BLOCK_SIZE - 1) / BLOCK_SIZE, BLOCK_SIZE>>>(
|
| 40 |
+
codes.size(0),
|
| 41 |
+
reinterpret_cast<uint32_t*>(codes.contiguous().data_ptr<int>()),
|
| 42 |
+
reinterpret_cast<uint32_t*>(x.data_ptr<int>()),
|
| 43 |
+
reinterpret_cast<uint32_t*>(y.data_ptr<int>()),
|
| 44 |
+
reinterpret_cast<uint32_t*>(z.data_ptr<int>())
|
| 45 |
+
);
|
| 46 |
+
|
| 47 |
+
return std::make_tuple(x, y, z);
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
torch::Tensor
|
| 52 |
+
hilbert_encode(
|
| 53 |
+
const torch::Tensor& x,
|
| 54 |
+
const torch::Tensor& y,
|
| 55 |
+
const torch::Tensor& z
|
| 56 |
+
) {
|
| 57 |
+
// Allocate output tensor
|
| 58 |
+
torch::Tensor codes = torch::empty_like(x);
|
| 59 |
+
|
| 60 |
+
// Call CUDA kernel
|
| 61 |
+
hilbert_encode_cuda<<<(x.size(0) + BLOCK_SIZE - 1) / BLOCK_SIZE, BLOCK_SIZE>>>(
|
| 62 |
+
x.size(0),
|
| 63 |
+
reinterpret_cast<uint32_t*>(x.contiguous().data_ptr<int>()),
|
| 64 |
+
reinterpret_cast<uint32_t*>(y.contiguous().data_ptr<int>()),
|
| 65 |
+
reinterpret_cast<uint32_t*>(z.contiguous().data_ptr<int>()),
|
| 66 |
+
reinterpret_cast<uint32_t*>(codes.data_ptr<int>())
|
| 67 |
+
);
|
| 68 |
+
|
| 69 |
+
return codes;
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
std::tuple<torch::Tensor, torch::Tensor, torch::Tensor>
|
| 74 |
+
hilbert_decode(
|
| 75 |
+
const torch::Tensor& codes
|
| 76 |
+
) {
|
| 77 |
+
// Allocate output tensors
|
| 78 |
+
torch::Tensor x = torch::empty_like(codes);
|
| 79 |
+
torch::Tensor y = torch::empty_like(codes);
|
| 80 |
+
torch::Tensor z = torch::empty_like(codes);
|
| 81 |
+
|
| 82 |
+
// Call CUDA kernel
|
| 83 |
+
hilbert_decode_cuda<<<(codes.size(0) + BLOCK_SIZE - 1) / BLOCK_SIZE, BLOCK_SIZE>>>(
|
| 84 |
+
codes.size(0),
|
| 85 |
+
reinterpret_cast<uint32_t*>(codes.contiguous().data_ptr<int>()),
|
| 86 |
+
reinterpret_cast<uint32_t*>(x.data_ptr<int>()),
|
| 87 |
+
reinterpret_cast<uint32_t*>(y.data_ptr<int>()),
|
| 88 |
+
reinterpret_cast<uint32_t*>(z.data_ptr<int>())
|
| 89 |
+
);
|
| 90 |
+
|
| 91 |
+
return std::make_tuple(x, y, z);
|
| 92 |
+
}
|
OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/src/api.h
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/*
|
| 2 |
+
* Serialize a voxel grid
|
| 3 |
+
*
|
| 4 |
+
* Copyright (C) 2024, Jianfeng XIANG <belljig@outlook.com>
|
| 5 |
+
* All rights reserved.
|
| 6 |
+
*
|
| 7 |
+
* Licensed under The MIT License [see LICENSE for details]
|
| 8 |
+
*
|
| 9 |
+
* Written by Jianfeng XIANG
|
| 10 |
+
*/
|
| 11 |
+
|
| 12 |
+
#pragma once
|
| 13 |
+
#include <torch/extension.h>
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
#define BLOCK_SIZE 256
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
/**
|
| 20 |
+
* Z-order encode 3D points
|
| 21 |
+
*
|
| 22 |
+
* @param x [N] tensor containing the x coordinates
|
| 23 |
+
* @param y [N] tensor containing the y coordinates
|
| 24 |
+
* @param z [N] tensor containing the z coordinates
|
| 25 |
+
*
|
| 26 |
+
* @return [N] tensor containing the z-order encoded values
|
| 27 |
+
*/
|
| 28 |
+
torch::Tensor
|
| 29 |
+
z_order_encode(
|
| 30 |
+
const torch::Tensor& x,
|
| 31 |
+
const torch::Tensor& y,
|
| 32 |
+
const torch::Tensor& z
|
| 33 |
+
);
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
/**
|
| 37 |
+
* Z-order decode 3D points
|
| 38 |
+
*
|
| 39 |
+
* @param codes [N] tensor containing the z-order encoded values
|
| 40 |
+
*
|
| 41 |
+
* @return 3 tensors [N] containing the x, y, z coordinates
|
| 42 |
+
*/
|
| 43 |
+
std::tuple<torch::Tensor, torch::Tensor, torch::Tensor>
|
| 44 |
+
z_order_decode(
|
| 45 |
+
const torch::Tensor& codes
|
| 46 |
+
);
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
/**
|
| 50 |
+
* Hilbert encode 3D points
|
| 51 |
+
*
|
| 52 |
+
* @param x [N] tensor containing the x coordinates
|
| 53 |
+
* @param y [N] tensor containing the y coordinates
|
| 54 |
+
* @param z [N] tensor containing the z coordinates
|
| 55 |
+
*
|
| 56 |
+
* @return [N] tensor containing the Hilbert encoded values
|
| 57 |
+
*/
|
| 58 |
+
torch::Tensor
|
| 59 |
+
hilbert_encode(
|
| 60 |
+
const torch::Tensor& x,
|
| 61 |
+
const torch::Tensor& y,
|
| 62 |
+
const torch::Tensor& z
|
| 63 |
+
);
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
/**
|
| 67 |
+
* Hilbert decode 3D points
|
| 68 |
+
*
|
| 69 |
+
* @param codes [N] tensor containing the Hilbert encoded values
|
| 70 |
+
*
|
| 71 |
+
* @return 3 tensors [N] containing the x, y, z coordinates
|
| 72 |
+
*/
|
| 73 |
+
std::tuple<torch::Tensor, torch::Tensor, torch::Tensor>
|
| 74 |
+
hilbert_decode(
|
| 75 |
+
const torch::Tensor& codes
|
| 76 |
+
);
|
OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/src/ext.cpp
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#include <torch/extension.h>
|
| 2 |
+
#include "api.h"
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
|
| 6 |
+
m.def("z_order_encode", &z_order_encode);
|
| 7 |
+
m.def("z_order_decode", &z_order_decode);
|
| 8 |
+
m.def("hilbert_encode", &hilbert_encode);
|
| 9 |
+
m.def("hilbert_decode", &hilbert_decode);
|
| 10 |
+
}
|
OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/src/hilbert.cu
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#include <cuda.h>
|
| 2 |
+
#include <cuda_runtime.h>
|
| 3 |
+
#include <device_launch_parameters.h>
|
| 4 |
+
|
| 5 |
+
#include <cooperative_groups.h>
|
| 6 |
+
#include <cooperative_groups/memcpy_async.h>
|
| 7 |
+
namespace cg = cooperative_groups;
|
| 8 |
+
|
| 9 |
+
#include "hilbert.h"
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
// Expands a 10-bit integer into 30 bits by inserting 2 zeros after each bit.
|
| 13 |
+
static __device__ uint32_t expandBits(uint32_t v)
|
| 14 |
+
{
|
| 15 |
+
v = (v * 0x00010001u) & 0xFF0000FFu;
|
| 16 |
+
v = (v * 0x00000101u) & 0x0F00F00Fu;
|
| 17 |
+
v = (v * 0x00000011u) & 0xC30C30C3u;
|
| 18 |
+
v = (v * 0x00000005u) & 0x49249249u;
|
| 19 |
+
return v;
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
// Removes 2 zeros after each bit in a 30-bit integer.
|
| 24 |
+
static __device__ uint32_t extractBits(uint32_t v)
|
| 25 |
+
{
|
| 26 |
+
v = v & 0x49249249;
|
| 27 |
+
v = (v ^ (v >> 2)) & 0x030C30C3u;
|
| 28 |
+
v = (v ^ (v >> 4)) & 0x0300F00Fu;
|
| 29 |
+
v = (v ^ (v >> 8)) & 0x030000FFu;
|
| 30 |
+
v = (v ^ (v >> 16)) & 0x000003FFu;
|
| 31 |
+
return v;
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
__global__ void hilbert_encode_cuda(
|
| 36 |
+
size_t N,
|
| 37 |
+
const uint32_t* x,
|
| 38 |
+
const uint32_t* y,
|
| 39 |
+
const uint32_t* z,
|
| 40 |
+
uint32_t* codes
|
| 41 |
+
) {
|
| 42 |
+
size_t thread_id = cg::this_grid().thread_rank();
|
| 43 |
+
if (thread_id >= N) return;
|
| 44 |
+
|
| 45 |
+
uint32_t point[3] = {x[thread_id], y[thread_id], z[thread_id]};
|
| 46 |
+
|
| 47 |
+
uint32_t m = 1 << 9, q, p, t;
|
| 48 |
+
|
| 49 |
+
// Inverse undo excess work
|
| 50 |
+
q = m;
|
| 51 |
+
while (q > 1) {
|
| 52 |
+
p = q - 1;
|
| 53 |
+
for (int i = 0; i < 3; i++) {
|
| 54 |
+
if (point[i] & q) {
|
| 55 |
+
point[0] ^= p; // invert
|
| 56 |
+
} else {
|
| 57 |
+
t = (point[0] ^ point[i]) & p;
|
| 58 |
+
point[0] ^= t;
|
| 59 |
+
point[i] ^= t;
|
| 60 |
+
}
|
| 61 |
+
}
|
| 62 |
+
q >>= 1;
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
// Gray encode
|
| 66 |
+
for (int i = 1; i < 3; i++) {
|
| 67 |
+
point[i] ^= point[i - 1];
|
| 68 |
+
}
|
| 69 |
+
t = 0;
|
| 70 |
+
q = m;
|
| 71 |
+
while (q > 1) {
|
| 72 |
+
if (point[2] & q) {
|
| 73 |
+
t ^= q - 1;
|
| 74 |
+
}
|
| 75 |
+
q >>= 1;
|
| 76 |
+
}
|
| 77 |
+
for (int i = 0; i < 3; i++) {
|
| 78 |
+
point[i] ^= t;
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
// Convert to 3D Hilbert code
|
| 82 |
+
uint32_t xx = expandBits(point[0]);
|
| 83 |
+
uint32_t yy = expandBits(point[1]);
|
| 84 |
+
uint32_t zz = expandBits(point[2]);
|
| 85 |
+
|
| 86 |
+
codes[thread_id] = xx * 4 + yy * 2 + zz;
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
__global__ void hilbert_decode_cuda(
|
| 91 |
+
size_t N,
|
| 92 |
+
const uint32_t* codes,
|
| 93 |
+
uint32_t* x,
|
| 94 |
+
uint32_t* y,
|
| 95 |
+
uint32_t* z
|
| 96 |
+
) {
|
| 97 |
+
size_t thread_id = cg::this_grid().thread_rank();
|
| 98 |
+
if (thread_id >= N) return;
|
| 99 |
+
|
| 100 |
+
uint32_t point[3];
|
| 101 |
+
point[0] = extractBits(codes[thread_id] >> 2);
|
| 102 |
+
point[1] = extractBits(codes[thread_id] >> 1);
|
| 103 |
+
point[2] = extractBits(codes[thread_id]);
|
| 104 |
+
|
| 105 |
+
uint32_t m = 2 << 9, q, p, t;
|
| 106 |
+
|
| 107 |
+
// Gray decode by H ^ (H/2)
|
| 108 |
+
t = point[2] >> 1;
|
| 109 |
+
for (int i = 2; i > 0; i--) {
|
| 110 |
+
point[i] ^= point[i - 1];
|
| 111 |
+
}
|
| 112 |
+
point[0] ^= t;
|
| 113 |
+
|
| 114 |
+
// Undo excess work
|
| 115 |
+
q = 2;
|
| 116 |
+
while (q != m) {
|
| 117 |
+
p = q - 1;
|
| 118 |
+
for (int i = 2; i >= 0; i--) {
|
| 119 |
+
if (point[i] & q) {
|
| 120 |
+
point[0] ^= p;
|
| 121 |
+
} else {
|
| 122 |
+
t = (point[0] ^ point[i]) & p;
|
| 123 |
+
point[0] ^= t;
|
| 124 |
+
point[i] ^= t;
|
| 125 |
+
}
|
| 126 |
+
}
|
| 127 |
+
q <<= 1;
|
| 128 |
+
}
|
| 129 |
+
|
| 130 |
+
x[thread_id] = point[0];
|
| 131 |
+
y[thread_id] = point[1];
|
| 132 |
+
z[thread_id] = point[2];
|
| 133 |
+
}
|
OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/src/hilbert.h
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
/**
|
| 4 |
+
* Hilbert encode 3D points
|
| 5 |
+
*
|
| 6 |
+
* @param x [N] tensor containing the x coordinates
|
| 7 |
+
* @param y [N] tensor containing the y coordinates
|
| 8 |
+
* @param z [N] tensor containing the z coordinates
|
| 9 |
+
*
|
| 10 |
+
* @return [N] tensor containing the z-order encoded values
|
| 11 |
+
*/
|
| 12 |
+
__global__ void hilbert_encode_cuda(
|
| 13 |
+
size_t N,
|
| 14 |
+
const uint32_t* x,
|
| 15 |
+
const uint32_t* y,
|
| 16 |
+
const uint32_t* z,
|
| 17 |
+
uint32_t* codes
|
| 18 |
+
);
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
/**
|
| 22 |
+
* Hilbert decode 3D points
|
| 23 |
+
*
|
| 24 |
+
* @param codes [N] tensor containing the z-order encoded values
|
| 25 |
+
* @param x [N] tensor containing the x coordinates
|
| 26 |
+
* @param y [N] tensor containing the y coordinates
|
| 27 |
+
* @param z [N] tensor containing the z coordinates
|
| 28 |
+
*/
|
| 29 |
+
__global__ void hilbert_decode_cuda(
|
| 30 |
+
size_t N,
|
| 31 |
+
const uint32_t* codes,
|
| 32 |
+
uint32_t* x,
|
| 33 |
+
uint32_t* y,
|
| 34 |
+
uint32_t* z
|
| 35 |
+
);
|
OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/src/z_order.cu
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#include <cuda.h>
|
| 2 |
+
#include <cuda_runtime.h>
|
| 3 |
+
#include <device_launch_parameters.h>
|
| 4 |
+
|
| 5 |
+
#include <cooperative_groups.h>
|
| 6 |
+
#include <cooperative_groups/memcpy_async.h>
|
| 7 |
+
namespace cg = cooperative_groups;
|
| 8 |
+
|
| 9 |
+
#include "z_order.h"
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
// Expands a 10-bit integer into 30 bits by inserting 2 zeros after each bit.
|
| 13 |
+
static __device__ uint32_t expandBits(uint32_t v)
|
| 14 |
+
{
|
| 15 |
+
v = (v * 0x00010001u) & 0xFF0000FFu;
|
| 16 |
+
v = (v * 0x00000101u) & 0x0F00F00Fu;
|
| 17 |
+
v = (v * 0x00000011u) & 0xC30C30C3u;
|
| 18 |
+
v = (v * 0x00000005u) & 0x49249249u;
|
| 19 |
+
return v;
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
// Removes 2 zeros after each bit in a 30-bit integer.
|
| 24 |
+
static __device__ uint32_t extractBits(uint32_t v)
|
| 25 |
+
{
|
| 26 |
+
v = v & 0x49249249;
|
| 27 |
+
v = (v ^ (v >> 2)) & 0x030C30C3u;
|
| 28 |
+
v = (v ^ (v >> 4)) & 0x0300F00Fu;
|
| 29 |
+
v = (v ^ (v >> 8)) & 0x030000FFu;
|
| 30 |
+
v = (v ^ (v >> 16)) & 0x000003FFu;
|
| 31 |
+
return v;
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
__global__ void z_order_encode_cuda(
|
| 36 |
+
size_t N,
|
| 37 |
+
const uint32_t* x,
|
| 38 |
+
const uint32_t* y,
|
| 39 |
+
const uint32_t* z,
|
| 40 |
+
uint32_t* codes
|
| 41 |
+
) {
|
| 42 |
+
size_t thread_id = cg::this_grid().thread_rank();
|
| 43 |
+
if (thread_id >= N) return;
|
| 44 |
+
|
| 45 |
+
uint32_t xx = expandBits(x[thread_id]);
|
| 46 |
+
uint32_t yy = expandBits(y[thread_id]);
|
| 47 |
+
uint32_t zz = expandBits(z[thread_id]);
|
| 48 |
+
|
| 49 |
+
codes[thread_id] = xx * 4 + yy * 2 + zz;
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
__global__ void z_order_decode_cuda(
|
| 54 |
+
size_t N,
|
| 55 |
+
const uint32_t* codes,
|
| 56 |
+
uint32_t* x,
|
| 57 |
+
uint32_t* y,
|
| 58 |
+
uint32_t* z
|
| 59 |
+
) {
|
| 60 |
+
size_t thread_id = cg::this_grid().thread_rank();
|
| 61 |
+
if (thread_id >= N) return;
|
| 62 |
+
|
| 63 |
+
x[thread_id] = extractBits(codes[thread_id] >> 2);
|
| 64 |
+
y[thread_id] = extractBits(codes[thread_id] >> 1);
|
| 65 |
+
z[thread_id] = extractBits(codes[thread_id]);
|
| 66 |
+
}
|
OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/src/z_order.h
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
/**
|
| 4 |
+
* Z-order encode 3D points
|
| 5 |
+
*
|
| 6 |
+
* @param x [N] tensor containing the x coordinates
|
| 7 |
+
* @param y [N] tensor containing the y coordinates
|
| 8 |
+
* @param z [N] tensor containing the z coordinates
|
| 9 |
+
*
|
| 10 |
+
* @return [N] tensor containing the z-order encoded values
|
| 11 |
+
*/
|
| 12 |
+
__global__ void z_order_encode_cuda(
|
| 13 |
+
size_t N,
|
| 14 |
+
const uint32_t* x,
|
| 15 |
+
const uint32_t* y,
|
| 16 |
+
const uint32_t* z,
|
| 17 |
+
uint32_t* codes
|
| 18 |
+
);
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
/**
|
| 22 |
+
* Z-order decode 3D points
|
| 23 |
+
*
|
| 24 |
+
* @param codes [N] tensor containing the z-order encoded values
|
| 25 |
+
* @param x [N] tensor containing the x coordinates
|
| 26 |
+
* @param y [N] tensor containing the y coordinates
|
| 27 |
+
* @param z [N] tensor containing the z coordinates
|
| 28 |
+
*/
|
| 29 |
+
__global__ void z_order_decode_cuda(
|
| 30 |
+
size_t N,
|
| 31 |
+
const uint32_t* codes,
|
| 32 |
+
uint32_t* x,
|
| 33 |
+
uint32_t* y,
|
| 34 |
+
uint32_t* z
|
| 35 |
+
);
|
OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/vox2seq/__init__.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
from typing import *
|
| 3 |
+
import torch
|
| 4 |
+
from . import _C
|
| 5 |
+
from . import pytorch
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
@torch.no_grad()
|
| 9 |
+
def encode(coords: torch.Tensor, permute: List[int] = [0, 1, 2], mode: Literal['z_order', 'hilbert'] = 'z_order') -> torch.Tensor:
|
| 10 |
+
"""
|
| 11 |
+
Encodes 3D coordinates into a 30-bit code.
|
| 12 |
+
|
| 13 |
+
Args:
|
| 14 |
+
coords: a tensor of shape [N, 3] containing the 3D coordinates.
|
| 15 |
+
permute: the permutation of the coordinates.
|
| 16 |
+
mode: the encoding mode to use.
|
| 17 |
+
"""
|
| 18 |
+
assert coords.shape[-1] == 3 and coords.ndim == 2, "Input coordinates must be of shape [N, 3]"
|
| 19 |
+
x = coords[:, permute[0]].int()
|
| 20 |
+
y = coords[:, permute[1]].int()
|
| 21 |
+
z = coords[:, permute[2]].int()
|
| 22 |
+
if mode == 'z_order':
|
| 23 |
+
return _C.z_order_encode(x, y, z)
|
| 24 |
+
elif mode == 'hilbert':
|
| 25 |
+
return _C.hilbert_encode(x, y, z)
|
| 26 |
+
else:
|
| 27 |
+
raise ValueError(f"Unknown encoding mode: {mode}")
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@torch.no_grad()
|
| 31 |
+
def decode(code: torch.Tensor, permute: List[int] = [0, 1, 2], mode: Literal['z_order', 'hilbert'] = 'z_order') -> torch.Tensor:
|
| 32 |
+
"""
|
| 33 |
+
Decodes a 30-bit code into 3D coordinates.
|
| 34 |
+
|
| 35 |
+
Args:
|
| 36 |
+
code: a tensor of shape [N] containing the 30-bit code.
|
| 37 |
+
permute: the permutation of the coordinates.
|
| 38 |
+
mode: the decoding mode to use.
|
| 39 |
+
"""
|
| 40 |
+
assert code.ndim == 1, "Input code must be of shape [N]"
|
| 41 |
+
if mode == 'z_order':
|
| 42 |
+
coords = _C.z_order_decode(code)
|
| 43 |
+
elif mode == 'hilbert':
|
| 44 |
+
coords = _C.hilbert_decode(code)
|
| 45 |
+
else:
|
| 46 |
+
raise ValueError(f"Unknown decoding mode: {mode}")
|
| 47 |
+
x = coords[permute.index(0)]
|
| 48 |
+
y = coords[permute.index(1)]
|
| 49 |
+
z = coords[permute.index(2)]
|
| 50 |
+
return torch.stack([x, y, z], dim=-1)
|
OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/vox2seq/pytorch/__init__.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from typing import *
|
| 3 |
+
|
| 4 |
+
from .default import (
|
| 5 |
+
encode,
|
| 6 |
+
decode,
|
| 7 |
+
z_order_encode,
|
| 8 |
+
z_order_decode,
|
| 9 |
+
hilbert_encode,
|
| 10 |
+
hilbert_decode,
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
@torch.no_grad()
|
| 15 |
+
def encode(coords: torch.Tensor, permute: List[int] = [0, 1, 2], mode: Literal['z_order', 'hilbert'] = 'z_order') -> torch.Tensor:
|
| 16 |
+
"""
|
| 17 |
+
Encodes 3D coordinates into a 30-bit code.
|
| 18 |
+
|
| 19 |
+
Args:
|
| 20 |
+
coords: a tensor of shape [N, 3] containing the 3D coordinates.
|
| 21 |
+
permute: the permutation of the coordinates.
|
| 22 |
+
mode: the encoding mode to use.
|
| 23 |
+
"""
|
| 24 |
+
if mode == 'z_order':
|
| 25 |
+
return z_order_encode(coords[:, permute], depth=10).int()
|
| 26 |
+
elif mode == 'hilbert':
|
| 27 |
+
return hilbert_encode(coords[:, permute], depth=10).int()
|
| 28 |
+
else:
|
| 29 |
+
raise ValueError(f"Unknown encoding mode: {mode}")
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
@torch.no_grad()
|
| 33 |
+
def decode(code: torch.Tensor, permute: List[int] = [0, 1, 2], mode: Literal['z_order', 'hilbert'] = 'z_order') -> torch.Tensor:
|
| 34 |
+
"""
|
| 35 |
+
Decodes a 30-bit code into 3D coordinates.
|
| 36 |
+
|
| 37 |
+
Args:
|
| 38 |
+
code: a tensor of shape [N] containing the 30-bit code.
|
| 39 |
+
permute: the permutation of the coordinates.
|
| 40 |
+
mode: the decoding mode to use.
|
| 41 |
+
"""
|
| 42 |
+
if mode == 'z_order':
|
| 43 |
+
return z_order_decode(code, depth=10)[:, permute].float()
|
| 44 |
+
elif mode == 'hilbert':
|
| 45 |
+
return hilbert_decode(code, depth=10)[:, permute].float()
|
| 46 |
+
else:
|
| 47 |
+
raise ValueError(f"Unknown decoding mode: {mode}")
|
| 48 |
+
|
OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/vox2seq/pytorch/default.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from .z_order import xyz2key as z_order_encode_
|
| 3 |
+
from .z_order import key2xyz as z_order_decode_
|
| 4 |
+
from .hilbert import encode as hilbert_encode_
|
| 5 |
+
from .hilbert import decode as hilbert_decode_
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
@torch.inference_mode()
|
| 9 |
+
def encode(grid_coord, batch=None, depth=16, order="z"):
|
| 10 |
+
assert order in {"z", "z-trans", "hilbert", "hilbert-trans"}
|
| 11 |
+
if order == "z":
|
| 12 |
+
code = z_order_encode(grid_coord, depth=depth)
|
| 13 |
+
elif order == "z-trans":
|
| 14 |
+
code = z_order_encode(grid_coord[:, [1, 0, 2]], depth=depth)
|
| 15 |
+
elif order == "hilbert":
|
| 16 |
+
code = hilbert_encode(grid_coord, depth=depth)
|
| 17 |
+
elif order == "hilbert-trans":
|
| 18 |
+
code = hilbert_encode(grid_coord[:, [1, 0, 2]], depth=depth)
|
| 19 |
+
else:
|
| 20 |
+
raise NotImplementedError
|
| 21 |
+
if batch is not None:
|
| 22 |
+
batch = batch.long()
|
| 23 |
+
code = batch << depth * 3 | code
|
| 24 |
+
return code
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@torch.inference_mode()
|
| 28 |
+
def decode(code, depth=16, order="z"):
|
| 29 |
+
assert order in {"z", "hilbert"}
|
| 30 |
+
batch = code >> depth * 3
|
| 31 |
+
code = code & ((1 << depth * 3) - 1)
|
| 32 |
+
if order == "z":
|
| 33 |
+
grid_coord = z_order_decode(code, depth=depth)
|
| 34 |
+
elif order == "hilbert":
|
| 35 |
+
grid_coord = hilbert_decode(code, depth=depth)
|
| 36 |
+
else:
|
| 37 |
+
raise NotImplementedError
|
| 38 |
+
return grid_coord, batch
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def z_order_encode(grid_coord: torch.Tensor, depth: int = 16):
|
| 42 |
+
x, y, z = grid_coord[:, 0].long(), grid_coord[:, 1].long(), grid_coord[:, 2].long()
|
| 43 |
+
# we block the support to batch, maintain batched code in Point class
|
| 44 |
+
code = z_order_encode_(x, y, z, b=None, depth=depth)
|
| 45 |
+
return code
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def z_order_decode(code: torch.Tensor, depth):
|
| 49 |
+
x, y, z, _ = z_order_decode_(code, depth=depth)
|
| 50 |
+
grid_coord = torch.stack([x, y, z], dim=-1) # (N, 3)
|
| 51 |
+
return grid_coord
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def hilbert_encode(grid_coord: torch.Tensor, depth: int = 16):
|
| 55 |
+
return hilbert_encode_(grid_coord, num_dims=3, num_bits=depth)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def hilbert_decode(code: torch.Tensor, depth: int = 16):
|
| 59 |
+
return hilbert_decode_(code, num_dims=3, num_bits=depth)
|
OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/vox2seq/pytorch/hilbert.py
ADDED
|
@@ -0,0 +1,303 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Hilbert Order
|
| 3 |
+
Modified from https://github.com/PrincetonLIPS/numpy-hilbert-curve
|
| 4 |
+
|
| 5 |
+
Author: Xiaoyang Wu (xiaoyang.wu.cs@gmail.com), Kaixin Xu
|
| 6 |
+
Please cite our work if the code is helpful to you.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def right_shift(binary, k=1, axis=-1):
|
| 13 |
+
"""Right shift an array of binary values.
|
| 14 |
+
|
| 15 |
+
Parameters:
|
| 16 |
+
-----------
|
| 17 |
+
binary: An ndarray of binary values.
|
| 18 |
+
|
| 19 |
+
k: The number of bits to shift. Default 1.
|
| 20 |
+
|
| 21 |
+
axis: The axis along which to shift. Default -1.
|
| 22 |
+
|
| 23 |
+
Returns:
|
| 24 |
+
--------
|
| 25 |
+
Returns an ndarray with zero prepended and the ends truncated, along
|
| 26 |
+
whatever axis was specified."""
|
| 27 |
+
|
| 28 |
+
# If we're shifting the whole thing, just return zeros.
|
| 29 |
+
if binary.shape[axis] <= k:
|
| 30 |
+
return torch.zeros_like(binary)
|
| 31 |
+
|
| 32 |
+
# Determine the padding pattern.
|
| 33 |
+
# padding = [(0,0)] * len(binary.shape)
|
| 34 |
+
# padding[axis] = (k,0)
|
| 35 |
+
|
| 36 |
+
# Determine the slicing pattern to eliminate just the last one.
|
| 37 |
+
slicing = [slice(None)] * len(binary.shape)
|
| 38 |
+
slicing[axis] = slice(None, -k)
|
| 39 |
+
shifted = torch.nn.functional.pad(
|
| 40 |
+
binary[tuple(slicing)], (k, 0), mode="constant", value=0
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
return shifted
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def binary2gray(binary, axis=-1):
|
| 47 |
+
"""Convert an array of binary values into Gray codes.
|
| 48 |
+
|
| 49 |
+
This uses the classic X ^ (X >> 1) trick to compute the Gray code.
|
| 50 |
+
|
| 51 |
+
Parameters:
|
| 52 |
+
-----------
|
| 53 |
+
binary: An ndarray of binary values.
|
| 54 |
+
|
| 55 |
+
axis: The axis along which to compute the gray code. Default=-1.
|
| 56 |
+
|
| 57 |
+
Returns:
|
| 58 |
+
--------
|
| 59 |
+
Returns an ndarray of Gray codes.
|
| 60 |
+
"""
|
| 61 |
+
shifted = right_shift(binary, axis=axis)
|
| 62 |
+
|
| 63 |
+
# Do the X ^ (X >> 1) trick.
|
| 64 |
+
gray = torch.logical_xor(binary, shifted)
|
| 65 |
+
|
| 66 |
+
return gray
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def gray2binary(gray, axis=-1):
|
| 70 |
+
"""Convert an array of Gray codes back into binary values.
|
| 71 |
+
|
| 72 |
+
Parameters:
|
| 73 |
+
-----------
|
| 74 |
+
gray: An ndarray of gray codes.
|
| 75 |
+
|
| 76 |
+
axis: The axis along which to perform Gray decoding. Default=-1.
|
| 77 |
+
|
| 78 |
+
Returns:
|
| 79 |
+
--------
|
| 80 |
+
Returns an ndarray of binary values.
|
| 81 |
+
"""
|
| 82 |
+
|
| 83 |
+
# Loop the log2(bits) number of times necessary, with shift and xor.
|
| 84 |
+
shift = 2 ** (torch.Tensor([gray.shape[axis]]).log2().ceil().int() - 1)
|
| 85 |
+
while shift > 0:
|
| 86 |
+
gray = torch.logical_xor(gray, right_shift(gray, shift))
|
| 87 |
+
shift = torch.div(shift, 2, rounding_mode="floor")
|
| 88 |
+
return gray
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def encode(locs, num_dims, num_bits):
|
| 92 |
+
"""Decode an array of locations in a hypercube into a Hilbert integer.
|
| 93 |
+
|
| 94 |
+
This is a vectorized-ish version of the Hilbert curve implementation by John
|
| 95 |
+
Skilling as described in:
|
| 96 |
+
|
| 97 |
+
Skilling, J. (2004, April). Programming the Hilbert curve. In AIP Conference
|
| 98 |
+
Proceedings (Vol. 707, No. 1, pp. 381-387). American Institute of Physics.
|
| 99 |
+
|
| 100 |
+
Params:
|
| 101 |
+
-------
|
| 102 |
+
locs - An ndarray of locations in a hypercube of num_dims dimensions, in
|
| 103 |
+
which each dimension runs from 0 to 2**num_bits-1. The shape can
|
| 104 |
+
be arbitrary, as long as the last dimension of the same has size
|
| 105 |
+
num_dims.
|
| 106 |
+
|
| 107 |
+
num_dims - The dimensionality of the hypercube. Integer.
|
| 108 |
+
|
| 109 |
+
num_bits - The number of bits for each dimension. Integer.
|
| 110 |
+
|
| 111 |
+
Returns:
|
| 112 |
+
--------
|
| 113 |
+
The output is an ndarray of uint64 integers with the same shape as the
|
| 114 |
+
input, excluding the last dimension, which needs to be num_dims.
|
| 115 |
+
"""
|
| 116 |
+
|
| 117 |
+
# Keep around the original shape for later.
|
| 118 |
+
orig_shape = locs.shape
|
| 119 |
+
bitpack_mask = 1 << torch.arange(0, 8).to(locs.device)
|
| 120 |
+
bitpack_mask_rev = bitpack_mask.flip(-1)
|
| 121 |
+
|
| 122 |
+
if orig_shape[-1] != num_dims:
|
| 123 |
+
raise ValueError(
|
| 124 |
+
"""
|
| 125 |
+
The shape of locs was surprising in that the last dimension was of size
|
| 126 |
+
%d, but num_dims=%d. These need to be equal.
|
| 127 |
+
"""
|
| 128 |
+
% (orig_shape[-1], num_dims)
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
if num_dims * num_bits > 63:
|
| 132 |
+
raise ValueError(
|
| 133 |
+
"""
|
| 134 |
+
num_dims=%d and num_bits=%d for %d bits total, which can't be encoded
|
| 135 |
+
into a int64. Are you sure you need that many points on your Hilbert
|
| 136 |
+
curve?
|
| 137 |
+
"""
|
| 138 |
+
% (num_dims, num_bits, num_dims * num_bits)
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
# Treat the location integers as 64-bit unsigned and then split them up into
|
| 142 |
+
# a sequence of uint8s. Preserve the association by dimension.
|
| 143 |
+
locs_uint8 = locs.long().view(torch.uint8).reshape((-1, num_dims, 8)).flip(-1)
|
| 144 |
+
|
| 145 |
+
# Now turn these into bits and truncate to num_bits.
|
| 146 |
+
gray = (
|
| 147 |
+
locs_uint8.unsqueeze(-1)
|
| 148 |
+
.bitwise_and(bitpack_mask_rev)
|
| 149 |
+
.ne(0)
|
| 150 |
+
.byte()
|
| 151 |
+
.flatten(-2, -1)[..., -num_bits:]
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
# Run the decoding process the other way.
|
| 155 |
+
# Iterate forwards through the bits.
|
| 156 |
+
for bit in range(0, num_bits):
|
| 157 |
+
# Iterate forwards through the dimensions.
|
| 158 |
+
for dim in range(0, num_dims):
|
| 159 |
+
# Identify which ones have this bit active.
|
| 160 |
+
mask = gray[:, dim, bit]
|
| 161 |
+
|
| 162 |
+
# Where this bit is on, invert the 0 dimension for lower bits.
|
| 163 |
+
gray[:, 0, bit + 1 :] = torch.logical_xor(
|
| 164 |
+
gray[:, 0, bit + 1 :], mask[:, None]
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
# Where the bit is off, exchange the lower bits with the 0 dimension.
|
| 168 |
+
to_flip = torch.logical_and(
|
| 169 |
+
torch.logical_not(mask[:, None]).repeat(1, gray.shape[2] - bit - 1),
|
| 170 |
+
torch.logical_xor(gray[:, 0, bit + 1 :], gray[:, dim, bit + 1 :]),
|
| 171 |
+
)
|
| 172 |
+
gray[:, dim, bit + 1 :] = torch.logical_xor(
|
| 173 |
+
gray[:, dim, bit + 1 :], to_flip
|
| 174 |
+
)
|
| 175 |
+
gray[:, 0, bit + 1 :] = torch.logical_xor(gray[:, 0, bit + 1 :], to_flip)
|
| 176 |
+
|
| 177 |
+
# Now flatten out.
|
| 178 |
+
gray = gray.swapaxes(1, 2).reshape((-1, num_bits * num_dims))
|
| 179 |
+
|
| 180 |
+
# Convert Gray back to binary.
|
| 181 |
+
hh_bin = gray2binary(gray)
|
| 182 |
+
|
| 183 |
+
# Pad back out to 64 bits.
|
| 184 |
+
extra_dims = 64 - num_bits * num_dims
|
| 185 |
+
padded = torch.nn.functional.pad(hh_bin, (extra_dims, 0), "constant", 0)
|
| 186 |
+
|
| 187 |
+
# Convert binary values into uint8s.
|
| 188 |
+
hh_uint8 = (
|
| 189 |
+
(padded.flip(-1).reshape((-1, 8, 8)) * bitpack_mask)
|
| 190 |
+
.sum(2)
|
| 191 |
+
.squeeze()
|
| 192 |
+
.type(torch.uint8)
|
| 193 |
+
)
|
| 194 |
+
|
| 195 |
+
# Convert uint8s into uint64s.
|
| 196 |
+
hh_uint64 = hh_uint8.view(torch.int64).squeeze()
|
| 197 |
+
|
| 198 |
+
return hh_uint64
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def decode(hilberts, num_dims, num_bits):
|
| 202 |
+
"""Decode an array of Hilbert integers into locations in a hypercube.
|
| 203 |
+
|
| 204 |
+
This is a vectorized-ish version of the Hilbert curve implementation by John
|
| 205 |
+
Skilling as described in:
|
| 206 |
+
|
| 207 |
+
Skilling, J. (2004, April). Programming the Hilbert curve. In AIP Conference
|
| 208 |
+
Proceedings (Vol. 707, No. 1, pp. 381-387). American Institute of Physics.
|
| 209 |
+
|
| 210 |
+
Params:
|
| 211 |
+
-------
|
| 212 |
+
hilberts - An ndarray of Hilbert integers. Must be an integer dtype and
|
| 213 |
+
cannot have fewer bits than num_dims * num_bits.
|
| 214 |
+
|
| 215 |
+
num_dims - The dimensionality of the hypercube. Integer.
|
| 216 |
+
|
| 217 |
+
num_bits - The number of bits for each dimension. Integer.
|
| 218 |
+
|
| 219 |
+
Returns:
|
| 220 |
+
--------
|
| 221 |
+
The output is an ndarray of unsigned integers with the same shape as hilberts
|
| 222 |
+
but with an additional dimension of size num_dims.
|
| 223 |
+
"""
|
| 224 |
+
|
| 225 |
+
if num_dims * num_bits > 64:
|
| 226 |
+
raise ValueError(
|
| 227 |
+
"""
|
| 228 |
+
num_dims=%d and num_bits=%d for %d bits total, which can't be encoded
|
| 229 |
+
into a uint64. Are you sure you need that many points on your Hilbert
|
| 230 |
+
curve?
|
| 231 |
+
"""
|
| 232 |
+
% (num_dims, num_bits)
|
| 233 |
+
)
|
| 234 |
+
|
| 235 |
+
# Handle the case where we got handed a naked integer.
|
| 236 |
+
hilberts = torch.atleast_1d(hilberts)
|
| 237 |
+
|
| 238 |
+
# Keep around the shape for later.
|
| 239 |
+
orig_shape = hilberts.shape
|
| 240 |
+
bitpack_mask = 2 ** torch.arange(0, 8).to(hilberts.device)
|
| 241 |
+
bitpack_mask_rev = bitpack_mask.flip(-1)
|
| 242 |
+
|
| 243 |
+
# Treat each of the hilberts as a s equence of eight uint8.
|
| 244 |
+
# This treats all of the inputs as uint64 and makes things uniform.
|
| 245 |
+
hh_uint8 = (
|
| 246 |
+
hilberts.ravel().type(torch.int64).view(torch.uint8).reshape((-1, 8)).flip(-1)
|
| 247 |
+
)
|
| 248 |
+
|
| 249 |
+
# Turn these lists of uints into lists of bits and then truncate to the size
|
| 250 |
+
# we actually need for using Skilling's procedure.
|
| 251 |
+
hh_bits = (
|
| 252 |
+
hh_uint8.unsqueeze(-1)
|
| 253 |
+
.bitwise_and(bitpack_mask_rev)
|
| 254 |
+
.ne(0)
|
| 255 |
+
.byte()
|
| 256 |
+
.flatten(-2, -1)[:, -num_dims * num_bits :]
|
| 257 |
+
)
|
| 258 |
+
|
| 259 |
+
# Take the sequence of bits and Gray-code it.
|
| 260 |
+
gray = binary2gray(hh_bits)
|
| 261 |
+
|
| 262 |
+
# There has got to be a better way to do this.
|
| 263 |
+
# I could index them differently, but the eventual packbits likes it this way.
|
| 264 |
+
gray = gray.reshape((-1, num_bits, num_dims)).swapaxes(1, 2)
|
| 265 |
+
|
| 266 |
+
# Iterate backwards through the bits.
|
| 267 |
+
for bit in range(num_bits - 1, -1, -1):
|
| 268 |
+
# Iterate backwards through the dimensions.
|
| 269 |
+
for dim in range(num_dims - 1, -1, -1):
|
| 270 |
+
# Identify which ones have this bit active.
|
| 271 |
+
mask = gray[:, dim, bit]
|
| 272 |
+
|
| 273 |
+
# Where this bit is on, invert the 0 dimension for lower bits.
|
| 274 |
+
gray[:, 0, bit + 1 :] = torch.logical_xor(
|
| 275 |
+
gray[:, 0, bit + 1 :], mask[:, None]
|
| 276 |
+
)
|
| 277 |
+
|
| 278 |
+
# Where the bit is off, exchange the lower bits with the 0 dimension.
|
| 279 |
+
to_flip = torch.logical_and(
|
| 280 |
+
torch.logical_not(mask[:, None]),
|
| 281 |
+
torch.logical_xor(gray[:, 0, bit + 1 :], gray[:, dim, bit + 1 :]),
|
| 282 |
+
)
|
| 283 |
+
gray[:, dim, bit + 1 :] = torch.logical_xor(
|
| 284 |
+
gray[:, dim, bit + 1 :], to_flip
|
| 285 |
+
)
|
| 286 |
+
gray[:, 0, bit + 1 :] = torch.logical_xor(gray[:, 0, bit + 1 :], to_flip)
|
| 287 |
+
|
| 288 |
+
# Pad back out to 64 bits.
|
| 289 |
+
extra_dims = 64 - num_bits
|
| 290 |
+
padded = torch.nn.functional.pad(gray, (extra_dims, 0), "constant", 0)
|
| 291 |
+
|
| 292 |
+
# Now chop these up into blocks of 8.
|
| 293 |
+
locs_chopped = padded.flip(-1).reshape((-1, num_dims, 8, 8))
|
| 294 |
+
|
| 295 |
+
# Take those blocks and turn them unto uint8s.
|
| 296 |
+
# from IPython import embed; embed()
|
| 297 |
+
locs_uint8 = (locs_chopped * bitpack_mask).sum(3).squeeze().type(torch.uint8)
|
| 298 |
+
|
| 299 |
+
# Finally, treat these as uint64s.
|
| 300 |
+
flat_locs = locs_uint8.view(torch.int64)
|
| 301 |
+
|
| 302 |
+
# Return them in the expected shape.
|
| 303 |
+
return flat_locs.reshape((*orig_shape, num_dims))
|
OVOW/engine/oneposeviagen/Amodal3R/extensions/vox2seq/vox2seq/pytorch/z_order.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# --------------------------------------------------------
|
| 2 |
+
# Octree-based Sparse Convolutional Neural Networks
|
| 3 |
+
# Copyright (c) 2022 Peng-Shuai Wang <wangps@hotmail.com>
|
| 4 |
+
# Licensed under The MIT License [see LICENSE for details]
|
| 5 |
+
# Written by Peng-Shuai Wang
|
| 6 |
+
# --------------------------------------------------------
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
from typing import Optional, Union
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class KeyLUT:
|
| 13 |
+
def __init__(self):
|
| 14 |
+
r256 = torch.arange(256, dtype=torch.int64)
|
| 15 |
+
r512 = torch.arange(512, dtype=torch.int64)
|
| 16 |
+
zero = torch.zeros(256, dtype=torch.int64)
|
| 17 |
+
device = torch.device("cpu")
|
| 18 |
+
|
| 19 |
+
self._encode = {
|
| 20 |
+
device: (
|
| 21 |
+
self.xyz2key(r256, zero, zero, 8),
|
| 22 |
+
self.xyz2key(zero, r256, zero, 8),
|
| 23 |
+
self.xyz2key(zero, zero, r256, 8),
|
| 24 |
+
)
|
| 25 |
+
}
|
| 26 |
+
self._decode = {device: self.key2xyz(r512, 9)}
|
| 27 |
+
|
| 28 |
+
def encode_lut(self, device=torch.device("cpu")):
|
| 29 |
+
if device not in self._encode:
|
| 30 |
+
cpu = torch.device("cpu")
|
| 31 |
+
self._encode[device] = tuple(e.to(device) for e in self._encode[cpu])
|
| 32 |
+
return self._encode[device]
|
| 33 |
+
|
| 34 |
+
def decode_lut(self, device=torch.device("cpu")):
|
| 35 |
+
if device not in self._decode:
|
| 36 |
+
cpu = torch.device("cpu")
|
| 37 |
+
self._decode[device] = tuple(e.to(device) for e in self._decode[cpu])
|
| 38 |
+
return self._decode[device]
|
| 39 |
+
|
| 40 |
+
def xyz2key(self, x, y, z, depth):
|
| 41 |
+
key = torch.zeros_like(x)
|
| 42 |
+
for i in range(depth):
|
| 43 |
+
mask = 1 << i
|
| 44 |
+
key = (
|
| 45 |
+
key
|
| 46 |
+
| ((x & mask) << (2 * i + 2))
|
| 47 |
+
| ((y & mask) << (2 * i + 1))
|
| 48 |
+
| ((z & mask) << (2 * i + 0))
|
| 49 |
+
)
|
| 50 |
+
return key
|
| 51 |
+
|
| 52 |
+
def key2xyz(self, key, depth):
|
| 53 |
+
x = torch.zeros_like(key)
|
| 54 |
+
y = torch.zeros_like(key)
|
| 55 |
+
z = torch.zeros_like(key)
|
| 56 |
+
for i in range(depth):
|
| 57 |
+
x = x | ((key & (1 << (3 * i + 2))) >> (2 * i + 2))
|
| 58 |
+
y = y | ((key & (1 << (3 * i + 1))) >> (2 * i + 1))
|
| 59 |
+
z = z | ((key & (1 << (3 * i + 0))) >> (2 * i + 0))
|
| 60 |
+
return x, y, z
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
_key_lut = KeyLUT()
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def xyz2key(
|
| 67 |
+
x: torch.Tensor,
|
| 68 |
+
y: torch.Tensor,
|
| 69 |
+
z: torch.Tensor,
|
| 70 |
+
b: Optional[Union[torch.Tensor, int]] = None,
|
| 71 |
+
depth: int = 16,
|
| 72 |
+
):
|
| 73 |
+
r"""Encodes :attr:`x`, :attr:`y`, :attr:`z` coordinates to the shuffled keys
|
| 74 |
+
based on pre-computed look up tables. The speed of this function is much
|
| 75 |
+
faster than the method based on for-loop.
|
| 76 |
+
|
| 77 |
+
Args:
|
| 78 |
+
x (torch.Tensor): The x coordinate.
|
| 79 |
+
y (torch.Tensor): The y coordinate.
|
| 80 |
+
z (torch.Tensor): The z coordinate.
|
| 81 |
+
b (torch.Tensor or int): The batch index of the coordinates, and should be
|
| 82 |
+
smaller than 32768. If :attr:`b` is :obj:`torch.Tensor`, the size of
|
| 83 |
+
:attr:`b` must be the same as :attr:`x`, :attr:`y`, and :attr:`z`.
|
| 84 |
+
depth (int): The depth of the shuffled key, and must be smaller than 17 (< 17).
|
| 85 |
+
"""
|
| 86 |
+
|
| 87 |
+
EX, EY, EZ = _key_lut.encode_lut(x.device)
|
| 88 |
+
x, y, z = x.long(), y.long(), z.long()
|
| 89 |
+
|
| 90 |
+
mask = 255 if depth > 8 else (1 << depth) - 1
|
| 91 |
+
key = EX[x & mask] | EY[y & mask] | EZ[z & mask]
|
| 92 |
+
if depth > 8:
|
| 93 |
+
mask = (1 << (depth - 8)) - 1
|
| 94 |
+
key16 = EX[(x >> 8) & mask] | EY[(y >> 8) & mask] | EZ[(z >> 8) & mask]
|
| 95 |
+
key = key16 << 24 | key
|
| 96 |
+
|
| 97 |
+
if b is not None:
|
| 98 |
+
b = b.long()
|
| 99 |
+
key = b << 48 | key
|
| 100 |
+
|
| 101 |
+
return key
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def key2xyz(key: torch.Tensor, depth: int = 16):
|
| 105 |
+
r"""Decodes the shuffled key to :attr:`x`, :attr:`y`, :attr:`z` coordinates
|
| 106 |
+
and the batch index based on pre-computed look up tables.
|
| 107 |
+
|
| 108 |
+
Args:
|
| 109 |
+
key (torch.Tensor): The shuffled key.
|
| 110 |
+
depth (int): The depth of the shuffled key, and must be smaller than 17 (< 17).
|
| 111 |
+
"""
|
| 112 |
+
|
| 113 |
+
DX, DY, DZ = _key_lut.decode_lut(key.device)
|
| 114 |
+
x, y, z = torch.zeros_like(key), torch.zeros_like(key), torch.zeros_like(key)
|
| 115 |
+
|
| 116 |
+
b = key >> 48
|
| 117 |
+
key = key & ((1 << 48) - 1)
|
| 118 |
+
|
| 119 |
+
n = (depth + 2) // 3
|
| 120 |
+
for i in range(n):
|
| 121 |
+
k = key >> (i * 9) & 511
|
| 122 |
+
x = x | (DX[k] << (i * 3))
|
| 123 |
+
y = y | (DY[k] << (i * 3))
|
| 124 |
+
z = z | (DZ[k] << (i * 3))
|
| 125 |
+
|
| 126 |
+
return x, y, z, b
|
OVOW/engine/oneposeviagen/Amodal3R/inference.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
os.environ['ATTN_BACKEND'] = 'xformers' # Can be 'flash-attn' or 'xformers', default is 'flash-attn'
|
| 3 |
+
# os.environ['SPCONV_ALGO'] = 'native' # Can be 'native' or 'auto', default is 'auto'.
|
| 4 |
+
# 'auto' is faster but will do benchmarking at the beginning.
|
| 5 |
+
# Recommended to set to 'native' if run only once.
|
| 6 |
+
|
| 7 |
+
import numpy as np
|
| 8 |
+
import imageio
|
| 9 |
+
from PIL import Image
|
| 10 |
+
from amodal3r.pipelines import Amodal3RImageTo3DPipeline
|
| 11 |
+
from amodal3r.utils import render_utils, postprocessing_utils
|
| 12 |
+
import cv2
|
| 13 |
+
import trimesh
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def extract_glb(gs, mesh, mesh_simplify=0.95, texture_size=1024, export_path="output.glb"):
|
| 17 |
+
"""
|
| 18 |
+
Extract a GLB file from the 3D model.
|
| 19 |
+
|
| 20 |
+
Args:
|
| 21 |
+
state (dict): The state of the generated 3D model.
|
| 22 |
+
mesh_simplify (float): The mesh simplification factor.
|
| 23 |
+
texture_size (int): The texture resolution.
|
| 24 |
+
|
| 25 |
+
Returns:
|
| 26 |
+
str: The path to the extracted GLB file.
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
glb = postprocessing_utils.to_glb(gs, mesh, simplify=mesh_simplify, texture_size=texture_size, verbose=False)
|
| 30 |
+
glb.export(export_path)
|
| 31 |
+
return export_path
|
| 32 |
+
|
| 33 |
+
def save_mesh(mesh_result, filename):
|
| 34 |
+
vertices = mesh_result.vertices.cpu().numpy() if hasattr(mesh_result.vertices, 'cpu') else mesh_result.vertices
|
| 35 |
+
faces = mesh_result.faces.cpu().numpy() if hasattr(mesh_result.faces, 'cpu') else mesh_result.faces
|
| 36 |
+
|
| 37 |
+
mesh = trimesh.Trimesh(vertices=vertices, faces=faces, process=False)
|
| 38 |
+
|
| 39 |
+
if mesh_result.vertex_attrs is not None:
|
| 40 |
+
attrs = mesh_result.vertex_attrs.cpu().numpy() if hasattr(mesh_result.vertex_attrs, 'cpu') else mesh_result.vertex_attrs
|
| 41 |
+
mesh.visual.vertex_colors = attrs
|
| 42 |
+
|
| 43 |
+
mesh.export(filename)
|
| 44 |
+
|
| 45 |
+
# Load a pipeline from a model folder or a Hugging Face model hub.
|
| 46 |
+
pipeline = Amodal3RImageTo3DPipeline.from_pretrained("/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/Amodal3R/Amodal3R")
|
| 47 |
+
pipeline.cuda()
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
output_dir = "./output/1/"
|
| 51 |
+
os.makedirs(output_dir, exist_ok=True)
|
| 52 |
+
|
| 53 |
+
# can be single image or multiple images
|
| 54 |
+
images = [
|
| 55 |
+
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"),
|
| 56 |
+
]
|
| 57 |
+
|
| 58 |
+
masks = [
|
| 59 |
+
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"),
|
| 60 |
+
]
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
# Run the pipeline
|
| 64 |
+
outputs = pipeline.run_multi_image(
|
| 65 |
+
images,
|
| 66 |
+
masks,
|
| 67 |
+
seed=1,
|
| 68 |
+
# Optional parameters
|
| 69 |
+
sparse_structure_sampler_params={
|
| 70 |
+
"steps": 12,
|
| 71 |
+
"cfg_strength": 7.5,
|
| 72 |
+
},
|
| 73 |
+
slat_sampler_params={
|
| 74 |
+
"steps": 12,
|
| 75 |
+
"cfg_strength": 3,
|
| 76 |
+
},
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
# save as gif
|
| 80 |
+
video_gs = render_utils.render_video(outputs['gaussian'][0], bg_color=(1, 1, 1))['color']
|
| 81 |
+
video_mesh = render_utils.render_video(outputs['mesh'][0], bg_color=(1, 1, 1))['normal']
|
| 82 |
+
video = [np.concatenate([frame_gs, frame_mesh], axis=1) for frame_gs, frame_mesh in zip(video_gs, video_mesh)]
|
| 83 |
+
imageio.mimsave(os.path.join(output_dir, "sample_multi.gif"), video, fps=30)
|
| 84 |
+
|
| 85 |
+
# save multi-view gs and mesh
|
| 86 |
+
# gaussian = outputs['gaussian'][0]
|
| 87 |
+
# multi_view_gs,_,_ = render_utils.render_multiview(gaussian, nviews=8, bg_color=(1, 1, 1))
|
| 88 |
+
# multi_view_gs = multi_view_gs['color']
|
| 89 |
+
# for i in range(8):
|
| 90 |
+
# output = multi_view_gs[i]
|
| 91 |
+
# output = cv2.cvtColor(output, cv2.COLOR_RGB2BGR)
|
| 92 |
+
# cv2.imwrite(os.path.join(output_dir, f"{i:03d}_gs.png"), output)
|
| 93 |
+
|
| 94 |
+
mesh = outputs['mesh'][0]
|
| 95 |
+
# multi_view_mesh,_,_ = render_utils.render_multiview(mesh, nviews=8, bg_color=(1, 1, 1))
|
| 96 |
+
# multi_view_mesh = multi_view_mesh['normal']
|
| 97 |
+
# for i in range(8):
|
| 98 |
+
# output = multi_view_mesh[i]
|
| 99 |
+
# output = cv2.cvtColor(output, cv2.COLOR_RGB2BGR)
|
| 100 |
+
# cv2.imwrite(os.path.join(output_dir, f"{i:03d}_mesh.png"), output)
|
| 101 |
+
|
| 102 |
+
# # save mesh
|
| 103 |
+
save_mesh(mesh, os.path.join(output_dir, "mesh.ply"))
|
| 104 |
+
|
| 105 |
+
# export glb if needed
|
| 106 |
+
glb_path = os.path.join(output_dir, "mesh.glb")
|
| 107 |
+
extract_glb(outputs['gaussian'][0], outputs['mesh'][0], 0.5, 1024, glb_path)
|
OVOW/engine/oneposeviagen/Amodal3R/lightning/network_slat.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch,random
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
from torch.nn import functional as F
|
| 4 |
+
import numpy as np
|
| 5 |
+
|
| 6 |
+
import pytorch_lightning as L
|
| 7 |
+
from torchvision import transforms
|
| 8 |
+
|
| 9 |
+
from amodal3r.models import SLatFlowModelMaskAsCondWeighted
|
| 10 |
+
|
| 11 |
+
from dit.diffusion_slat import GaussianDiffusion, get_betas
|
| 12 |
+
|
| 13 |
+
from safetensors.torch import load_file
|
| 14 |
+
|
| 15 |
+
class mask_patcher(nn.Module):
|
| 16 |
+
def __init__(self):
|
| 17 |
+
super(mask_patcher, self).__init__()
|
| 18 |
+
|
| 19 |
+
def forward(self, mask, patch_size=14):
|
| 20 |
+
"""
|
| 21 |
+
Inputs:
|
| 22 |
+
mask: tensor, size [B, H, W] (e.g., the original mask might not be 518x518)
|
| 23 |
+
patch_size: the size of each patch, default is 14 (since 518/14=37)
|
| 24 |
+
Outputs:
|
| 25 |
+
patch_ratio: tensor, size [B, 37, 37], where each element represents the ratio of 1's in the corresponding patch of the mask
|
| 26 |
+
"""
|
| 27 |
+
# 1. Resize the mask if the shape is not (518, 518)
|
| 28 |
+
if mask.shape != (518, 518):
|
| 29 |
+
mask = F.interpolate(mask.unsqueeze(1).float(), size=(518, 518), mode='nearest') # [B, 1, 518, 518]
|
| 30 |
+
else:
|
| 31 |
+
mask = mask.unsqueeze(1).float()
|
| 32 |
+
|
| 33 |
+
# 2. Use unfold to divide the mask into non-overlapping patches
|
| 34 |
+
# Unfold parameters: dimension, window size, stride
|
| 35 |
+
patches = mask.unfold(2, patch_size, patch_size).unfold(3, patch_size, patch_size)
|
| 36 |
+
# At this point, patches have shape [B, 1, 37, 37, 14, 14]
|
| 37 |
+
|
| 38 |
+
# 3. For each patch, compute the ratio of ones in the mask by taking the mean
|
| 39 |
+
patch_ratio = patches.mean(dim=(-1, -2)) # Shape becomes [B, 1, 37, 37]
|
| 40 |
+
|
| 41 |
+
# 4. Remove the channel dimension
|
| 42 |
+
patch_ratio = patch_ratio.squeeze(1) # Final shape is [B, 37, 37]
|
| 43 |
+
|
| 44 |
+
return patch_ratio
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class Network_slat(L.LightningModule):
|
| 48 |
+
def __init__(self, cfg, white_bkgd=True):
|
| 49 |
+
super(Network_slat, self).__init__()
|
| 50 |
+
|
| 51 |
+
self.cfg = cfg
|
| 52 |
+
|
| 53 |
+
self.slat_model = SLatFlowModelMaskAsCondWeighted(resolution=64,
|
| 54 |
+
in_channels=8,
|
| 55 |
+
out_channels=8,
|
| 56 |
+
model_channels=1024,
|
| 57 |
+
cond_channels=1024,
|
| 58 |
+
num_blocks=24,
|
| 59 |
+
num_heads=16,
|
| 60 |
+
mlp_ratio=4,
|
| 61 |
+
patch_size=2,
|
| 62 |
+
num_io_res_blocks=2,
|
| 63 |
+
io_block_channels=[128],
|
| 64 |
+
pe_mode='ape',
|
| 65 |
+
qk_rms_norm=True,
|
| 66 |
+
use_fp16=False,
|
| 67 |
+
use_checkpoint=True,
|
| 68 |
+
mask_cond_type='mask_patcher'
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
for _, param in self.slat_model.named_parameters():
|
| 72 |
+
param.requires_grad = True
|
| 73 |
+
|
| 74 |
+
# diffusion model
|
| 75 |
+
betas = get_betas(schedule_type='linear', b_start=0.0001, b_end=0.02, time_num=1000)
|
| 76 |
+
self.diffusion = GaussianDiffusion(betas, loss_type='mse', model_mean_type='eps', model_var_type='fixedsmall')
|
| 77 |
+
|
| 78 |
+
dinov2_model = torch.hub.load('facebookresearch/dinov2', 'dinov2_vitl14_reg', pretrained=True)
|
| 79 |
+
dinov2_model.eval()
|
| 80 |
+
for param in dinov2_model.parameters():
|
| 81 |
+
param.requires_grad = False
|
| 82 |
+
self.img_encoder = dinov2_model
|
| 83 |
+
transform = transforms.Compose([
|
| 84 |
+
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
|
| 85 |
+
])
|
| 86 |
+
self.image_cond_model_transform = transform
|
| 87 |
+
self.img_encoder_feat_dim = 1024
|
| 88 |
+
|
| 89 |
+
self.std = torch.tensor([2.377650737762451,2.386378288269043,2.124418020248413,2.1748552322387695,2.663944721221924,2.371192216873169,2.6217446327209473,2.684523105621338])[None]
|
| 90 |
+
self.mean = torch.tensor([-2.1687545776367188, -0.004347046371549368,-0.13352349400520325,-0.08418072760105133,-0.5271206498146057,0.7238689064979553,-1.1414450407028198,1.2039363384246826])[None]
|
| 91 |
+
|
| 92 |
+
self.mask_patcher = mask_patcher()
|
| 93 |
+
|
| 94 |
+
self.load_pretrained_slat()
|
| 95 |
+
|
| 96 |
+
def load_pretrained_slat(self):
|
| 97 |
+
slat_model_weight = load_file("./ckpts/slat_flow_img_dit_L_64l8p2_fp16.safetensors")
|
| 98 |
+
self.slat_model.load_state_dict(slat_model_weight, strict=False)
|
| 99 |
+
print("load slat model")
|
| 100 |
+
|
| 101 |
+
def encode_image(self, inp_imgs):
|
| 102 |
+
B, _, _, _ = inp_imgs.shape
|
| 103 |
+
inp_imgs = inp_imgs.permute(0, 3, 1, 2)
|
| 104 |
+
inp_imgs = torch.stack([self.image_cond_model_transform(inp_imgs[i]) for i in range(B)], dim=0)
|
| 105 |
+
encode_imgs = self.img_encoder(inp_imgs, is_training=True)['x_prenorm']#['x_norm_patchtokens'] # [B*N, 37*37, 1024]
|
| 106 |
+
encode_imgs = F.layer_norm(encode_imgs, encode_imgs.shape[-1:])
|
| 107 |
+
return encode_imgs
|
| 108 |
+
|
| 109 |
+
def logit_normal(self, std, mean, size, device):
|
| 110 |
+
# Generate samples from logit-normal distribution
|
| 111 |
+
normal_samples = torch.randn(size, device=device) * std + mean
|
| 112 |
+
logit_samples = torch.sigmoid(normal_samples) # Apply logit transformation
|
| 113 |
+
return logit_samples
|
| 114 |
+
|
| 115 |
+
def _denoise(self, x, t, c):
|
| 116 |
+
t = t * 1000
|
| 117 |
+
out = self.slat_model(x, t, c)
|
| 118 |
+
return out
|
| 119 |
+
|
| 120 |
+
def forward(self, batch, if_vis=False):
|
| 121 |
+
cond_img = batch['cond_img_518_masked']
|
| 122 |
+
visibility_mask = batch['visibility_mask']
|
| 123 |
+
occlusion_mask = batch['occlusion_mask']
|
| 124 |
+
slat_paths = batch['slat_path']
|
| 125 |
+
B = len(slat_paths)
|
| 126 |
+
sp_feats, sp_coords = [], []
|
| 127 |
+
for idx, slat_path in enumerate(slat_paths):
|
| 128 |
+
slat_data = np.load(slat_path)
|
| 129 |
+
coords = torch.from_numpy(slat_data['coords']).int().to(self.device)
|
| 130 |
+
feats = torch.from_numpy(slat_data['feats']).float().to(self.device)
|
| 131 |
+
feats = (feats - self.mean.to(self.device)) / self.std.to(self.device)
|
| 132 |
+
coords = torch.cat([idx*torch.ones_like(coords[:, 0]).unsqueeze(1), coords], dim=1)
|
| 133 |
+
sp_feats.append(feats)
|
| 134 |
+
sp_coords.append(coords)
|
| 135 |
+
|
| 136 |
+
# extract image features
|
| 137 |
+
if random.random() > 0.1:
|
| 138 |
+
with torch.no_grad():
|
| 139 |
+
encoded_cond_img = self.encode_image(cond_img)
|
| 140 |
+
visibility_mask = self.mask_patcher(1-visibility_mask)
|
| 141 |
+
visibility_mask = visibility_mask.view(B, -1).unsqueeze(-1).repeat(1, 1, 1024)
|
| 142 |
+
occlusion_mask = self.mask_patcher(occlusion_mask)
|
| 143 |
+
occlusion_mask = occlusion_mask.view(B, -1).unsqueeze(-1).repeat(1, 1, 1024)
|
| 144 |
+
cond_img = torch.cat([encoded_cond_img, visibility_mask, occlusion_mask], dim=1)
|
| 145 |
+
else:
|
| 146 |
+
cond_img = torch.zeros((B,1374+37*37+37*37,1024)).to(cond_img.device).to(cond_img.dtype)
|
| 147 |
+
|
| 148 |
+
t = self.logit_normal(1.0, 1.0, (B,), device="cuda") # see trellis training details
|
| 149 |
+
|
| 150 |
+
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)
|
| 151 |
+
loss = loss.mean()
|
| 152 |
+
|
| 153 |
+
return None, loss
|
OVOW/engine/oneposeviagen/Amodal3R/lightning/network_ss.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch,random
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
from torch.nn import functional as F
|
| 4 |
+
|
| 5 |
+
import pytorch_lightning as L
|
| 6 |
+
from torchvision import transforms
|
| 7 |
+
|
| 8 |
+
from amodal3r.models import SparseStructureFlowModelMaskAsCondWeighted
|
| 9 |
+
|
| 10 |
+
from dit.diffusion_ss import GaussianDiffusion, get_betas
|
| 11 |
+
from safetensors.torch import load_file
|
| 12 |
+
|
| 13 |
+
class mask_patcher(nn.Module):
|
| 14 |
+
def __init__(self):
|
| 15 |
+
super(mask_patcher, self).__init__()
|
| 16 |
+
|
| 17 |
+
def forward(self, mask, patch_size=14):
|
| 18 |
+
"""
|
| 19 |
+
Inputs:
|
| 20 |
+
mask: tensor, size [B, H, W] (e.g., the original mask might not be 518x518)
|
| 21 |
+
patch_size: the size of each patch, default is 14 (since 518/14=37)
|
| 22 |
+
Outputs:
|
| 23 |
+
patch_ratio: tensor, size [B, 37, 37], where each element represents the ratio of 1's in the corresponding patch of the mask
|
| 24 |
+
"""
|
| 25 |
+
# 1. Resize the mask if the shape is not (518, 518)
|
| 26 |
+
if mask.shape != (518, 518):
|
| 27 |
+
mask = F.interpolate(mask.unsqueeze(1).float(), size=(518, 518), mode='nearest') # [B, 1, 518, 518]
|
| 28 |
+
else:
|
| 29 |
+
mask = mask.unsqueeze(1).float()
|
| 30 |
+
|
| 31 |
+
# 2. Use unfold to divide the mask into non-overlapping patches
|
| 32 |
+
# Unfold parameters: dimension, window size, stride
|
| 33 |
+
patches = mask.unfold(2, patch_size, patch_size).unfold(3, patch_size, patch_size)
|
| 34 |
+
# At this point, patches have shape [B, 1, 37, 37, 14, 14]
|
| 35 |
+
|
| 36 |
+
# 3. For each patch, compute the ratio of ones in the mask by taking the mean
|
| 37 |
+
patch_ratio = patches.mean(dim=(-1, -2)) # Shape becomes [B, 1, 37, 37]
|
| 38 |
+
|
| 39 |
+
# 4. Remove the channel dimension
|
| 40 |
+
patch_ratio = patch_ratio.squeeze(1) # Final shape is [B, 37, 37]
|
| 41 |
+
|
| 42 |
+
return patch_ratio
|
| 43 |
+
|
| 44 |
+
class Network_ss(L.LightningModule):
|
| 45 |
+
def __init__(self, cfg, white_bkgd=True):
|
| 46 |
+
super(Network_ss, self).__init__()
|
| 47 |
+
|
| 48 |
+
self.cfg = cfg
|
| 49 |
+
|
| 50 |
+
self.ss_model = SparseStructureFlowModelMaskAsCondWeighted(resolution=16,
|
| 51 |
+
in_channels=8,
|
| 52 |
+
out_channels=8,
|
| 53 |
+
model_channels=1024,
|
| 54 |
+
cond_channels=1024,
|
| 55 |
+
num_blocks=24,
|
| 56 |
+
num_heads=16,
|
| 57 |
+
mlp_ratio=4,
|
| 58 |
+
patch_size=1,
|
| 59 |
+
pe_mode='ape',
|
| 60 |
+
qk_rms_norm=True,
|
| 61 |
+
use_fp16=False,
|
| 62 |
+
use_checkpoint=True,
|
| 63 |
+
mask_cond_type='mask_patcher')
|
| 64 |
+
|
| 65 |
+
# diffusion model
|
| 66 |
+
betas = get_betas(schedule_type='linear', b_start=0.0001, b_end=0.02, time_num=1000)
|
| 67 |
+
self.diffusion = GaussianDiffusion(betas, loss_type='mse', model_mean_type='eps', model_var_type='fixedsmall')
|
| 68 |
+
|
| 69 |
+
dinov2_model = torch.hub.load('facebookresearch/dinov2', 'dinov2_vitl14_reg', pretrained=True)
|
| 70 |
+
dinov2_model.eval()
|
| 71 |
+
for param in dinov2_model.parameters():
|
| 72 |
+
param.requires_grad = False
|
| 73 |
+
self.img_encoder = dinov2_model
|
| 74 |
+
transform = transforms.Compose([
|
| 75 |
+
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
|
| 76 |
+
])
|
| 77 |
+
self.image_cond_model_transform = transform
|
| 78 |
+
self.img_encoder_feat_dim = 1024
|
| 79 |
+
|
| 80 |
+
self.mask_patcher = mask_patcher()
|
| 81 |
+
|
| 82 |
+
self.load_pretrained_ss()
|
| 83 |
+
|
| 84 |
+
def load_pretrained_ss(self):
|
| 85 |
+
ss_model_weight = load_file("./ckpts/ss_flow_img_dit_L_16l8_fp16.safetensors")
|
| 86 |
+
self.ss_model.load_state_dict(ss_model_weight, strict=False)
|
| 87 |
+
print("load ss model")
|
| 88 |
+
|
| 89 |
+
def encode_image(self, inp_imgs):
|
| 90 |
+
B, _, _, _ = inp_imgs.shape
|
| 91 |
+
inp_imgs = inp_imgs.permute(0, 3, 1, 2)
|
| 92 |
+
inp_imgs = torch.stack([self.image_cond_model_transform(inp_imgs[i]) for i in range(B)], dim=0)
|
| 93 |
+
encode_imgs = self.img_encoder(inp_imgs, is_training=True)['x_prenorm']
|
| 94 |
+
encode_imgs = F.layer_norm(encode_imgs, encode_imgs.shape[-1:])
|
| 95 |
+
return encode_imgs
|
| 96 |
+
|
| 97 |
+
def logit_normal(self, std, mean, size, device):
|
| 98 |
+
# Generate samples from logit-normal distribution
|
| 99 |
+
normal_samples = torch.randn(size, device=device) * std + mean
|
| 100 |
+
logit_samples = torch.sigmoid(normal_samples) # Apply logit transformation
|
| 101 |
+
return logit_samples
|
| 102 |
+
|
| 103 |
+
def _denoise(self, x, t, c):
|
| 104 |
+
t = t * 1000
|
| 105 |
+
out = self.ss_model(x, t, c)
|
| 106 |
+
return out
|
| 107 |
+
|
| 108 |
+
def forward(self, batch, if_vis=False):
|
| 109 |
+
cond_img = batch['cond_img_518_masked']
|
| 110 |
+
visibility_mask = batch['visibility_mask']
|
| 111 |
+
occlusion_mask = batch['occlusion_mask']
|
| 112 |
+
z_s = batch['ss_latent']
|
| 113 |
+
B,_,_,_,_ = z_s.shape
|
| 114 |
+
|
| 115 |
+
# extract image features, droprate 10%
|
| 116 |
+
random_num = random.random()
|
| 117 |
+
if 0.1 < random_num:
|
| 118 |
+
with torch.no_grad():
|
| 119 |
+
encoded_cond_img = self.encode_image(cond_img)
|
| 120 |
+
patched_visibility_mask = self.mask_patcher(visibility_mask)
|
| 121 |
+
visibility_mask_token = patched_visibility_mask.view(B, -1).unsqueeze(-1).repeat(1, 1, 1024)
|
| 122 |
+
patched_occlusion_mask = self.mask_patcher(occlusion_mask)
|
| 123 |
+
occlusion_mask_token = patched_occlusion_mask.view(B, -1).unsqueeze(-1).repeat(1, 1, 1024)
|
| 124 |
+
cond_img = torch.cat([encoded_cond_img, visibility_mask_token, occlusion_mask_token], dim=1)
|
| 125 |
+
else:
|
| 126 |
+
cond_img = torch.zeros((B,1374+37*37+37*37,1024)).to(cond_img.device).to(cond_img.dtype)
|
| 127 |
+
|
| 128 |
+
t = self.logit_normal(1.0, 1.0, (B,), device="cuda") # follow trellis training details
|
| 129 |
+
|
| 130 |
+
loss, _ = self.diffusion.p_losses(denoise_fn=self._denoise, data_start=z_s, t=t, y=cond_img)
|
| 131 |
+
loss = loss.mean()
|
| 132 |
+
|
| 133 |
+
return None, loss
|
OVOW/engine/oneposeviagen/Amodal3R/lightning/system.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import torch
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pytorch_lightning as L
|
| 5 |
+
|
| 6 |
+
import torch.nn as nn
|
| 7 |
+
from lightning.utils import vis_images, CosineWarmupScheduler
|
| 8 |
+
|
| 9 |
+
from lightning.network_ss import Network_ss
|
| 10 |
+
from lightning.network_slat import Network_slat
|
| 11 |
+
|
| 12 |
+
import matplotlib.pyplot as plt
|
| 13 |
+
import os
|
| 14 |
+
import shutil
|
| 15 |
+
|
| 16 |
+
class system(L.LightningModule):
|
| 17 |
+
def __init__(self, cfg, cfg_path=None):
|
| 18 |
+
super().__init__()
|
| 19 |
+
|
| 20 |
+
self.cfg = cfg
|
| 21 |
+
if cfg.model.type == 'ss':
|
| 22 |
+
self.net = Network_ss(cfg)
|
| 23 |
+
elif cfg.model.type == 'slat':
|
| 24 |
+
self.net = Network_slat(cfg)
|
| 25 |
+
|
| 26 |
+
self.validation_step_outputs = []
|
| 27 |
+
|
| 28 |
+
self.vis_dir = cfg.vis_dir
|
| 29 |
+
os.makedirs(self.vis_dir, exist_ok=True)
|
| 30 |
+
if cfg_path is not None:
|
| 31 |
+
shutil.copy(cfg_path, os.path.join(self.vis_dir, 'config.yaml'))
|
| 32 |
+
|
| 33 |
+
def training_step(self, batch, batch_idx):
|
| 34 |
+
with torch.amp.autocast('cuda'):
|
| 35 |
+
output, loss = self.net(batch)
|
| 36 |
+
if output is not None:
|
| 37 |
+
if 0 == self.trainer.global_step % 1000 and (self.trainer.local_rank == 0):
|
| 38 |
+
self.vis_results(output, batch, prex='train')
|
| 39 |
+
self.log(f'rec', loss, prog_bar=True)
|
| 40 |
+
return loss
|
| 41 |
+
|
| 42 |
+
def validation_step(self, batch, batch_idx):
|
| 43 |
+
self.net.eval()
|
| 44 |
+
output, loss = self.net(batch, if_vis=True)
|
| 45 |
+
if output is not None:
|
| 46 |
+
if batch_idx == 0 and (self.trainer.local_rank == 0):
|
| 47 |
+
self.vis_results(output, batch, prex='val')
|
| 48 |
+
self.validation_step_outputs.append({'rec': loss})
|
| 49 |
+
return loss
|
| 50 |
+
|
| 51 |
+
def on_validation_epoch_end(self):
|
| 52 |
+
keys = self.validation_step_outputs[0]
|
| 53 |
+
for key in keys:
|
| 54 |
+
prog_bar = True if key in ['psnr','mask','depth', 'rec'] else False
|
| 55 |
+
metric_mean = torch.stack([x[key] for x in self.validation_step_outputs]).mean()
|
| 56 |
+
self.log(f'val/{key}', metric_mean, prog_bar=prog_bar, sync_dist=True)
|
| 57 |
+
|
| 58 |
+
self.validation_step_outputs.clear() # free memory
|
| 59 |
+
torch.cuda.empty_cache()
|
| 60 |
+
|
| 61 |
+
def vis_results(self, output, batch, prex):
|
| 62 |
+
output_vis = vis_images(output, batch)
|
| 63 |
+
for key, value in output_vis.items():
|
| 64 |
+
imgs = [np.concatenate([img for img in value],axis=0)]
|
| 65 |
+
for idx, img in enumerate(imgs):
|
| 66 |
+
img_save_path = os.path.join(self.vis_dir, f'{prex}_{self.global_step}_{key}.png')
|
| 67 |
+
plt.imsave(img_save_path, img)
|
| 68 |
+
self.net.train()
|
| 69 |
+
if hasattr(self.net, 'img_encoder'):
|
| 70 |
+
self.net.img_encoder.eval()
|
| 71 |
+
|
| 72 |
+
def num_steps(self) -> int:
|
| 73 |
+
"""Get number of steps"""
|
| 74 |
+
# Accessing _data_source is flaky and might break
|
| 75 |
+
dataset = self.trainer.fit_loop._data_source.dataloader()
|
| 76 |
+
dataset_size = len(dataset)
|
| 77 |
+
num_devices = max(1, self.trainer.num_devices)
|
| 78 |
+
num_steps = dataset_size * self.trainer.max_epochs * self.cfg.train.limit_train_batches // (self.trainer.accumulate_grad_batches * num_devices)
|
| 79 |
+
return int(num_steps)
|
| 80 |
+
|
| 81 |
+
def configure_optimizers(self):
|
| 82 |
+
decay_params, no_decay_params = [], []
|
| 83 |
+
|
| 84 |
+
# add all bias and LayerNorm params to no_decay_params
|
| 85 |
+
for name, module in self.named_modules():
|
| 86 |
+
if isinstance(module, nn.LayerNorm):
|
| 87 |
+
no_decay_params.extend([p for p in module.parameters()])
|
| 88 |
+
elif hasattr(module, 'bias') and module.bias is not None:
|
| 89 |
+
no_decay_params.append(module.bias)
|
| 90 |
+
|
| 91 |
+
# add remaining parameters to decay_params
|
| 92 |
+
_no_decay_ids = set(map(id, no_decay_params))
|
| 93 |
+
decay_params = [p for p in self.parameters() if id(p) not in _no_decay_ids]
|
| 94 |
+
|
| 95 |
+
# filter out parameters with no grad
|
| 96 |
+
decay_params = list(filter(lambda p: p.requires_grad, decay_params))
|
| 97 |
+
no_decay_params = list(filter(lambda p: p.requires_grad, no_decay_params))
|
| 98 |
+
|
| 99 |
+
# Optimizer
|
| 100 |
+
opt_groups = [
|
| 101 |
+
{'params': decay_params, 'weight_decay': self.cfg.train.weight_decay},
|
| 102 |
+
{'params': no_decay_params, 'weight_decay': 0.0},
|
| 103 |
+
]
|
| 104 |
+
optimizer = torch.optim.AdamW(
|
| 105 |
+
opt_groups,
|
| 106 |
+
lr=self.cfg.train.lr,
|
| 107 |
+
betas=(self.cfg.train.beta1, self.cfg.train.beta2),
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
total_global_batches = self.num_steps()
|
| 111 |
+
scheduler = CosineWarmupScheduler(
|
| 112 |
+
optimizer=optimizer,
|
| 113 |
+
warmup_iters=self.cfg.train.warmup_iters,
|
| 114 |
+
max_iters=total_global_batches,
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
return {"optimizer": optimizer,
|
| 118 |
+
"lr_scheduler": {
|
| 119 |
+
'scheduler': scheduler,
|
| 120 |
+
'interval': 'step' # or 'epoch' for epoch-level updates
|
| 121 |
+
}}
|
OVOW/engine/oneposeviagen/Amodal3R/lightning/utils.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch, os, json, math
|
| 2 |
+
import numpy as np
|
| 3 |
+
from torch.optim.lr_scheduler import LRScheduler
|
| 4 |
+
|
| 5 |
+
def init_volume_grid(bound=0.45, num_pts_each_axis=32):
|
| 6 |
+
# Define the range and number of points
|
| 7 |
+
start = -bound
|
| 8 |
+
stop = bound
|
| 9 |
+
num_points = num_pts_each_axis # Adjust the number of points to your preference
|
| 10 |
+
|
| 11 |
+
# Create a linear space for each axis
|
| 12 |
+
x = np.linspace(start, stop, num_points)
|
| 13 |
+
y = np.linspace(start, stop, num_points)
|
| 14 |
+
z = np.linspace(start, stop, num_points)
|
| 15 |
+
|
| 16 |
+
# Create a 3D grid of points using meshgrid
|
| 17 |
+
X, Y, Z = np.meshgrid(x, y, z, indexing='ij')
|
| 18 |
+
|
| 19 |
+
# Stack the grid points in a single array of shape (N, 3)
|
| 20 |
+
xyz = np.vstack((X.ravel(), Y.ravel(), Z.ravel())).T
|
| 21 |
+
|
| 22 |
+
return xyz
|
| 23 |
+
|
| 24 |
+
def getProjectionMatrix(znear, zfar, fovX, fovY):
|
| 25 |
+
|
| 26 |
+
tanHalfFovY = torch.tan((fovY / 2))
|
| 27 |
+
tanHalfFovX = torch.tan((fovX / 2))
|
| 28 |
+
|
| 29 |
+
P = torch.zeros(4, 4)
|
| 30 |
+
|
| 31 |
+
z_sign = 1.0
|
| 32 |
+
|
| 33 |
+
P[0, 0] = 1 / tanHalfFovX
|
| 34 |
+
P[1, 1] = 1 / tanHalfFovY
|
| 35 |
+
P[3, 2] = z_sign
|
| 36 |
+
P[2, 2] = z_sign * zfar / (zfar - znear)
|
| 37 |
+
P[2, 3] = -(zfar * znear) / (zfar - znear)
|
| 38 |
+
return P
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class MiniCam:
|
| 42 |
+
def __init__(self, c2w, width, height, fovy, fovx, znear, zfar, device):
|
| 43 |
+
# c2w (pose) should be in NeRF convention.
|
| 44 |
+
|
| 45 |
+
self.image_width = width
|
| 46 |
+
self.image_height = height
|
| 47 |
+
self.FoVy = fovy
|
| 48 |
+
self.FoVx = fovx
|
| 49 |
+
self.znear = znear
|
| 50 |
+
self.zfar = zfar
|
| 51 |
+
|
| 52 |
+
w2c = torch.inverse(c2w)
|
| 53 |
+
|
| 54 |
+
# rectify...
|
| 55 |
+
# w2c[1:3, :3] *= -1
|
| 56 |
+
# w2c[:3, 3] *= -1
|
| 57 |
+
|
| 58 |
+
self.world_view_transform = w2c.transpose(0, 1).to(device)
|
| 59 |
+
self.projection_matrix = (
|
| 60 |
+
getProjectionMatrix(
|
| 61 |
+
znear=self.znear, zfar=self.zfar, fovX=self.FoVx, fovY=self.FoVy
|
| 62 |
+
)
|
| 63 |
+
.transpose(0, 1)
|
| 64 |
+
.to(device)
|
| 65 |
+
)
|
| 66 |
+
self.full_proj_transform = (self.world_view_transform @ self.projection_matrix).float()
|
| 67 |
+
self.camera_center = -c2w[:3, 3].to(device)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def rotation_matrix_to_quaternion(R):
|
| 71 |
+
tr = R[0, 0] + R[1, 1] + R[2, 2]
|
| 72 |
+
if tr > 0:
|
| 73 |
+
S = torch.sqrt(tr + 1.0) * 2.0
|
| 74 |
+
qw = 0.25 * S
|
| 75 |
+
qx = (R[2, 1] - R[1, 2]) / S
|
| 76 |
+
qy = (R[0, 2] - R[2, 0]) / S
|
| 77 |
+
qz = (R[1, 0] - R[0, 1]) / S
|
| 78 |
+
elif (R[0, 0] > R[1, 1]) and (R[0, 0] > R[2, 2]):
|
| 79 |
+
S = torch.sqrt(1.0 + R[0, 0] - R[1, 1] - R[2, 2]) * 2.0
|
| 80 |
+
qw = (R[2, 1] - R[1, 2]) / S
|
| 81 |
+
qx = 0.25 * S
|
| 82 |
+
qy = (R[0, 1] + R[1, 0]) / S
|
| 83 |
+
qz = (R[0, 2] + R[2, 0]) / S
|
| 84 |
+
elif R[1, 1] > R[2, 2]:
|
| 85 |
+
S = torch.sqrt(1.0 + R[1, 1] - R[0, 0] - R[2, 2]) * 2.0
|
| 86 |
+
qw = (R[0, 2] - R[2, 0]) / S
|
| 87 |
+
qx = (R[0, 1] + R[1, 0]) / S
|
| 88 |
+
qy = 0.25 * S
|
| 89 |
+
qz = (R[1, 2] + R[2, 1]) / S
|
| 90 |
+
else:
|
| 91 |
+
S = torch.sqrt(1.0 + R[2, 2] - R[0, 0] - R[1, 1]) * 2.0
|
| 92 |
+
qw = (R[1, 0] - R[0, 1]) / S
|
| 93 |
+
qx = (R[0, 2] + R[2, 0]) / S
|
| 94 |
+
qy = (R[1, 2] + R[2, 1]) / S
|
| 95 |
+
qz = 0.25 * S
|
| 96 |
+
return torch.stack([qw, qx, qy, qz], dim=1)
|
| 97 |
+
|
| 98 |
+
def rotate_quaternions(q, R):
|
| 99 |
+
# Convert quaternions to rotation matrices
|
| 100 |
+
q = torch.cat([q[:, :1], -q[:, 1:]], dim=1)
|
| 101 |
+
q = torch.cat([q[:, :3], q[:, 3:] * -1], dim=1)
|
| 102 |
+
rotated_R = torch.matmul(torch.matmul(q, R), q.inverse())
|
| 103 |
+
|
| 104 |
+
# Convert the rotated rotation matrices back to quaternions
|
| 105 |
+
return rotation_matrix_to_quaternion(rotated_R)
|
| 106 |
+
|
| 107 |
+
# this function is borrowed from OpenLRM
|
| 108 |
+
class CosineWarmupScheduler(LRScheduler):
|
| 109 |
+
def __init__(self, optimizer, warmup_iters: int, max_iters: int, initial_lr: float = 1e-10, last_iter: int = -1):
|
| 110 |
+
self.warmup_iters = warmup_iters
|
| 111 |
+
self.max_iters = max_iters
|
| 112 |
+
self.initial_lr = initial_lr
|
| 113 |
+
super().__init__(optimizer, last_iter)
|
| 114 |
+
|
| 115 |
+
def get_lr(self):
|
| 116 |
+
|
| 117 |
+
if self._step_count <= self.warmup_iters:
|
| 118 |
+
return [
|
| 119 |
+
self.initial_lr + (base_lr - self.initial_lr) * self._step_count / self.warmup_iters
|
| 120 |
+
for base_lr in self.base_lrs]
|
| 121 |
+
else:
|
| 122 |
+
cos_iter = self._step_count - self.warmup_iters
|
| 123 |
+
cos_max_iter = self.max_iters - self.warmup_iters
|
| 124 |
+
cos_theta = cos_iter / cos_max_iter * math.pi
|
| 125 |
+
cos_lr = [base_lr * (1 + math.cos(cos_theta)) / 2 for base_lr in self.base_lrs]
|
| 126 |
+
return cos_lr
|
| 127 |
+
|
| 128 |
+
def vis_images(output, batch):
|
| 129 |
+
pass
|
OVOW/engine/oneposeviagen/Amodal3R/setup.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# src/fpose/setup.py
|
| 2 |
+
from setuptools import setup, find_packages
|
| 3 |
+
|
| 4 |
+
setup(
|
| 5 |
+
name='amodal3r',
|
| 6 |
+
version='0.1',
|
| 7 |
+
package_dir={'amodal3r': 'amodal3r'},
|
| 8 |
+
packages=find_packages(where='amodal3r', include=['amodal3r*']),
|
| 9 |
+
)
|