Add files using upload-large-folder tool
Browse files- RGBD_DINOV3_HouseCat6D_final_copy.py +1198 -0
- RGBD_DINOV3_HouseCat6D_wlcop.py +1467 -0
- RGBD_DINO_HouseCat6D_final_copy.py +1083 -0
- RGBD_DINO_HouseCat6D_final_copy_amodal.py +1109 -0
- RGBD_DINO_HouseCat6D_final_copy_sam3d.py +1131 -0
- feature_alignment.py +187 -0
RGBD_DINOV3_HouseCat6D_final_copy.py
ADDED
|
@@ -0,0 +1,1198 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
from custom_utils import ShapeNetCore
|
| 18 |
+
from custom_utils import _compute_fov,_sample_points_from_faces
|
| 19 |
+
from custom_utils import image_grid
|
| 20 |
+
from custom_utils.shapenet_base import HouseCatDataset
|
| 21 |
+
import matplotlib.pyplot as plt
|
| 22 |
+
import numpy as np
|
| 23 |
+
import k3d
|
| 24 |
+
import os
|
| 25 |
+
import json
|
| 26 |
+
import torch
|
| 27 |
+
from PIL import Image
|
| 28 |
+
|
| 29 |
+
import cv2
|
| 30 |
+
import imageio
|
| 31 |
+
import numpy as np
|
| 32 |
+
from PIL import Image
|
| 33 |
+
import matplotlib.pyplot as plt
|
| 34 |
+
from torchvision import transforms
|
| 35 |
+
from custom_utils.extractor import ViTExtractor
|
| 36 |
+
import torch.nn.functional as F
|
| 37 |
+
from sklearn.decomposition import PCA as sklearnPCA
|
| 38 |
+
import math
|
| 39 |
+
from custom_utils.utils_general import center_crop
|
| 40 |
+
|
| 41 |
+
from pytorch3d.io import load_objs_as_meshes, load_obj
|
| 42 |
+
from pytorch3d.implicitron.tools.point_cloud_utils import get_rgbd_point_cloud
|
| 43 |
+
from pytorch3d.structures import Meshes
|
| 44 |
+
from pytorch3d.renderer import (
|
| 45 |
+
PerspectiveCameras,
|
| 46 |
+
FoVPerspectiveCameras,
|
| 47 |
+
PointLights,
|
| 48 |
+
MeshRasterizer,
|
| 49 |
+
MeshRenderer,
|
| 50 |
+
RasterizationSettings,
|
| 51 |
+
HardPhongShader,
|
| 52 |
+
TexturesVertex,
|
| 53 |
+
look_at_view_transform,
|
| 54 |
+
ray_bundle_to_ray_points,
|
| 55 |
+
NDCMultinomialRaysampler,
|
| 56 |
+
TexturesUV,
|
| 57 |
+
BlendParams,
|
| 58 |
+
|
| 59 |
+
TexturesVertex
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
from pytorch3d.implicitron.tools.point_cloud_utils import get_rgbd_point_cloud
|
| 63 |
+
from pytorch3d.structures import Pointclouds
|
| 64 |
+
import torch
|
| 65 |
+
from pytorch3d.ops import sample_farthest_points, knn_points, knn_gather
|
| 66 |
+
|
| 67 |
+
from matplotlib import cm
|
| 68 |
+
import numpy as np
|
| 69 |
+
import matplotlib.pyplot as plt
|
| 70 |
+
from sklearn.decomposition import PCA
|
| 71 |
+
from mpl_toolkits.mplot3d import Axes3D
|
| 72 |
+
import open3d as o3d
|
| 73 |
+
|
| 74 |
+
import torch
|
| 75 |
+
import torch.nn as nn
|
| 76 |
+
import torch.nn.functional as F
|
| 77 |
+
from transformers import AutoConfig, AutoModel
|
| 78 |
+
|
| 79 |
+
class Dinov3PatchExtractor(nn.Module):
|
| 80 |
+
"""
|
| 81 |
+
Returns patch tokens as [B, C, T] (C=384 for ViT-S/16).
|
| 82 |
+
Input must be ImageNet-normalized [B,3,H,W].
|
| 83 |
+
"""
|
| 84 |
+
def __init__(self, model_id="facebook/dinov3-vits16-pretrain-lvd1689m", freeze=True):
|
| 85 |
+
super().__init__()
|
| 86 |
+
self.cfg = AutoConfig.from_pretrained(model_id)
|
| 87 |
+
self.C = self.cfg.hidden_size # 384
|
| 88 |
+
self.nreg = getattr(self.cfg, "num_register_tokens", 0)
|
| 89 |
+
self.backbone = AutoModel.from_pretrained(model_id).eval()
|
| 90 |
+
self.p = 16 # ViT-S/16 的 patch 大小
|
| 91 |
+
if freeze:
|
| 92 |
+
for p in self.backbone.parameters():
|
| 93 |
+
p.requires_grad = False
|
| 94 |
+
|
| 95 |
+
@torch.no_grad()
|
| 96 |
+
def forward(self, x): # x: [B,3,H,W], normalized
|
| 97 |
+
B, _, H, W = x.shape
|
| 98 |
+
out = self.backbone(x)
|
| 99 |
+
seq = out.last_hidden_state # [B, T_all, C]
|
| 100 |
+
patch_seq = seq[:, 1 + self.nreg :, :] # drop CLS + registers -> [B, T_patch, C]
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
# 关键:用输入尺寸和 patch 大小推 H_p, W_p
|
| 104 |
+
H_p = H // self.p
|
| 105 |
+
W_p = W // self.p
|
| 106 |
+
T = patch_seq.shape[1]
|
| 107 |
+
|
| 108 |
+
# 若预处理不是整除,或模型内部有 pad/裁剪,做个健壮性兜底
|
| 109 |
+
if H_p * W_p != T:
|
| 110 |
+
# 按长宽比从 T 的因子中挑最合理的 (H_p, W_p)
|
| 111 |
+
aspect = H / W
|
| 112 |
+
best = None
|
| 113 |
+
for h in range(1, int(math.sqrt(T)) + 1):
|
| 114 |
+
if T % h == 0:
|
| 115 |
+
w = T // h
|
| 116 |
+
for (hh, ww) in [(h, w), (w, h)]:
|
| 117 |
+
score = abs((hh / ww) - aspect)
|
| 118 |
+
if best is None or score < best[2]:
|
| 119 |
+
best = (hh, ww, score)
|
| 120 |
+
if best is None:
|
| 121 |
+
raise RuntimeError(f"Cannot factor T={T} into (H_p,W_p).")
|
| 122 |
+
H_p, W_p, _ = best
|
| 123 |
+
|
| 124 |
+
feat = patch_seq.view(B, H_p, W_p, self.C).permute(0, 3, 1, 2) # [B,C,H_p,W_p]
|
| 125 |
+
return feat
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
class DINOv3ExtractorAdapter:
|
| 129 |
+
"""
|
| 130 |
+
Adapter to mimic ViTExtractor.extract_descriptors(batch, layer, facet, bin)
|
| 131 |
+
Returns descriptors with shape [B, 1, T, d] like ViTExtractor.
|
| 132 |
+
"""
|
| 133 |
+
def __init__(self, model_id="facebook/dinov3-vits16-pretrain-lvd1689m", device="cuda"):
|
| 134 |
+
self.device = device
|
| 135 |
+
self.model = Dinov3PatchExtractor(model_id, freeze=True).to(device)
|
| 136 |
+
self.p = 16 # patch size for vits16
|
| 137 |
+
self.stride = (16, 16) # nominal stride on tokens
|
| 138 |
+
self.mean = (0.485, 0.456, 0.406) # ImageNet normalization
|
| 139 |
+
self.std = (0.229, 0.224, 0.225)
|
| 140 |
+
|
| 141 |
+
@torch.no_grad()
|
| 142 |
+
def extract_descriptors(self, batch, layer=11, facet='token', bin=False, include_cls=False):
|
| 143 |
+
"""
|
| 144 |
+
batch: [B,3,H,W] normalized to ImageNet stats.
|
| 145 |
+
returns: [B, 1, T, d](T = H_p*W_p, d=384)
|
| 146 |
+
"""
|
| 147 |
+
# DINOv3 doesn't expose q/k/v hooks like timm; we just use its final patch tokens.
|
| 148 |
+
# 先拿到 [B,C,H_p,W_p]
|
| 149 |
+
feat_map = self.model(batch.to(self.device)) # [B,384,H_p,W_p]
|
| 150 |
+
B, C, H_p, W_p = feat_map.shape
|
| 151 |
+
# 再回到 [B,1,T,d] 以兼容你现有代码
|
| 152 |
+
desc = feat_map.flatten(2).permute(0, 2, 1).unsqueeze(1) # [B,1,H_p*W_p,384]
|
| 153 |
+
return desc
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def sample_points_on_sphere(num_points=80):
|
| 157 |
+
points = []
|
| 158 |
+
phi = (1 + math.sqrt(5)) / 2 # golden ratio
|
| 159 |
+
|
| 160 |
+
for i in range(num_points):
|
| 161 |
+
theta = 2 * math.pi * i / phi # azimuthal angle
|
| 162 |
+
z = 1 - (2 * i + 1) / num_points # z-coordinate, uniform from -1 to 1
|
| 163 |
+
radius = math.sqrt(1 - z * z) # radius for the xy-plane
|
| 164 |
+
x = radius * math.cos(theta)
|
| 165 |
+
y = radius * math.sin(theta)
|
| 166 |
+
points.append([x, y, z])
|
| 167 |
+
|
| 168 |
+
return torch.tensor(points, dtype=torch.float32)
|
| 169 |
+
|
| 170 |
+
def get_cube_vertices():
|
| 171 |
+
# Cube vertices (8 vertices)
|
| 172 |
+
return torch.tensor([[1, 1, 1],
|
| 173 |
+
[1, 1, -1],
|
| 174 |
+
[1, -1, 1],
|
| 175 |
+
[1, -1, -1],
|
| 176 |
+
[-1, 1, 1],
|
| 177 |
+
[-1, 1, -1],
|
| 178 |
+
[-1, -1, 1],
|
| 179 |
+
[-1, -1, -1]], dtype=torch.float32) # Ensure float type
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def render(meshes,scale=3.0,image_size=(420,420),light=(0.3,0.3,0.3)):
|
| 183 |
+
# prepare the camera
|
| 184 |
+
num_views = 8
|
| 185 |
+
# Get the cube vertices
|
| 186 |
+
#cube_vertices = get_cube_vertices()*scale
|
| 187 |
+
cube_vertices = sample_points_on_sphere(num_views)*scale
|
| 188 |
+
#up = torch.randn(1, 3)
|
| 189 |
+
up=torch.tensor([[0.0, 0.0, 1.0]], dtype=torch.float32)
|
| 190 |
+
up = up / torch.norm(up, dim=1)[:, None]
|
| 191 |
+
R, T = look_at_view_transform(eye=cube_vertices, at=torch.tensor([[0.0, 0.0, 0.0]], dtype=torch.float32), up=up)
|
| 192 |
+
cam_K= np.array([[572, 0.0, image_size[0]//2], [0.0, 572, image_size[1]//2], [0.0, 0.0, 1.0]])
|
| 193 |
+
fx,_,cx,_,fy,cy,_,_,_=cam_K.reshape(9)
|
| 194 |
+
fov_x, fov_y = _compute_fov(cam_K, 420, 420)
|
| 195 |
+
|
| 196 |
+
cameras = PerspectiveCameras(device=device, R=R, T=T, image_size=((420,420),),
|
| 197 |
+
focal_length=torch.tensor([[fx, fy]], dtype=torch.float32),
|
| 198 |
+
principal_point=torch.tensor([[cx, cy]], dtype=torch.float32),
|
| 199 |
+
in_ndc=False)
|
| 200 |
+
|
| 201 |
+
# prepare the lights
|
| 202 |
+
raster_settings = RasterizationSettings(image_size=image_size)
|
| 203 |
+
lights = PointLights(location=torch.tensor([0.0, 1.0, -2.0], device=device)[None], ambient_color=(light,),diffuse_color=(light,),device=device)
|
| 204 |
+
|
| 205 |
+
# move the data to the device
|
| 206 |
+
meshes = meshes.to(device)
|
| 207 |
+
cameras = cameras.to(device)
|
| 208 |
+
if len(cameras) != 1 and len(cameras) % len(meshes) != 0:
|
| 209 |
+
raise ValueError("Mismatch between batch dims of cameras and meshes.")
|
| 210 |
+
if len(cameras) > 1:
|
| 211 |
+
meshes = meshes.extend(len(cameras) // len(meshes))
|
| 212 |
+
|
| 213 |
+
# prepare the renderer
|
| 214 |
+
class MeshRendererWithDepth(torch.nn.Module):
|
| 215 |
+
def __init__(self, rasterizer, shader):
|
| 216 |
+
super().__init__()
|
| 217 |
+
self.rasterizer = rasterizer
|
| 218 |
+
self.shader = shader
|
| 219 |
+
|
| 220 |
+
def forward(self, meshes_world, **kwargs) -> torch.Tensor:
|
| 221 |
+
fragments = self.rasterizer(meshes_world, **kwargs)
|
| 222 |
+
images = self.shader(fragments, meshes_world, **kwargs)
|
| 223 |
+
return images, fragments.zbuf
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
blend_params = BlendParams(background_color=(0.0, 0.0, 0.0)) # Blue background
|
| 227 |
+
renderer = MeshRendererWithDepth(
|
| 228 |
+
rasterizer=MeshRasterizer(
|
| 229 |
+
cameras=cameras,
|
| 230 |
+
raster_settings=raster_settings,
|
| 231 |
+
),
|
| 232 |
+
# Set background color to blue [R, G, B]
|
| 233 |
+
|
| 234 |
+
shader=HardPhongShader(
|
| 235 |
+
device=device,
|
| 236 |
+
cameras=cameras,
|
| 237 |
+
lights=lights,
|
| 238 |
+
blend_params=blend_params
|
| 239 |
+
)
|
| 240 |
+
)
|
| 241 |
+
|
| 242 |
+
images,fragments = renderer(meshes)
|
| 243 |
+
return images,fragments,cameras
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
def render_batch(meshes,scale=3.0,image_size=(420,420),light=(0.3,0.3,0.3)):
|
| 247 |
+
# prepare the camera
|
| 248 |
+
num_views = 8
|
| 249 |
+
# Get the cube vertices
|
| 250 |
+
cube_vertices = get_cube_vertices()*scale
|
| 251 |
+
#cube_vertices = sample_points_on_sphere(num_views)*scale
|
| 252 |
+
up = torch.randn(1, 3)
|
| 253 |
+
# up=torch.tensor([[0.0, 0.0, 1.0]], dtype=torch.float32)
|
| 254 |
+
up = up / torch.norm(up, dim=1)[:, None]
|
| 255 |
+
R, T = look_at_view_transform(eye=cube_vertices, at=torch.tensor([[0.0, 0.0, 0.0]], dtype=torch.float32), up=up)
|
| 256 |
+
|
| 257 |
+
cam_K= np.array([[572, 0.0, image_size[0]//2], [0.0, 572, image_size[1]//2], [0.0, 0.0, 1.0]])
|
| 258 |
+
fx,_,cx,_,fy,cy,_,_,_=cam_K.reshape(9)
|
| 259 |
+
fov_x, fov_y = _compute_fov(cam_K, 420, 420)
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
# prepare the renderer
|
| 263 |
+
class MeshRendererWithDepth(torch.nn.Module):
|
| 264 |
+
def __init__(self, rasterizer, shader):
|
| 265 |
+
super().__init__()
|
| 266 |
+
self.rasterizer = rasterizer
|
| 267 |
+
self.shader = shader
|
| 268 |
+
|
| 269 |
+
def forward(self, meshes_world, **kwargs) -> torch.Tensor:
|
| 270 |
+
fragments = self.rasterizer(meshes_world, **kwargs)
|
| 271 |
+
images = self.shader(fragments, meshes_world, **kwargs)
|
| 272 |
+
return images, fragments.zbuf
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
blend_params = BlendParams(background_color=(0.0, 0.0, 0.0)) # Blue background
|
| 276 |
+
|
| 277 |
+
batch_size = 10
|
| 278 |
+
all_images=[]
|
| 279 |
+
all_fragments=[]
|
| 280 |
+
|
| 281 |
+
# move the data to the device
|
| 282 |
+
meshes = meshes.extend(batch_size).to(device)
|
| 283 |
+
for i in range(0,R.shape[0],batch_size):
|
| 284 |
+
R_batch = R[i:i+batch_size]
|
| 285 |
+
T_batch = T[i:i+batch_size]
|
| 286 |
+
cameras_batch = PerspectiveCameras(device=device, R=R_batch, T=T_batch, image_size=((420,420),),
|
| 287 |
+
focal_length=torch.tensor([[fx, fy]], dtype=torch.float32),
|
| 288 |
+
principal_point=torch.tensor([[cx, cy]], dtype=torch.float32),
|
| 289 |
+
in_ndc=False).to(device)
|
| 290 |
+
|
| 291 |
+
# prepare the lights
|
| 292 |
+
raster_settings = RasterizationSettings(image_size=image_size)
|
| 293 |
+
lights = PointLights(location=torch.tensor([0.0, 1.0, -2.0], device=device)[None],
|
| 294 |
+
ambient_color=(light,),diffuse_color=(light,),device=device)
|
| 295 |
+
|
| 296 |
+
renderer = MeshRendererWithDepth(
|
| 297 |
+
rasterizer=MeshRasterizer(
|
| 298 |
+
cameras=cameras_batch,
|
| 299 |
+
raster_settings=raster_settings,
|
| 300 |
+
),
|
| 301 |
+
# Set background color to blue [R, G, B]
|
| 302 |
+
shader=HardPhongShader(
|
| 303 |
+
device=device,
|
| 304 |
+
cameras=cameras_batch,
|
| 305 |
+
lights=lights,
|
| 306 |
+
blend_params=blend_params
|
| 307 |
+
)
|
| 308 |
+
)
|
| 309 |
+
images,fragments = renderer(meshes)
|
| 310 |
+
all_images.append(images)
|
| 311 |
+
all_fragments.append(fragments)
|
| 312 |
+
all_images = torch.cat(all_images,dim=0)
|
| 313 |
+
all_fragments = torch.cat(all_fragments,dim=0)
|
| 314 |
+
cameras = PerspectiveCameras(device=device, R=R, T=T, image_size=((420,420),),
|
| 315 |
+
focal_length=torch.tensor([[fx, fy]], dtype=torch.float32),
|
| 316 |
+
principal_point=torch.tensor([[cx, cy]], dtype=torch.float32),
|
| 317 |
+
in_ndc=False).to(device)
|
| 318 |
+
return all_images,all_fragments,cameras
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def fuse_feature_rgbd(extractor,images,fragments,cameras):
|
| 322 |
+
dino_feat_masked_list = []
|
| 323 |
+
feature_point_cloud_list = []
|
| 324 |
+
for i in range(images.shape[0]):
|
| 325 |
+
image = images.cpu().numpy()[i, :, :, :3]
|
| 326 |
+
image_mask = images[i, ..., 3].cpu().numpy()!=0
|
| 327 |
+
crop_size = (420, 420)
|
| 328 |
+
crop_image, crop_mask, bbox = center_crop(image, image_mask, crop_size)
|
| 329 |
+
cropped_image_np = cv2.resize(crop_image, crop_size, interpolation=cv2.INTER_AREA)
|
| 330 |
+
#cropped_mask = cv2.resize(crop_mask*1.0, crop_size, interpolation=cv2.INTER_NEAREST)!=0 # Use nearest neighbor interpolation for masks
|
| 331 |
+
orignal_size = (int(bbox[2]-bbox[0]), int(bbox[3]-bbox[1])) #K,K
|
| 332 |
+
|
| 333 |
+
to_tensor = transforms.ToTensor()
|
| 334 |
+
input_image = to_tensor(cropped_image_np).cuda(0)
|
| 335 |
+
input_image = input_image.unsqueeze(0)
|
| 336 |
+
#input_image=extractor.preprocess_pil(input_image)
|
| 337 |
+
mean = torch.tensor([0.485, 0.456, 0.406]).cuda(0)
|
| 338 |
+
std = torch.tensor([0.229, 0.224, 0.225]).cuda(0)
|
| 339 |
+
input_image = (input_image - mean[None, :, None, None]) / std[None, :, None, None]
|
| 340 |
+
|
| 341 |
+
_desc_q = extractor.extract_descriptors(input_image,layer=11, facet='key', include_cls=True).squeeze(1) # (1,900,384)
|
| 342 |
+
# _desc_q = extractor.forward_features(input_image)["x_prenorm"][:, :] # (1,900,384)
|
| 343 |
+
#_desc_q = extractor.extract_descriptors(input_image,layer=11,facet='token',include_cls=True).squeeze(1) # B,L,C
|
| 344 |
+
# _norm_q = torch.linalg.norm(_desc_q, dim=-1)[:, :, None]
|
| 345 |
+
# _desc_q = _desc_q / (_norm_q)
|
| 346 |
+
|
| 347 |
+
desc = _desc_q[:,1:,:][None]
|
| 348 |
+
#cls_token_q = _desc_q[:,0,:] #B,C`
|
| 349 |
+
|
| 350 |
+
input_mask = to_tensor(crop_mask).cuda(0)
|
| 351 |
+
input_mask = input_mask.unsqueeze(0)
|
| 352 |
+
|
| 353 |
+
img_mask = to_tensor(image_mask)
|
| 354 |
+
|
| 355 |
+
img_mask = img_mask.permute(1,2,0)
|
| 356 |
+
|
| 357 |
+
dino_feat = patch2pixel_feats(desc, original_size=orignal_size) #reize back to K,K =>( K, K, 384)
|
| 358 |
+
# create dino-feat with orignal size
|
| 359 |
+
dino_height, dino_width, feat_dim = (image_size[0],image_size[1], desc.shape[-1])
|
| 360 |
+
dino_feat_orig = torch.zeros(dino_height,dino_width,feat_dim)
|
| 361 |
+
# Fill the dino features into the original tensor at the specified bounding box
|
| 362 |
+
dino_feat_orig[bbox[1]:bbox[3], bbox[0]:bbox[2],:] = dino_feat #reize back to K,K =>(420, 420, 384) #gradint is not supported for this operation
|
| 363 |
+
# Apply the mask
|
| 364 |
+
dino_feat_masked = dino_feat_orig * img_mask
|
| 365 |
+
dino_feat_masked = dino_feat_masked.permute(2,0,1).unsqueeze(0)
|
| 366 |
+
dino_feat_masked_low = F.interpolate(dino_feat_masked, size=(30, 30), mode='bilinear')
|
| 367 |
+
|
| 368 |
+
image_mask = images[i, ..., 3][None,None]
|
| 369 |
+
depth_image = fragments[i, ..., 0][None]*image_mask
|
| 370 |
+
|
| 371 |
+
# # Define the kernel for erosion (3x3 ones kernel)
|
| 372 |
+
# kernel = torch.ones((1, 1, 5, 5), dtype=torch.float).cuda()
|
| 373 |
+
# # Number of erosion iterations
|
| 374 |
+
# iterations = 5
|
| 375 |
+
|
| 376 |
+
# # Perform iterative erosion
|
| 377 |
+
# for i in range(iterations):
|
| 378 |
+
# # Apply erosion using 2D convolution
|
| 379 |
+
# eroded_mask = F.conv2d(image_mask, kernel, padding=2)
|
| 380 |
+
# image_mask = (eroded_mask == kernel.sum()).float() # Update mask to eroded version
|
| 381 |
+
|
| 382 |
+
feature_point_cloud = get_rgbd_point_cloud(cameras[i], dino_feat_masked.to(device), depth_map=depth_image,mask=image_mask)#everthing on GPU
|
| 383 |
+
|
| 384 |
+
index = np.random.choice(feature_point_cloud.points_list()[0].shape[0], 4096, replace=True)
|
| 385 |
+
points = feature_point_cloud.points_list()[0].detach().cpu()[index,:]
|
| 386 |
+
colors = feature_point_cloud.features_list()[0].detach().cpu()[index,:]
|
| 387 |
+
# points = feature_point_cloud.points_list()[0].detach().cpu()[:,:]
|
| 388 |
+
# colors = feature_point_cloud.features_list()[0].detach().cpu()[:,:]
|
| 389 |
+
feature_point_cloud = torch.cat((points, colors), dim=1)
|
| 390 |
+
|
| 391 |
+
dino_feat_masked_list.append(dino_feat_masked_low.detach().cpu())
|
| 392 |
+
feature_point_cloud_list.append(feature_point_cloud)
|
| 393 |
+
feature_point_cloud = torch.cat(feature_point_cloud_list, dim=0)
|
| 394 |
+
dino_feat_masked = torch.cat(dino_feat_masked_list, dim=0)
|
| 395 |
+
return feature_point_cloud,dino_feat_masked, feature_point_cloud_list
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
def downsample_with_knn_feature_aggregation(feature_point_cloud,num_pts=1024,k_nearest_neighbors=100, instance_points=None):
|
| 399 |
+
#N_1, C_1 = 2048, 384 # Example number of points and features
|
| 400 |
+
num_points_to_sample = num_pts
|
| 401 |
+
k_nearest_neighbors = k_nearest_neighbors
|
| 402 |
+
|
| 403 |
+
# Example input pointcloud and features (N_1, C_1), where N_1 is the number of points and C_1 is the feature dimension
|
| 404 |
+
pointcloud = feature_point_cloud[None,:,:3].cuda() # Shape (1, N_1, 3) for 3D coordinates
|
| 405 |
+
features = feature_point_cloud[None,:,3:].cuda() # Shape (1, N_1, C_1) for features
|
| 406 |
+
|
| 407 |
+
# Step 1: FPS to downsample the points
|
| 408 |
+
# We use sample_farthest_points to select num_points_to_sample points
|
| 409 |
+
sampled_points, sampled_indices = sample_farthest_points(pointcloud, K=num_points_to_sample) # Shape: (1, 1024, 3), (1, 1024)
|
| 410 |
+
if instance_points is not None:
|
| 411 |
+
sampled_points = instance_points
|
| 412 |
+
|
| 413 |
+
# Step 2: KNN to find nearest neighbors
|
| 414 |
+
# Find the k nearest neighbors for each sampled point in the original pointcloud
|
| 415 |
+
dists, knn_indices, _ = knn_points(sampled_points, pointcloud, K=k_nearest_neighbors, return_nn=False)
|
| 416 |
+
|
| 417 |
+
# Step 3: Gather the features of the k-nearest neighbors using the knn indices
|
| 418 |
+
# Use knn_gather to get neighbor features for each sampled point
|
| 419 |
+
neighbor_features = knn_gather(features, knn_indices) # Shape: (1, 1024, k, C_1)
|
| 420 |
+
|
| 421 |
+
# Step 4: Aggregate features from the neighbors (e.g., by averaging)
|
| 422 |
+
#aggregated_features,_ = torch.max(neighbor_features,dim=-2) # Shape: (1, 1024, C_1)
|
| 423 |
+
aggregated_features = torch.mean(neighbor_features,dim=-2) # Shape: (1, 1024, C_1)
|
| 424 |
+
return sampled_points, aggregated_features
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
def vis_pca(feature):
|
| 428 |
+
n_components=3 # the first component is to seperate the object from the background
|
| 429 |
+
|
| 430 |
+
pca = sklearnPCA(n_components=n_components)
|
| 431 |
+
feature = pca.fit_transform(feature.detach().cpu().numpy())
|
| 432 |
+
for show_channel in range(n_components):
|
| 433 |
+
# min max normalize the feature map
|
| 434 |
+
feature[:, show_channel] = (feature[:, show_channel] - feature[:, show_channel].mean()) / (feature[:, show_channel].std()*10)
|
| 435 |
+
feature_resized = np.clip(feature[:,:]+0.5,0,1)
|
| 436 |
+
return feature_resized
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
def patch2pixel_feats(patch_features, original_size):
|
| 440 |
+
"""
|
| 441 |
+
修改版:自动根据 T(patch 数量)和原图比例推算 (Hp, Wp)
|
| 442 |
+
"""
|
| 443 |
+
H, W = original_size
|
| 444 |
+
B = patch_features.shape[0]
|
| 445 |
+
T = patch_features.shape[2]
|
| 446 |
+
C = patch_features.shape[3]
|
| 447 |
+
|
| 448 |
+
# ✅ 【修改1】自动寻找 (Hp, Wp),而不是用 sqrt(T)
|
| 449 |
+
aspect = H / W
|
| 450 |
+
best = None
|
| 451 |
+
for h in range(1, int(math.sqrt(T)) + 1):
|
| 452 |
+
if T % h == 0:
|
| 453 |
+
w = T // h
|
| 454 |
+
for hh, ww in [(h, w), (w, h)]:
|
| 455 |
+
score = abs((hh / ww) - aspect)
|
| 456 |
+
if best is None or score < best[2]:
|
| 457 |
+
best = (hh, ww, score)
|
| 458 |
+
Hp, Wp, _ = best # 比如 27, 25
|
| 459 |
+
|
| 460 |
+
# ✅ 【修改2】用 Hp, Wp 替代 num_patches
|
| 461 |
+
patch_features = patch_features.reshape(B, Hp, Wp, C)
|
| 462 |
+
|
| 463 |
+
# ✅ 【修改3】后面不变
|
| 464 |
+
patch_features = patch_features.permute(0, 3, 1, 2)
|
| 465 |
+
pixel_features = F.interpolate(
|
| 466 |
+
patch_features, size=(H, W), mode='bilinear', align_corners=False
|
| 467 |
+
)
|
| 468 |
+
pixel_features = pixel_features.squeeze().permute(1, 2, 0)
|
| 469 |
+
|
| 470 |
+
return pixel_features
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
def vis_pca_pixelwise(feature):
|
| 474 |
+
n_components = 4 # The number of PCA components to use
|
| 475 |
+
batch, feat_dim, height,width = feature.shape
|
| 476 |
+
|
| 477 |
+
# Reshape the feature to (num_pixels, feat_dim)
|
| 478 |
+
num_pixels = height * width
|
| 479 |
+
feature_reshaped = np.array(feature).transpose(0,2,3,1).reshape(-1, feat_dim)
|
| 480 |
+
|
| 481 |
+
|
| 482 |
+
# Apply PCA
|
| 483 |
+
pca = sklearnPCA(n_components=n_components)
|
| 484 |
+
feature_pca = pca.fit_transform(feature_reshaped)
|
| 485 |
+
|
| 486 |
+
# Min-max normalization for each component
|
| 487 |
+
# for show_channel in range(n_components):
|
| 488 |
+
# feature_pca[:, show_channel] = (feature_pca[:, show_channel] - feature_pca[:, show_channel].min()) / \
|
| 489 |
+
# (feature_pca[:, show_channel].max() - feature_pca[:, show_channel].min() + 1e-8) # Small epsilon to avoid division by zero
|
| 490 |
+
for show_channel in range(n_components):
|
| 491 |
+
feature_pca[:, show_channel] = (feature_pca[:, show_channel] - feature_pca[:, show_channel].mean()) / \
|
| 492 |
+
(feature_pca[:, show_channel].std()*10 + 1e-8) # Small epsilon to avoid division by zero
|
| 493 |
+
|
| 494 |
+
feature_pca = np.clip(feature_pca+0.5, 0, 1)
|
| 495 |
+
# Reshape the PCA result back to (height, width, n_components)
|
| 496 |
+
feature_resized = feature_pca.reshape(batch,height,width,n_components)[...,1:4]
|
| 497 |
+
return feature_resized
|
| 498 |
+
|
| 499 |
+
def normalize_mesh_verts(data):
|
| 500 |
+
# data [N, 3]
|
| 501 |
+
min_vals, _ = torch.min(data, dim=0)
|
| 502 |
+
max_vals, _ = torch.max(data, dim=0)
|
| 503 |
+
bbox_sizes = max_vals - min_vals
|
| 504 |
+
scale = torch.norm(bbox_sizes)
|
| 505 |
+
print("Scale:", scale)
|
| 506 |
+
normalized_verts = verts / scale
|
| 507 |
+
return normalized_verts
|
| 508 |
+
|
| 509 |
+
def plot_pointclouds_with_color_mapping(pc1_f, pc2_f,pc1,pc2, query_points, similarity_threshold=None):
|
| 510 |
+
"""
|
| 511 |
+
Visualizes two 3D point clouds. The second point cloud (pc2) is color-mapped
|
| 512 |
+
using the 'viridis' colormap based on its similarity (proximity) to the sampled
|
| 513 |
+
query points in the first point cloud (pc1).
|
| 514 |
+
|
| 515 |
+
Parameters:
|
| 516 |
+
- pc1: np.ndarray of shape (N, 3), first point cloud #partial
|
| 517 |
+
- pc2: np.ndarray of shape (M, 3), second point cloud # global
|
| 518 |
+
- query_points: list of indices in pc1, representing the query points to compare.
|
| 519 |
+
- similarity_threshold: float, optional, threshold to cap the similarity distance.
|
| 520 |
+
"""
|
| 521 |
+
|
| 522 |
+
|
| 523 |
+
pc1_f = pc1_f / np.linalg.norm(pc1_f, axis=1)[:, None] # Normalize the features
|
| 524 |
+
pc2_f = pc2_f / np.linalg.norm(pc2_f, axis=1)[:, None] # Normalize the features
|
| 525 |
+
# Create a figure with subplots
|
| 526 |
+
fig = plt.figure(figsize=(12, 10))
|
| 527 |
+
num_query_points = len(query_points)
|
| 528 |
+
# Set limits and labels
|
| 529 |
+
size = pc2.max() - pc2.min()
|
| 530 |
+
# Plot the first point cloud in the first subplot
|
| 531 |
+
ax1 = fig.add_subplot(1, num_query_points + 1, 1, projection='3d')
|
| 532 |
+
ax1.scatter(pc2[:, 0], pc2[:, 1], pc2[:, 2], color='grey', label='Point Cloud 1 (Left)', alpha=0.1,s=10)
|
| 533 |
+
|
| 534 |
+
# Define a color list for each query point
|
| 535 |
+
query_colors = cm.tab10(np.linspace(0, 1, num_query_points)) # Use tab10 colormap for distinct colors
|
| 536 |
+
|
| 537 |
+
# Highlight query points in pc1 with different colors
|
| 538 |
+
for i, idx in enumerate(query_points):
|
| 539 |
+
ax1.scatter(pc1[idx, 0], pc1[idx, 1], pc1[idx, 2],
|
| 540 |
+
color=query_colors[i], s=100, edgecolor='k', label=f'Query Point {idx}')
|
| 541 |
+
|
| 542 |
+
ax1.set_title('Point Cloud 1 with Query Points')
|
| 543 |
+
ax1.set_xlabel('X')
|
| 544 |
+
ax1.set_ylabel('Y')
|
| 545 |
+
ax1.set_zlabel('Z')
|
| 546 |
+
ax1.set_xlim(-size / 1.4, size / 1.4)
|
| 547 |
+
ax1.set_ylim(-size / 1.4, size / 1.4)
|
| 548 |
+
ax1.set_zlim(-size / 1.4, size / 1.4)
|
| 549 |
+
ax1.view_init(elev=45, azim=-45)
|
| 550 |
+
ax1.grid(True)
|
| 551 |
+
ax1.legend()
|
| 552 |
+
|
| 553 |
+
# Plot the second point cloud in the subsequent subplots
|
| 554 |
+
for k in range(num_query_points):
|
| 555 |
+
|
| 556 |
+
ax = fig.add_subplot(1, num_query_points + 1, k + 2, projection='3d')
|
| 557 |
+
|
| 558 |
+
# Calculate distances between query points in pc1 and all points in pc2
|
| 559 |
+
similarity =(pc1_f[query_points[k]][None]@ pc2_f.T).reshape(-1) # (1, 3) x (M, 3) = (1, M)
|
| 560 |
+
# For each point in pc2, take the minimum distance to any query point
|
| 561 |
+
min_similarity = np.min(similarity, axis=0)
|
| 562 |
+
# Optionally cap the similarity distances to a threshold (to avoid extreme values)
|
| 563 |
+
similarity_threshold= 0.3
|
| 564 |
+
if similarity_threshold is not None:
|
| 565 |
+
similarity = np.clip(similarity, similarity_threshold,1)
|
| 566 |
+
# Normalize the distances to a range of 0 to 1 for colormap mapping
|
| 567 |
+
similarity = (similarity - np.min(similarity)) / (np.max(similarity) - np.min(similarity))
|
| 568 |
+
colors = cm.plasma(similarity)
|
| 569 |
+
|
| 570 |
+
# Plot the second point cloud with color mapping based on similarity
|
| 571 |
+
ax.scatter(pc2[:, 0], pc2[:, 1], pc2[:, 2], color=colors, s=15, alpha=1.0, label='Point Cloud 2 (Right)', edgecolor='k')
|
| 572 |
+
|
| 573 |
+
ax.set_xlim(-size / 1.4, size / 1.4)
|
| 574 |
+
ax.set_ylim(-size / 1.4, size / 1.4)
|
| 575 |
+
ax.set_zlim(-size / 1.4, size / 1.4)
|
| 576 |
+
ax.set_title(f'QP_{query_points[k]}')
|
| 577 |
+
ax.set_xlabel('X')
|
| 578 |
+
ax.set_ylabel('Y')
|
| 579 |
+
ax.set_zlabel('Z')
|
| 580 |
+
ax.view_init(elev=45, azim=-45)
|
| 581 |
+
ax.grid(True)
|
| 582 |
+
ax.legend()
|
| 583 |
+
|
| 584 |
+
# Show the plot
|
| 585 |
+
plt.tight_layout()
|
| 586 |
+
plt.show()
|
| 587 |
+
|
| 588 |
+
|
| 589 |
+
def plot_pointclouds_3d_with_copca_old(global_sem_pcd, partial_sem_pcd, global_pcd, partial_pcd):
|
| 590 |
+
"""
|
| 591 |
+
Visualizes two point clouds in 3D, coloring them based on their PCA components.
|
| 592 |
+
|
| 593 |
+
Parameters:
|
| 594 |
+
- global_pointcloud: numpy array of shape (N, D) for global point cloud.
|
| 595 |
+
- partial_pointcloud: numpy array of shape (M, D) for partial point cloud.
|
| 596 |
+
"""
|
| 597 |
+
|
| 598 |
+
|
| 599 |
+
n_components = 3
|
| 600 |
+
# Step 1: Perform PCA on both global and partial point clouds
|
| 601 |
+
sem_pca = PCA(n_components=n_components)
|
| 602 |
+
sem_pca = sem_pca.fit(global_sem_pcd) # shape (N+M, 3)
|
| 603 |
+
|
| 604 |
+
transformed_sem_pcd_list = [sem_pca.transform(pcd) for pcd in [global_sem_pcd,partial_sem_pcd]]
|
| 605 |
+
sem_pcd_pca = np.concatenate(transformed_sem_pcd_list,axis=0)
|
| 606 |
+
for show_channel in range(n_components):
|
| 607 |
+
sem_pcd_pca[:, show_channel] = (sem_pcd_pca[:, show_channel] - sem_pcd_pca[:, show_channel].mean()) / \
|
| 608 |
+
(sem_pcd_pca[:, show_channel].std()*5 + 1e-8) # Small epsilon to avoid division by zero
|
| 609 |
+
|
| 610 |
+
# sem_pcd_pca_min = sem_pcd_pca.min()
|
| 611 |
+
# sem_pcd_pca_max = sem_pcd_pca.max()
|
| 612 |
+
# sem_pcd_pca = (sem_pcd_pca- sem_pcd_pca_min) / (sem_pcd_pca_max - sem_pcd_pca_min) # Normalize to [0, 1]
|
| 613 |
+
|
| 614 |
+
sem_pcd_pca = np.clip(sem_pcd_pca[:,:]+0.5, 0, 1)
|
| 615 |
+
global_pca = sem_pcd_pca[:global_sem_pcd.shape[0]] # shape (N, 3)
|
| 616 |
+
partial_pca = sem_pcd_pca[-partial_sem_pcd.shape[0]:] # shape (M, 3)
|
| 617 |
+
|
| 618 |
+
# Step 2: Create a 3D scatter plot
|
| 619 |
+
fig = plt.figure(figsize=(12, 6))
|
| 620 |
+
ax = fig.add_subplot(121, projection='3d')
|
| 621 |
+
|
| 622 |
+
|
| 623 |
+
# Global point cloud
|
| 624 |
+
ax.scatter(global_pcd[:, 0], global_pcd[:, 1], global_pcd[:, 2],
|
| 625 |
+
c=global_pca, marker='o', s=100, alpha=1.0, label='Global Point Cloud')
|
| 626 |
+
|
| 627 |
+
# Set labels for each axis
|
| 628 |
+
# ax.set_xlabel('X axis')
|
| 629 |
+
# ax.set_ylabel('Y axis')
|
| 630 |
+
# ax.set_zlabel('Z axis')
|
| 631 |
+
ax.set_xlim(-0.5, 0.5)
|
| 632 |
+
ax.set_ylim(-0.5, 0.5)
|
| 633 |
+
ax.set_zlim(-0.5, 0.5)
|
| 634 |
+
|
| 635 |
+
ax1 = fig.add_subplot(122, projection='3d')
|
| 636 |
+
|
| 637 |
+
# Partial point cloud
|
| 638 |
+
ax1.scatter(partial_pcd[:, 0], partial_pcd[:, 1], partial_pcd[:, 2],
|
| 639 |
+
c=partial_pca, marker='o', s=100, alpha=1.0, label='Partial Point Cloud')
|
| 640 |
+
|
| 641 |
+
# ax1.scatter(global_pcd[:, 0], global_pcd[:, 1], global_pcd[:, 2],
|
| 642 |
+
# marker='o', s=10, alpha=0.1)
|
| 643 |
+
# Set labels for each axis
|
| 644 |
+
# ax1.set_xlabel('X axis')
|
| 645 |
+
# ax1.set_ylabel('Y axis')
|
| 646 |
+
# ax1.set_zlabel('Z axis')
|
| 647 |
+
|
| 648 |
+
|
| 649 |
+
ax1.set_xlim(-0.5, 0.5)
|
| 650 |
+
ax1.set_ylim(-0.5, 0.5)
|
| 651 |
+
ax1.set_zlim(-0.5, 0.5)
|
| 652 |
+
plt.tight_layout()
|
| 653 |
+
|
| 654 |
+
ax.view_init(120,-95)
|
| 655 |
+
ax1.view_init(120,-95)
|
| 656 |
+
|
| 657 |
+
|
| 658 |
+
ax.set_axis_off()
|
| 659 |
+
ax.set_facecolor((0, 0, 0, 0))
|
| 660 |
+
ax1.set_axis_off()
|
| 661 |
+
ax1.set_facecolor((0, 0, 0, 0))
|
| 662 |
+
|
| 663 |
+
plt.show()
|
| 664 |
+
|
| 665 |
+
|
| 666 |
+
def plot_pointclouds_3d_with_pca(global_sem_pcd, global_pcd):
|
| 667 |
+
"""
|
| 668 |
+
Visualizes two point clouds in 3D, coloring them based on their PCA components.
|
| 669 |
+
|
| 670 |
+
Parameters:
|
| 671 |
+
- global_pointcloud: numpy array of shape (N, D) for global point cloud.
|
| 672 |
+
- partial_pointcloud: numpy array of shape (M, D) for partial point cloud.
|
| 673 |
+
"""
|
| 674 |
+
#sem_pcd = np.concatenate((global_sem_pcd,partial_sem_pcd), axis=0) # shape (N+M, D)
|
| 675 |
+
|
| 676 |
+
# Step 1: Perform PCA on both global and partial point clouds
|
| 677 |
+
sem_pca = PCA(n_components=3)
|
| 678 |
+
sem_pcd_pca = sem_pca.fit_transform(global_sem_pcd) # shape (N+M, 3)
|
| 679 |
+
|
| 680 |
+
for i in range(3): # Iterate over each component (3 in total for RGB)
|
| 681 |
+
sem_pcd_pca_mean = sem_pcd_pca[:, i].mean()
|
| 682 |
+
sem_pcd_pca_std = sem_pcd_pca[:, i].std()
|
| 683 |
+
sem_pcd_pca[:, i] = (sem_pcd_pca[:, i] - sem_pcd_pca_mean) / (sem_pcd_pca_std*5+1e-8) # Normalize to [0, 1]
|
| 684 |
+
|
| 685 |
+
|
| 686 |
+
global_pca = np.clip(sem_pcd_pca+0.5,0,1)
|
| 687 |
+
# scatter plot
|
| 688 |
+
fig = plt.figure(figsize=(6, 6))
|
| 689 |
+
ax = fig.add_subplot(111, projection='3d')
|
| 690 |
+
|
| 691 |
+
# Global point cloud
|
| 692 |
+
ax.scatter(global_pcd[:, 0], global_pcd[:, 1], global_pcd[:, 2],
|
| 693 |
+
c=global_pca, marker='o', s=50, alpha=1.0, label='Global Point Cloud')
|
| 694 |
+
|
| 695 |
+
# Remove axes and background
|
| 696 |
+
ax.set_axis_off()
|
| 697 |
+
|
| 698 |
+
# Set background color to none
|
| 699 |
+
ax.set_facecolor((0, 0, 0, 0))
|
| 700 |
+
# # Set labels for each axis
|
| 701 |
+
# ax.set_xlabel('X axis')
|
| 702 |
+
# ax.set_ylabel('Y axis')
|
| 703 |
+
# ax.set_zlabel('Z axis')
|
| 704 |
+
ax.set_xlim(-0.5, 0.5)
|
| 705 |
+
ax.set_ylim(-0.5, 0.5)
|
| 706 |
+
ax.set_zlim(-0.5, 0.5)
|
| 707 |
+
|
| 708 |
+
ax.view_init(-73,102)
|
| 709 |
+
|
| 710 |
+
return fig
|
| 711 |
+
|
| 712 |
+
|
| 713 |
+
def plot_pointclouds_3d_with_copca(global_sem_pcd_list, global_pcd_list,co_pca=True):
|
| 714 |
+
"""
|
| 715 |
+
Visualizes multiple point clouds in 3D, each in a separate subplot, after applying CoPCA.
|
| 716 |
+
Coloring them based on their PCA components.
|
| 717 |
+
|
| 718 |
+
Parameters:
|
| 719 |
+
- global_sem_pcd_list: list of numpy arrays for semantic point clouds (one per object).
|
| 720 |
+
- global_pcd_list: list of numpy arrays for global point clouds (one per object).
|
| 721 |
+
"""
|
| 722 |
+
num_pcds = len(global_sem_pcd_list) # Number of point clouds
|
| 723 |
+
print("Number of point clouds to visualize:", num_pcds)
|
| 724 |
+
# Step 1: Perform CoPCA (Common PCA) on the semantic point clouds
|
| 725 |
+
# Concatenate all point clouds to perform common PCA
|
| 726 |
+
if co_pca:
|
| 727 |
+
|
| 728 |
+
concatenated_pcds = np.concatenate(global_sem_pcd_list, axis=0) # shape (N_total, D)
|
| 729 |
+
copca = PCA(n_components=3, random_state=0)
|
| 730 |
+
copca.fit(concatenated_pcds[:1024]) # Fit PCA on all point clouds together
|
| 731 |
+
transformed_sem_pcd_list = [copca.transform(pcd) for pcd in global_sem_pcd_list]
|
| 732 |
+
|
| 733 |
+
|
| 734 |
+
signs = np.sign(np.sum(transformed_sem_pcd_list[0], axis=0))
|
| 735 |
+
# Post-process to ensure consistent orientation of PCA components
|
| 736 |
+
for i, transformed_pcd in enumerate(transformed_sem_pcd_list):
|
| 737 |
+
# For each component (column), align sign based on the sum of values in the column
|
| 738 |
+
transformed_sem_pcd_list[i] = transformed_pcd * signs
|
| 739 |
+
else:
|
| 740 |
+
copca = PCA(n_components=3)
|
| 741 |
+
transformed_sem_pcd_list = [copca.fit_transform(pcd) for pcd in global_sem_pcd_list]
|
| 742 |
+
# Post-process to ensure consistent orientation of PCA components
|
| 743 |
+
for i, transformed_pcd in enumerate(transformed_sem_pcd_list):
|
| 744 |
+
signs = np.sign(np.sum(transformed_pcd, axis=0))
|
| 745 |
+
# For each component (column), align sign based on the sum of values in the column
|
| 746 |
+
transformed_sem_pcd_list[i] = transformed_pcd * signs
|
| 747 |
+
|
| 748 |
+
|
| 749 |
+
|
| 750 |
+
# Create a figure with subplots arranged in a grid (based on number of point clouds)
|
| 751 |
+
fig = plt.figure(figsize=(6 * num_pcds, 6)) # Adjust figure size based on the number of subplots
|
| 752 |
+
|
| 753 |
+
# Loop over the point clouds
|
| 754 |
+
for idx, (sem_pcd_pca, global_pcd) in enumerate(zip(transformed_sem_pcd_list, global_pcd_list)):
|
| 755 |
+
ax = fig.add_subplot(1, num_pcds, idx + 1, projection='3d')
|
| 756 |
+
|
| 757 |
+
# Step 2: Normalize the PCA-transformed data to use as colors
|
| 758 |
+
for i in range(3): # Iterate over each component (3 in total for RGB)
|
| 759 |
+
pca_mean = sem_pcd_pca[:, i].mean()
|
| 760 |
+
pca_std = sem_pcd_pca[:, i].std()
|
| 761 |
+
sem_pcd_pca[:, i] = (sem_pcd_pca[:, i] - pca_mean) / (pca_std * 5 + 1e-8) # Normalize
|
| 762 |
+
|
| 763 |
+
global_pca_colors = np.clip(sem_pcd_pca + 0.5, 0, 1) # Map to [0, 1] for RGB
|
| 764 |
+
|
| 765 |
+
# Scatter plot for this point cloud in the current subplot
|
| 766 |
+
ax.scatter(global_pcd[:, 0], global_pcd[:, 1], global_pcd[:, 2],
|
| 767 |
+
c=global_pca_colors, marker='o', s=50, alpha=1.0)
|
| 768 |
+
|
| 769 |
+
# Remove axes and background
|
| 770 |
+
ax.set_axis_off()
|
| 771 |
+
ax.set_facecolor((0, 0, 0, 0))
|
| 772 |
+
|
| 773 |
+
# Set axis limits for each subplot
|
| 774 |
+
ax.set_xlim(-0.5, 0.5)
|
| 775 |
+
ax.set_ylim(-0.5, 0.5)
|
| 776 |
+
ax.set_zlim(-0.5, 0.5)
|
| 777 |
+
|
| 778 |
+
# Set view angle
|
| 779 |
+
ax.view_init(-55, 102)
|
| 780 |
+
|
| 781 |
+
# Adjust spacing between subplots
|
| 782 |
+
plt.tight_layout()
|
| 783 |
+
|
| 784 |
+
return fig
|
| 785 |
+
|
| 786 |
+
|
| 787 |
+
|
| 788 |
+
def unnormalize(x):
|
| 789 |
+
# x.shape : [H,W,3]
|
| 790 |
+
mean = np.array([0.485, 0.456, 0.406])
|
| 791 |
+
std = np.array([0.229, 0.224, 0.225])
|
| 792 |
+
return x * std + mean
|
| 793 |
+
|
| 794 |
+
|
| 795 |
+
from custom_utils.housecat6d_dataset import HouseCat6DTrainingDataset
|
| 796 |
+
trainset = HouseCat6DTrainingDataset(image_size=420, sample_num=1024,data_dir='/media/xyz/data1/HouseCat6D')
|
| 797 |
+
|
| 798 |
+
vis = True
|
| 799 |
+
device = "cuda"
|
| 800 |
+
import matplotlib
|
| 801 |
+
matplotlib.use('TkAgg')
|
| 802 |
+
|
| 803 |
+
#cat_list = ['bottle','box','can','cup','cutlery','remote','shoe','tube','teapot']
|
| 804 |
+
cat_list = ['cup']
|
| 805 |
+
|
| 806 |
+
|
| 807 |
+
sem_global_list = []
|
| 808 |
+
sem_global_pcd_list = []
|
| 809 |
+
|
| 810 |
+
# load semantc feature and show
|
| 811 |
+
########################################
|
| 812 |
+
save_dir = 'Yung/yung_large_files/semantic_feature/test_notebook/8v'
|
| 813 |
+
#save_dir = './80views_textured_token'
|
| 814 |
+
if True:
|
| 815 |
+
for cat in cat_list:
|
| 816 |
+
# # orriginal
|
| 817 |
+
# with open(f'/mnt/4T/Yung/yung_large_files/semantic_feature/test_notebook/housecat_{cat}/raw/housecat1_train.txt', 'r') as f:
|
| 818 |
+
# instances = [line.strip() for line in f.readlines()]
|
| 819 |
+
|
| 820 |
+
# print(instances)
|
| 821 |
+
# revised
|
| 822 |
+
# instance try cup-grey_handle
|
| 823 |
+
instances = ['cup-grey_handle']
|
| 824 |
+
sem_global_list = []
|
| 825 |
+
sem_global_pcd_list = []
|
| 826 |
+
|
| 827 |
+
# Load the mean shape point cloud
|
| 828 |
+
meanshape_path = f'Yung/yung_large_files/semantic_feature/test_notebook/saved_pcd/{cat}/mean_shape/mean_shape_pcd_1.txt'
|
| 829 |
+
meanshape_pcd_np = np.loadtxt(meanshape_path)
|
| 830 |
+
meanshape_pcd_tensor = torch.from_numpy(meanshape_pcd_np)
|
| 831 |
+
M = meanshape_pcd_tensor.shape[0]
|
| 832 |
+
meanshape_points = meanshape_pcd_tensor.view(1, M, 3).float()
|
| 833 |
+
#make sure map to cuda0
|
| 834 |
+
average_aggregated_features = torch.load(f'//mnt/4T/Yung/yung_large_files/semantic_feature/test_notebook/8v_key/sem_cat_pcd_untex/cup_dino_feature.pt', map_location={"cuda:1": "cuda:0"})
|
| 835 |
+
sem_global_pcd_list.append(meanshape_points[0])
|
| 836 |
+
sem_global_list.append(average_aggregated_features[0].detach().cpu())
|
| 837 |
+
#fig =plot_pointclouds_3d_with_pca(average_aggregated_features[0].detach().cpu(),meanshape_points[0])
|
| 838 |
+
#fig.savefig('test.png')
|
| 839 |
+
for j,instance in enumerate(instances):
|
| 840 |
+
#break
|
| 841 |
+
print("Processing", instance)
|
| 842 |
+
#obj_path = f'/media/xyz/data/HouseCat6D/obj_models_small_size_final/{cat}/{instance}.obj'
|
| 843 |
+
#instance_pcd_tensor = torch.load(f'{save_dir}/saved_pcd_untex/{cat}/{instance}_pcd.pt')[0]
|
| 844 |
+
#obj_path = f'/media/xyz/data1/HouseCat6D/obj_models_small_size_final/{cat}/{instance}.obj'
|
| 845 |
+
# if instance != 'cup-grey_handle':
|
| 846 |
+
# # original pcd
|
| 847 |
+
instance_pcd_path = f'Yung/yung_large_files/semantic_feature/test_notebook/saved_pcd/{cat}/test/{instance}.txt'
|
| 848 |
+
# Load the instance point cloud
|
| 849 |
+
instance_pcd_np = np.loadtxt(instance_pcd_path)
|
| 850 |
+
reference_scale = np.linalg.norm(instance_pcd_np.max(axis=0) - instance_pcd_np.min(axis=0))
|
| 851 |
+
|
| 852 |
+
# else:
|
| 853 |
+
# instance_pcd_path = f'Yung/yung_large_files/pose_can_results/housecat6d_sonata_feature/scene01/000000/cup-grey_handle/normalized_groundtruth_pca.ply'
|
| 854 |
+
# pcd = o3d.io.read_point_cloud(instance_pcd_path)
|
| 855 |
+
# instance_pcd_np = np.asarray(pcd.points)
|
| 856 |
+
|
| 857 |
+
current_scale = np.linalg.norm(instance_pcd_np.max(axis=0) - instance_pcd_np.min(axis=0))
|
| 858 |
+
scale_factor = reference_scale / current_scale
|
| 859 |
+
instance_pcd_np = instance_pcd_np * scale_factor
|
| 860 |
+
|
| 861 |
+
scale = np.linalg.norm(instance_pcd_np.max(axis=0) - instance_pcd_np.min(axis=0))
|
| 862 |
+
print("Scale:", scale)
|
| 863 |
+
|
| 864 |
+
instance_pcd_tensor = torch.from_numpy(instance_pcd_np)
|
| 865 |
+
N = instance_pcd_tensor.shape[0]
|
| 866 |
+
instance_points = instance_pcd_tensor.view(1, N, 3).float()
|
| 867 |
+
try:
|
| 868 |
+
# aggregated_features = torch.load(f'{save_dir}/saved_dino_pcd_untex/{cat}/{instance}_dino_feature.pt')
|
| 869 |
+
aggregated_features = average_aggregated_features
|
| 870 |
+
except:
|
| 871 |
+
print(f"Warning: {instance} not found.")
|
| 872 |
+
continue
|
| 873 |
+
# plot_pointclouds_3d_with_pca(aggregated_features[0].detach().cpu(),
|
| 874 |
+
# instance_points[0])
|
| 875 |
+
|
| 876 |
+
sem_global_pcd_list.append(instance_points[0].detach().cpu())
|
| 877 |
+
sem_global_list.append(aggregated_features[0].detach().cpu())
|
| 878 |
+
if len(sem_global_list)>4:
|
| 879 |
+
break
|
| 880 |
+
|
| 881 |
+
fig = plot_pointclouds_3d_with_copca(sem_global_list,sem_global_pcd_list,co_pca=True)
|
| 882 |
+
fig.savefig(f'./{save_dir}/{cat}.png')
|
| 883 |
+
###############################
|
| 884 |
+
|
| 885 |
+
|
| 886 |
+
# TODO: Change extractor model to dinov3
|
| 887 |
+
# 1) Build a ViT-S/16 backbone from timm (shape-compatible with your hooks)
|
| 888 |
+
extractor = DINOv3ExtractorAdapter(
|
| 889 |
+
model_id="facebook/dinov3-vits16-pretrain-lvd1689m", # ViT-S/16
|
| 890 |
+
device="cuda"
|
| 891 |
+
)
|
| 892 |
+
extractor.model = extractor.model.cuda(0)
|
| 893 |
+
# extractor = torch.hub.load('facebookresearch/dinov2', model_dict['small'], pretrained=True).cuda()
|
| 894 |
+
|
| 895 |
+
|
| 896 |
+
# cat_list = ['bottle','box','can','cup','cutlery','glass','remote','shoe','tube','teapot']
|
| 897 |
+
cat_list = ['cup']
|
| 898 |
+
|
| 899 |
+
#cat_list = ['teapot']
|
| 900 |
+
#TODO: if condition for tex rendering
|
| 901 |
+
for cat in cat_list:
|
| 902 |
+
# orriginal
|
| 903 |
+
with open(f'/mnt/4T/Yung/yung_large_files/semantic_feature/test_notebook/housecat_{cat}/raw/housecat1_train.txt', 'r') as f:
|
| 904 |
+
instances = [line.strip() for line in f.readlines()]
|
| 905 |
+
|
| 906 |
+
print(instances)
|
| 907 |
+
# #revised
|
| 908 |
+
# # instance try cup-grey_handle
|
| 909 |
+
# instances = ['cup-grey_handle']
|
| 910 |
+
|
| 911 |
+
aggregated_features_list = [] # N * [1, 1024, 384]
|
| 912 |
+
# Load the mean shape point cloud
|
| 913 |
+
meanshape_path = f'Yung/yung_large_files/semantic_feature/test_notebook/saved_pcd/{cat}/mean_shape/mean_shape_pcd_1.txt'
|
| 914 |
+
meanshape_pcd_np = np.loadtxt(meanshape_path)
|
| 915 |
+
meanshape_pcd_tensor = torch.from_numpy(meanshape_pcd_np)
|
| 916 |
+
M = meanshape_pcd_tensor.shape[0]
|
| 917 |
+
# modify for cuda0
|
| 918 |
+
meanshape_points = meanshape_pcd_tensor.view(1, M, 3).float().cuda(0)
|
| 919 |
+
|
| 920 |
+
|
| 921 |
+
for j,instance in enumerate(instances):
|
| 922 |
+
# if instance != 'bottle-85_alcool':
|
| 923 |
+
# continue
|
| 924 |
+
print("Processing", instance)
|
| 925 |
+
obj_path = f'pose_dataset/HouseCat6D/obj_models_small_size_final/{cat}/{instance}.obj'
|
| 926 |
+
instance_pcd_path = f'Yung/yung_large_files/semantic_feature/test_notebook/saved_pcd/{cat}/test/{instance}.txt'
|
| 927 |
+
|
| 928 |
+
# Load the instance point cloud
|
| 929 |
+
instance_pcd_np = np.loadtxt(instance_pcd_path)
|
| 930 |
+
instance_pcd_tensor = torch.from_numpy(instance_pcd_np)
|
| 931 |
+
N = instance_pcd_tensor.shape[0]
|
| 932 |
+
# modify for cuda0
|
| 933 |
+
instance_points = instance_pcd_tensor.view(1, N, 3).float().cuda(0)
|
| 934 |
+
|
| 935 |
+
try:
|
| 936 |
+
verts, faces, aux = load_obj(obj_path)
|
| 937 |
+
except ValueError as e:
|
| 938 |
+
print(f"Warning: {e}, attempting to load without material.")
|
| 939 |
+
|
| 940 |
+
try:
|
| 941 |
+
verts, faces, aux = load_obj(obj_path, load_textures=True)
|
| 942 |
+
except ValueError as e2:
|
| 943 |
+
print(f"Failed to load {obj_path} without material: {e2}")
|
| 944 |
+
continue
|
| 945 |
+
|
| 946 |
+
# 检查 verts_uvs 是否为 None
|
| 947 |
+
if aux.verts_uvs is not None:
|
| 948 |
+
verts_uvs = aux.verts_uvs[None, ...] # (1, V, 2)
|
| 949 |
+
faces_uvs = faces.textures_idx[None, ...] # (1, F, 3)
|
| 950 |
+
tex_maps = aux.texture_images
|
| 951 |
+
|
| 952 |
+
# tex_maps is a dictionary of {material name: texture image}.
|
| 953 |
+
# Take the first image:
|
| 954 |
+
if tex_maps:
|
| 955 |
+
texture_image = list(tex_maps.values())[0]
|
| 956 |
+
texture_image = texture_image[None, ...] # (1, H, W, 3)
|
| 957 |
+
|
| 958 |
+
# Create a textures object
|
| 959 |
+
tex = TexturesUV(verts_uvs=verts_uvs, faces_uvs=faces_uvs, maps=texture_image)
|
| 960 |
+
print(f"Loaded texture for {instance}.")
|
| 961 |
+
else:
|
| 962 |
+
# 如果 verts_uvs 是 None,直接跳过纹理处理,或者你可以设置默认行为
|
| 963 |
+
print(f"No UV coordinates for {instance}, skipping texture mapping.")
|
| 964 |
+
tex = None
|
| 965 |
+
|
| 966 |
+
# Initialise the mesh with textures
|
| 967 |
+
verts = normalize_mesh_verts(verts) # Housecat meshes are absolute scale
|
| 968 |
+
meshes = Meshes(verts=[verts], faces=[faces.verts_idx], textures=None)
|
| 969 |
+
# Rotate mesh 180 degrees around Y axis
|
| 970 |
+
rotation_matrix = torch.tensor([
|
| 971 |
+
[-1.0, 0.0, 0.0],
|
| 972 |
+
[0.0, 1.0, 0.0],
|
| 973 |
+
[0.0, 0.0, -1.0]
|
| 974 |
+
], dtype=torch.float32, device="cpu")
|
| 975 |
+
verts = torch.matmul(verts, rotation_matrix.T)
|
| 976 |
+
|
| 977 |
+
meshes = Meshes(verts=[verts], faces=[faces.verts_idx], textures=tex)
|
| 978 |
+
|
| 979 |
+
if meshes.textures is None:
|
| 980 |
+
meshes.textures = TexturesVertex(
|
| 981 |
+
verts_features=torch.ones_like(meshes.verts_padded(), device=device)
|
| 982 |
+
)
|
| 983 |
+
|
| 984 |
+
# render the mesh with 8 views, scale means the distance from the object to the camera
|
| 985 |
+
image_size=(420,420)
|
| 986 |
+
#images,fragments,cameras = render_batch(meshes,image_size=image_size,scale=1.0)
|
| 987 |
+
images,fragments,cameras = render(meshes,image_size=image_size,scale=2.0)
|
| 988 |
+
|
| 989 |
+
os.makedirs(f'{save_dir}/{cat}_rgb_dino_untex-try', exist_ok=True)
|
| 990 |
+
rgb = images.cpu().numpy()[:, :, :, :3]
|
| 991 |
+
image_grid(rgb, rows=1, cols=8, rgb=True)
|
| 992 |
+
plt.savefig(f'{save_dir}/{cat}_rgb_dino_untex-try/{instance}_rendering-texture_reverse.png')
|
| 993 |
+
plt.close()
|
| 994 |
+
|
| 995 |
+
# get the feature point cloud
|
| 996 |
+
feature_point_cloud, dino_feat_masked, feature_point_cloud_list = fuse_feature_rgbd(extractor,images,fragments,cameras)
|
| 997 |
+
|
| 998 |
+
# get the downsampled aggregated feature point cloud
|
| 999 |
+
num_pts= 1024
|
| 1000 |
+
nn_num= 100 # larger nn_num will make the feature more smooth
|
| 1001 |
+
sampled_points,aggregated_features = downsample_with_knn_feature_aggregation(feature_point_cloud,num_pts,nn_num)
|
| 1002 |
+
|
| 1003 |
+
# #Needed
|
| 1004 |
+
# index = np.random.choice(partial_feature_point_cloud.shape[0], 1024, replace=False)
|
| 1005 |
+
# plot_pointclouds_3d_with_copca(average_aggregated_features.squeeze(0).detach().cpu().numpy(),
|
| 1006 |
+
# partial_feature_point_cloud[index,3:],
|
| 1007 |
+
# sampled_points.squeeze(0).detach().cpu().numpy(),
|
| 1008 |
+
# partial_feature_point_cloud[index,:3])
|
| 1009 |
+
|
| 1010 |
+
|
| 1011 |
+
q=0
|
| 1012 |
+
|
| 1013 |
+
if False:
|
| 1014 |
+
q+=1
|
| 1015 |
+
inputs = trainset[q]
|
| 1016 |
+
rgb = inputs['rgb'][None].cuda()
|
| 1017 |
+
pts = inputs['pts'][None]
|
| 1018 |
+
choose = inputs['choose'][None]
|
| 1019 |
+
model = inputs['model'][None].cuda()
|
| 1020 |
+
rgb = inputs['rgb'][None].cuda()
|
| 1021 |
+
|
| 1022 |
+
_desc_q = extractor.forward_features(rgb)["x_prenorm"][:, :]
|
| 1023 |
+
#_desc_q = extractor.extract_descriptors(rgb,layer=11,facet='token',include_cls=True).squeeze(1) # B,L,C
|
| 1024 |
+
# _norm_q = torch.linalg.norm(_desc_q, dim=-1)[:, :, None]
|
| 1025 |
+
# _desc_q = _desc_q / (_norm_q)
|
| 1026 |
+
|
| 1027 |
+
dino_feature = _desc_q[:,1:,:]
|
| 1028 |
+
|
| 1029 |
+
|
| 1030 |
+
#dino_feature = self.rgb_extractor.forward_features(rgb)["x_prenorm"][:, 1:]
|
| 1031 |
+
#rgb=self.rgb_extractor.preprocess_pil(rgb)
|
| 1032 |
+
#dino_feature = self.rgb_extractor.extract_descriptors(rgb,layer=11,facet='key') # (1,900,384)
|
| 1033 |
+
f_dim = dino_feature.shape[-1]
|
| 1034 |
+
num_patches =int(dino_feature.shape[1]**0.5) # 1
|
| 1035 |
+
b=1
|
| 1036 |
+
dino_feature = dino_feature.reshape(b, num_patches, num_patches, f_dim).permute(0,3,1,2)
|
| 1037 |
+
|
| 1038 |
+
dino_feature = F.interpolate(dino_feature, size=(num_patches * 14, num_patches * 14), mode='nearest')
|
| 1039 |
+
dino_feature_2d_vis = dino_feature.detach().cpu()[0] #384, 224,224
|
| 1040 |
+
|
| 1041 |
+
b, d = dino_feature.shape[0:2]
|
| 1042 |
+
dino_feature = dino_feature.reshape(b,d,-1)
|
| 1043 |
+
choose_2 = choose.unsqueeze(1).repeat(1, d, 1).cuda()
|
| 1044 |
+
dino_feature = torch.gather(dino_feature,2,choose_2).contiguous() # b,d,n
|
| 1045 |
+
|
| 1046 |
+
#dino_feature = dino_feature / torch.std(dino_feature, dim=1, keepdim=True)
|
| 1047 |
+
#dino_feature = torch.norm(dino_feature, dim=1, keepdim=True)
|
| 1048 |
+
#choose_dino = choose.unsqueeze(1).repeat(1, d, 1Z
|
| 1049 |
+
#sem_model = sem_model / torch.std(sem_model, dim=-1, keepdim=True)
|
| 1050 |
+
#visual_global_sem_high = sem_model.detach().cpu().numpy()[0] #1024,384
|
| 1051 |
+
visual_partial_sem_high = dino_feature.permute(0,2,1).detach().cpu().numpy()[0] #1024,128
|
| 1052 |
+
|
| 1053 |
+
#visual_global_sem_low = self.feature_mlp(sem_model.permute(0,2,1)).permute(0,2,1).detach().cpu().numpy()[0]
|
| 1054 |
+
#visual_partial_sem_low = rgb_local.permute(0,2,1).detach().cpu().numpy()[0]
|
| 1055 |
+
# transform the pts with GT 9D Pose into object coordinate
|
| 1056 |
+
translation_gt = inputs['translation_label'][None]
|
| 1057 |
+
rotation_gt = inputs['rotation_label'][None]
|
| 1058 |
+
size_gt = inputs['size_label'][None]
|
| 1059 |
+
pts_obj_frame = (inputs['pts'] - translation_gt.unsqueeze(1)) / (torch.norm(size_gt, dim=1).view(b, 1, 1) + 1e-8) @ rotation_gt
|
| 1060 |
+
#kpt_obj_frame = (kpt_3d - translation_gt.unsqueeze(1)) / (torch.norm(size_gt, dim=1).view(b, 1, 1) + 1e-8) @ rotation_gt
|
| 1061 |
+
|
| 1062 |
+
# dino_feature_2d_vis_pca = vis_pca_pixelwise(dino_feature_2d_vis[None])[0]
|
| 1063 |
+
# plt.imshow(dino_feature_2d_vis_pca[:,:,:3])
|
| 1064 |
+
# plt.show()
|
| 1065 |
+
# fig =plt.figure()
|
| 1066 |
+
# rgb_unnorm = unnormalize(rgb[0].permute(1,2,0).detach().cpu())
|
| 1067 |
+
# plt.imshow(rgb_unnorm)
|
| 1068 |
+
# plt.show()
|
| 1069 |
+
# image_mask = ((rgb_unnorm.clone().sum(axis=2) >0.1)*1.0)[None,None] # 224,224
|
| 1070 |
+
|
| 1071 |
+
# rgb_mask = np.array(image_mask[0,0,:,:,None]).repeat(384, axis=2).transpose(2,0,1)
|
| 1072 |
+
|
| 1073 |
+
# dino_feature_2d_vis[rgb_mask==0] = 0
|
| 1074 |
+
# masked_dino_feature_2d_vis_pca = vis_pca_pixelwise(dino_feature_2d_vis[None])[0]
|
| 1075 |
+
# plt.imshow(masked_dino_feature_2d_vis_pca[:,:,:])
|
| 1076 |
+
# plt.show()
|
| 1077 |
+
|
| 1078 |
+
|
| 1079 |
+
# print('self.pca.cateagg-partial')
|
| 1080 |
+
# index = np.random.choice(partial_feature_point_cloud.shape[0], 1024, replace=False)
|
| 1081 |
+
# #average_aggregated_features = torch.load(f'sem_cat_pcd/{cat}_dino_feature.pt')
|
| 1082 |
+
|
| 1083 |
+
average_aggregated_features = torch.load(f'/home/xyz/anything6d_project/Sem-GCE-AG-Pose/sem_cat_pcd/{cat}_dino_feature.pt')
|
| 1084 |
+
# #plot_pointclouds_3d_with_copca(aggregated_features.squeeze(0).detach().cpu().numpy(), partial_feature_point_cloud[index,3:], sampled_points.squeeze(0).detach().cpu().numpy(), pts_obj_frame)
|
| 1085 |
+
|
| 1086 |
+
plot_pointclouds_3d_with_copca_old(average_aggregated_features.squeeze(0).detach().cpu().numpy(),
|
| 1087 |
+
visual_partial_sem_high,
|
| 1088 |
+
sampled_points.squeeze(0).detach().cpu().numpy(),
|
| 1089 |
+
pts_obj_frame[0].detach().cpu().numpy())
|
| 1090 |
+
plt.show()
|
| 1091 |
+
|
| 1092 |
+
|
| 1093 |
+
# plot_pointclouds_3d_with_copca(average_aggregated_features.squeeze(0).detach().cpu().numpy(),
|
| 1094 |
+
# visual_partial_sem_high,
|
| 1095 |
+
# sampled_points.squeeze(0).detach().cpu().numpy(),
|
| 1096 |
+
# pts_obj_frame[0].detach().cpu().numpy())
|
| 1097 |
+
|
| 1098 |
+
|
| 1099 |
+
# #query_points =np.random.choice(1024, 3)
|
| 1100 |
+
# query_points, sampled_indices = sample_farthest_points(pts_obj_frame, K=4) # Shape: (1, 1024, 3), (1, 1024)
|
| 1101 |
+
# plot_pointclouds_with_color_mapping(visual_partial_sem_high,
|
| 1102 |
+
# aggregated_features.squeeze(0).detach().cpu().numpy(),
|
| 1103 |
+
# pts_obj_frame[0].detach().cpu().numpy(),
|
| 1104 |
+
# model[0].detach().cpu().numpy(),
|
| 1105 |
+
# sampled_indices[0], similarity_threshold=None)
|
| 1106 |
+
|
| 1107 |
+
|
| 1108 |
+
# # plot_pointclouds_3d_with_copca(average_aggregated_features.squeeze(0).detach().cpu().numpy(), partial_feature_point_cloud[index,3:], sampled_points.squeeze(0).detach().cpu().numpy(), partial_feature_point_cloud[index,:3])
|
| 1109 |
+
# # plot_pointclouds_3d_with_pca(average_aggregated_features.squeeze(0).detach().cpu().numpy(), partial_feature_point_cloud[index,3:], sampled_points.squeeze(0).detach().cpu().numpy(), partial_feature_point_cloud[index,:3])
|
| 1110 |
+
# partial_feature_point_cloud = feature_point_cloud_list[5]
|
| 1111 |
+
# plot_pointclouds_3d_with_copca(visual_partial_sem_high,
|
| 1112 |
+
# partial_feature_point_cloud[index,3:],
|
| 1113 |
+
# pts_obj_frame[0].detach().cpu().numpy(),
|
| 1114 |
+
# partial_feature_point_cloud[index,:3])
|
| 1115 |
+
|
| 1116 |
+
# plot_pointclouds_3d_with_copca(average_aggregated_features.squeeze(0).detach().cpu().numpy(), aggregated_features.squeeze(0).detach().cpu().numpy(), sampled_points.squeeze(0).detach().cpu().numpy(), sampled_points.squeeze(0).detach().cpu().numpy())
|
| 1117 |
+
|
| 1118 |
+
os.makedirs(f'{save_dir}/saved_dino_pcd_untex-try/{cat}', exist_ok=True)
|
| 1119 |
+
torch.save(aggregated_features, f'{save_dir}/saved_dino_pcd_untex-try/{cat}/{instance}_dinov3_feature-texture_reverse.pt')
|
| 1120 |
+
|
| 1121 |
+
os.makedirs(f'{save_dir}/saved_pcd_untex-try/{cat}', exist_ok=True)
|
| 1122 |
+
torch.save(sampled_points, f'{save_dir}/saved_pcd_untex-try/{cat}/{instance}_pcd-texture_reverse.pt')
|
| 1123 |
+
|
| 1124 |
+
aggregated_features_list.append(aggregated_features)
|
| 1125 |
+
# #break
|
| 1126 |
+
vis_dino = vis_pca_pixelwise(np.array(dino_feat_masked))
|
| 1127 |
+
vis_img = np.clip(vis_dino[:,:,:,:],a_min=0,a_max=1)
|
| 1128 |
+
image_grid(vis_img, rows=1, cols=8, rgb=True)
|
| 1129 |
+
|
| 1130 |
+
os.makedirs(f'{save_dir}/{cat}_rgb_dino_untex-try', exist_ok=True)
|
| 1131 |
+
plt.savefig(f'{save_dir}/{cat}_rgb_dino_untex-try/{instance}_dinov3-texture_reverse.png')
|
| 1132 |
+
plt.close()
|
| 1133 |
+
if False:
|
| 1134 |
+
|
| 1135 |
+
rgb = images.cpu().numpy()[:, :, :, :3]
|
| 1136 |
+
mask = images[:, ..., 3].cpu().numpy()!=0
|
| 1137 |
+
depth_image = fragments[:, ..., 0].cpu().numpy()*mask
|
| 1138 |
+
image_grid(rgb, rows=1, cols=8, rgb=True)
|
| 1139 |
+
# os.makedirs(f'/home/tulrfpf/code/PointFlowRenderer/{cat}_rgb_dino', exist_ok=True)
|
| 1140 |
+
# plt.savefig(f'/home/tulrfpf/code/PointFlowRenderer/{cat}_rgb_dino/{instance}_rgb.png')
|
| 1141 |
+
# image_grid(depth_image[...,None], rows=2, cols=4, rgb=True)
|
| 1142 |
+
# image_grid(mask[...,None], rows=2, cols=4, rgb=True)
|
| 1143 |
+
|
| 1144 |
+
|
| 1145 |
+
|
| 1146 |
+
fig = plt.figure(figsize=(10, 10))
|
| 1147 |
+
ax = fig.add_subplot(111, projection="3d")
|
| 1148 |
+
#ax.scatter(sampled_points[:, 2], sampled_points[:,0], sampled_points[:, 1], c="b")
|
| 1149 |
+
pca_color =vis_pca(feature_point_cloud[:, 3:])
|
| 1150 |
+
ax.scatter(feature_point_cloud[:, 2], feature_point_cloud[:, 0], feature_point_cloud[:, 1], c=pca_color,s=0.1)
|
| 1151 |
+
#create_camera_geometry_batch(ax=ax,R_batch=R,T_batch=T,order=(2,0,1))
|
| 1152 |
+
ax.set_xlabel("z")
|
| 1153 |
+
ax.set_ylabel("x")
|
| 1154 |
+
ax.set_zlabel("y")
|
| 1155 |
+
ax.set_xlim(-2, 2)
|
| 1156 |
+
ax.set_ylim(-2, 2)
|
| 1157 |
+
ax.set_zlim(-2, 2)
|
| 1158 |
+
plt.title("Sampled Dense Points from Mesh")
|
| 1159 |
+
plt.show()
|
| 1160 |
+
|
| 1161 |
+
fig = plt.figure(figsize=(10, 10))
|
| 1162 |
+
ax = fig.add_subplot(111, projection="3d")
|
| 1163 |
+
pca_color =vis_pca(aggregated_features.squeeze(0))
|
| 1164 |
+
sampled_points= sampled_points.squeeze(0).cpu().detach().numpy()
|
| 1165 |
+
ax.scatter(sampled_points[:, 2], sampled_points[:, 0], sampled_points[:, 1], c=pca_color,s=50)
|
| 1166 |
+
#create_camera_geometry_batch(ax=ax,R_batch=R,T_batch=T,order=(2,0,1))
|
| 1167 |
+
ax.set_xlabel("z")
|
| 1168 |
+
ax.set_ylabel("x")
|
| 1169 |
+
ax.set_zlabel("y")
|
| 1170 |
+
ax.set_xlim(-2, 2)
|
| 1171 |
+
ax.set_ylim(-2, 2)
|
| 1172 |
+
ax.set_zlim(-2, 2)
|
| 1173 |
+
plt.title("Sampled Sparse Points from Mesh")
|
| 1174 |
+
plt.show()
|
| 1175 |
+
#break
|
| 1176 |
+
# Assign the aggregated features to the mean shape point cloud
|
| 1177 |
+
aggregated_features_tensor = torch.cat(aggregated_features_list, dim=0) #[N, 1024, 384]
|
| 1178 |
+
average_aggregated_features = aggregated_features_tensor.mean(dim=0, keepdim=True)
|
| 1179 |
+
print("Average Aggregated Features Shape:", average_aggregated_features.shape) # Should be (1, 1024, 384)
|
| 1180 |
+
|
| 1181 |
+
os.makedirs(f'{save_dir}/sem_cat_pcd_untex-try', exist_ok=True)
|
| 1182 |
+
torch.save(average_aggregated_features, f'{save_dir}/sem_cat_pcd_untex-try/{cat}_dinov3_feature.pt')
|
| 1183 |
+
|
| 1184 |
+
# fig = plt.figure(figsize=(10, 10))
|
| 1185 |
+
# ax = fig.add_subplot(111, projection="3d")
|
| 1186 |
+
# pca_color =vis_pca(average_aggregated_features.squeeze(0))
|
| 1187 |
+
# # sampled_points= sampled_points.squeeze(0).cpu().detach().numpy()
|
| 1188 |
+
# meanshape_points = meanshape_points.squeeze(0).cpu().detach().numpy()
|
| 1189 |
+
# ax.scatter(meanshape_points[:, 2], meanshape_points[:, 0], meanshape_points[:, 1], c=pca_color,s=10.0, marker='o')
|
| 1190 |
+
# ax.set_xlabel("z")
|
| 1191 |
+
# ax.set_ylabel("x")
|
| 1192 |
+
# ax.set_zlabel("y")
|
| 1193 |
+
# ax.set_xlim(-2, 2)
|
| 1194 |
+
# ax.set_ylim(-2, 2)
|
| 1195 |
+
# ax.set_zlim(-2, 2)
|
| 1196 |
+
# plt.title("Shape Prior Dino")
|
| 1197 |
+
# pl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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pickle
|
| 2 |
+
import torch
|
| 3 |
+
from custom_utils import ShapeNetCore
|
| 4 |
+
from custom_utils import _compute_fov,_sample_points_from_faces
|
| 5 |
+
from custom_utils import image_grid
|
| 6 |
+
from custom_utils.shapenet_base import HouseCatDataset
|
| 7 |
+
import matplotlib.pyplot as plt
|
| 8 |
+
import numpy as np
|
| 9 |
+
import k3d
|
| 10 |
+
import os
|
| 11 |
+
import json
|
| 12 |
+
import torch
|
| 13 |
+
from PIL import Image
|
| 14 |
+
import numpy as np
|
| 15 |
+
import torch
|
| 16 |
+
from plyfile import PlyData # pip install plyfile
|
| 17 |
+
from types import SimpleNamespace
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
import open3d as o3d
|
| 20 |
+
import re
|
| 21 |
+
|
| 22 |
+
import cv2
|
| 23 |
+
import imageio
|
| 24 |
+
import numpy as np
|
| 25 |
+
from PIL import Image
|
| 26 |
+
import matplotlib.pyplot as plt
|
| 27 |
+
from torchvision import transforms
|
| 28 |
+
from custom_utils.extractor import ViTExtractor
|
| 29 |
+
import torch.nn.functional as F
|
| 30 |
+
from sklearn.decomposition import PCA as sklearnPCA
|
| 31 |
+
import math
|
| 32 |
+
from custom_utils.utils_general import center_crop
|
| 33 |
+
|
| 34 |
+
from pytorch3d.io import load_objs_as_meshes, load_obj
|
| 35 |
+
from pytorch3d.implicitron.tools.point_cloud_utils import get_rgbd_point_cloud
|
| 36 |
+
from pytorch3d.structures import Meshes
|
| 37 |
+
from pytorch3d.renderer import (
|
| 38 |
+
PerspectiveCameras,
|
| 39 |
+
FoVPerspectiveCameras,
|
| 40 |
+
PointLights,
|
| 41 |
+
MeshRasterizer,
|
| 42 |
+
MeshRenderer,
|
| 43 |
+
RasterizationSettings,
|
| 44 |
+
HardPhongShader,
|
| 45 |
+
TexturesVertex,
|
| 46 |
+
look_at_view_transform,
|
| 47 |
+
ray_bundle_to_ray_points,
|
| 48 |
+
NDCMultinomialRaysampler,
|
| 49 |
+
TexturesUV,
|
| 50 |
+
BlendParams,
|
| 51 |
+
|
| 52 |
+
TexturesVertex
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
from pytorch3d.implicitron.tools.point_cloud_utils import get_rgbd_point_cloud
|
| 56 |
+
from pytorch3d.structures import Pointclouds
|
| 57 |
+
import torch
|
| 58 |
+
from pytorch3d.ops import sample_farthest_points, knn_points, knn_gather
|
| 59 |
+
|
| 60 |
+
from matplotlib import cm
|
| 61 |
+
import numpy as np
|
| 62 |
+
import matplotlib.pyplot as plt
|
| 63 |
+
from sklearn.decomposition import PCA
|
| 64 |
+
from mpl_toolkits.mplot3d import Axes3D
|
| 65 |
+
|
| 66 |
+
import torch
|
| 67 |
+
import torch.nn as nn
|
| 68 |
+
import torch.nn.functional as F
|
| 69 |
+
from transformers import AutoConfig, AutoModel
|
| 70 |
+
|
| 71 |
+
class Dinov3PatchExtractor(nn.Module):
|
| 72 |
+
"""
|
| 73 |
+
Returns patch tokens as [B, C, T] (C=384 for ViT-S/16).
|
| 74 |
+
Input must be ImageNet-normalized [B,3,H,W].
|
| 75 |
+
"""
|
| 76 |
+
def __init__(self, model_id="facebook/dinov3-vits16-pretrain-lvd1689m", freeze=True):
|
| 77 |
+
super().__init__()
|
| 78 |
+
self.cfg = AutoConfig.from_pretrained(model_id)
|
| 79 |
+
self.C = self.cfg.hidden_size # 384
|
| 80 |
+
self.nreg = getattr(self.cfg, "num_register_tokens", 0)
|
| 81 |
+
self.backbone = AutoModel.from_pretrained(model_id).eval()
|
| 82 |
+
self.p = 16 # ViT-S/16 的 patch 大小
|
| 83 |
+
if freeze:
|
| 84 |
+
for p in self.backbone.parameters():
|
| 85 |
+
p.requires_grad = False
|
| 86 |
+
|
| 87 |
+
@torch.no_grad()
|
| 88 |
+
def forward(self, x): # x: [B,3,H,W], normalized
|
| 89 |
+
B, _, H, W = x.shape
|
| 90 |
+
out = self.backbone(x)
|
| 91 |
+
seq = out.last_hidden_state # [B, T_all, C]
|
| 92 |
+
patch_seq = seq[:, 1 + self.nreg :, :] # drop CLS + registers -> [B, T_patch, C]
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
# 关键:用输入尺寸和 patch 大小推 H_p, W_p
|
| 96 |
+
H_p = H // self.p
|
| 97 |
+
W_p = W // self.p
|
| 98 |
+
T = patch_seq.shape[1]
|
| 99 |
+
|
| 100 |
+
# 若预处理不是整除,或模型内部有 pad/裁剪,做个健壮性兜底
|
| 101 |
+
if H_p * W_p != T:
|
| 102 |
+
# 按长宽比从 T 的因子中挑最合理的 (H_p, W_p)
|
| 103 |
+
aspect = H / W
|
| 104 |
+
best = None
|
| 105 |
+
for h in range(1, int(math.sqrt(T)) + 1):
|
| 106 |
+
if T % h == 0:
|
| 107 |
+
w = T // h
|
| 108 |
+
for (hh, ww) in [(h, w), (w, h)]:
|
| 109 |
+
score = abs((hh / ww) - aspect)
|
| 110 |
+
if best is None or score < best[2]:
|
| 111 |
+
best = (hh, ww, score)
|
| 112 |
+
if best is None:
|
| 113 |
+
raise RuntimeError(f"Cannot factor T={T} into (H_p,W_p).")
|
| 114 |
+
H_p, W_p, _ = best
|
| 115 |
+
|
| 116 |
+
feat = patch_seq.view(B, H_p, W_p, self.C).permute(0, 3, 1, 2) # [B,C,H_p,W_p]
|
| 117 |
+
return feat
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
class DINOv3ExtractorAdapter:
|
| 121 |
+
"""
|
| 122 |
+
Adapter to mimic ViTExtractor.extract_descriptors(batch, layer, facet, bin)
|
| 123 |
+
Returns descriptors with shape [B, 1, T, d] like ViTExtractor.
|
| 124 |
+
"""
|
| 125 |
+
def __init__(self, model_id="facebook/dinov3-vits16-pretrain-lvd1689m", device="cuda"):
|
| 126 |
+
self.device = device
|
| 127 |
+
self.model = Dinov3PatchExtractor(model_id, freeze=True).to(device)
|
| 128 |
+
self.p = 16 # patch size for vits16
|
| 129 |
+
self.stride = (16, 16) # nominal stride on tokens
|
| 130 |
+
self.mean = (0.485, 0.456, 0.406) # ImageNet normalization
|
| 131 |
+
self.std = (0.229, 0.224, 0.225)
|
| 132 |
+
|
| 133 |
+
@torch.no_grad()
|
| 134 |
+
def extract_descriptors(self, batch, layer=11, facet='token', bin=False, include_cls=False):
|
| 135 |
+
"""
|
| 136 |
+
batch: [B,3,H,W] normalized to ImageNet stats.
|
| 137 |
+
returns: [B, 1, T, d](T = H_p*W_p, d=384)
|
| 138 |
+
"""
|
| 139 |
+
# DINOv3 doesn't expose q/k/v hooks like timm; we just use its final patch tokens.
|
| 140 |
+
# 先拿到 [B,C,H_p,W_p]
|
| 141 |
+
feat_map = self.model(batch.to(self.device)) # [B,384,H_p,W_p]
|
| 142 |
+
B, C, H_p, W_p = feat_map.shape
|
| 143 |
+
# 再回到 [B,1,T,d] 以兼容你现有代码
|
| 144 |
+
desc = feat_map.flatten(2).permute(0, 2, 1).unsqueeze(1) # [B,1,H_p*W_p,384]
|
| 145 |
+
return desc
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def sample_points_on_sphere(num_points=80):
|
| 149 |
+
points = []
|
| 150 |
+
phi = (1 + math.sqrt(5)) / 2 # golden ratio
|
| 151 |
+
|
| 152 |
+
for i in range(num_points):
|
| 153 |
+
theta = 2 * math.pi * i / phi # azimuthal angle
|
| 154 |
+
z = 1 - (2 * i + 1) / num_points # z-coordinate, uniform from -1 to 1
|
| 155 |
+
radius = math.sqrt(1 - z * z) # radius for the xy-plane
|
| 156 |
+
x = radius * math.cos(theta)
|
| 157 |
+
y = radius * math.sin(theta)
|
| 158 |
+
points.append([x, y, z])
|
| 159 |
+
|
| 160 |
+
return torch.tensor(points, dtype=torch.float32)
|
| 161 |
+
|
| 162 |
+
def get_cube_vertices():
|
| 163 |
+
# Cube vertices (8 vertices)
|
| 164 |
+
return torch.tensor([[1, 1, 1],
|
| 165 |
+
[1, 1, -1],
|
| 166 |
+
[1, -1, 1],
|
| 167 |
+
[1, -1, -1],
|
| 168 |
+
[-1, 1, 1],
|
| 169 |
+
[-1, 1, -1],
|
| 170 |
+
[-1, -1, 1],
|
| 171 |
+
[-1, -1, -1]], dtype=torch.float32) # Ensure float type
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def render(meshes,scale=3.0,image_size=(420,420),light=(0.3,0.3,0.3)):
|
| 176 |
+
# prepare the camera
|
| 177 |
+
num_views = 8
|
| 178 |
+
# Get the cube vertices
|
| 179 |
+
#cube_vertices = get_cube_vertices()*scale
|
| 180 |
+
cube_vertices = sample_points_on_sphere(num_views)*scale
|
| 181 |
+
#up = torch.randn(1, 3)
|
| 182 |
+
up=torch.tensor([[0.0, 0.0, 1.0]], dtype=torch.float32)
|
| 183 |
+
up = up / torch.norm(up, dim=1)[:, None]
|
| 184 |
+
R, T = look_at_view_transform(eye=cube_vertices, at=torch.tensor([[0.0, 0.0, 0.0]], dtype=torch.float32), up=up)
|
| 185 |
+
cam_K= np.array([[572, 0.0, image_size[0]//2], [0.0, 572, image_size[1]//2], [0.0, 0.0, 1.0]])
|
| 186 |
+
fx,_,cx,_,fy,cy,_,_,_=cam_K.reshape(9)
|
| 187 |
+
fov_x, fov_y = _compute_fov(cam_K, 420, 420)
|
| 188 |
+
|
| 189 |
+
cameras = PerspectiveCameras(device=device, R=R, T=T, image_size=((420,420),),
|
| 190 |
+
focal_length=torch.tensor([[fx, fy]], dtype=torch.float32),
|
| 191 |
+
principal_point=torch.tensor([[cx, cy]], dtype=torch.float32),
|
| 192 |
+
in_ndc=False)
|
| 193 |
+
|
| 194 |
+
# prepare the lights
|
| 195 |
+
raster_settings = RasterizationSettings(image_size=image_size)
|
| 196 |
+
lights = PointLights(location=torch.tensor([0.0, 1.0, -2.0], device=device)[None], ambient_color=(light,),diffuse_color=(light,),device=device)
|
| 197 |
+
|
| 198 |
+
# move the data to the device
|
| 199 |
+
meshes = meshes.to(device)
|
| 200 |
+
cameras = cameras.to(device)
|
| 201 |
+
if len(cameras) != 1 and len(cameras) % len(meshes) != 0:
|
| 202 |
+
raise ValueError("Mismatch between batch dims of cameras and meshes.")
|
| 203 |
+
if len(cameras) > 1:
|
| 204 |
+
meshes = meshes.extend(len(cameras) // len(meshes))
|
| 205 |
+
|
| 206 |
+
# prepare the renderer
|
| 207 |
+
class MeshRendererWithDepth(torch.nn.Module):
|
| 208 |
+
def __init__(self, rasterizer, shader):
|
| 209 |
+
super().__init__()
|
| 210 |
+
self.rasterizer = rasterizer
|
| 211 |
+
self.shader = shader
|
| 212 |
+
|
| 213 |
+
def forward(self, meshes_world, **kwargs) -> torch.Tensor:
|
| 214 |
+
fragments = self.rasterizer(meshes_world, **kwargs)
|
| 215 |
+
images = self.shader(fragments, meshes_world, **kwargs)
|
| 216 |
+
return images, fragments.zbuf
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
blend_params = BlendParams(background_color=(0.0, 0.0, 0.0)) # Blue background
|
| 220 |
+
renderer = MeshRendererWithDepth(
|
| 221 |
+
rasterizer=MeshRasterizer(
|
| 222 |
+
cameras=cameras,
|
| 223 |
+
raster_settings=raster_settings,
|
| 224 |
+
),
|
| 225 |
+
# Set background color to blue [R, G, B]
|
| 226 |
+
|
| 227 |
+
shader=HardPhongShader(
|
| 228 |
+
device=device,
|
| 229 |
+
cameras=cameras,
|
| 230 |
+
lights=lights,
|
| 231 |
+
blend_params=blend_params
|
| 232 |
+
)
|
| 233 |
+
)
|
| 234 |
+
|
| 235 |
+
images,fragments = renderer(meshes)
|
| 236 |
+
return images,fragments,cameras
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def render_batch(meshes,scale=3.0,image_size=(420,420),light=(0.3,0.3,0.3)):
|
| 240 |
+
# prepare the camera
|
| 241 |
+
num_views = 8
|
| 242 |
+
# Get the cube vertices
|
| 243 |
+
cube_vertices = get_cube_vertices()*scale
|
| 244 |
+
# cube_vertices = sample_points_on_sphere(num_views)*scale
|
| 245 |
+
#up = torch.randn(1, 3)
|
| 246 |
+
up=torch.tensor([[0.0, 0.0, 1.0]], dtype=torch.float32)
|
| 247 |
+
#up = up / torch.norm(up, dim=1)[:, None]
|
| 248 |
+
R, T = look_at_view_transform(eye=cube_vertices, at=torch.tensor([[0.0, 0.0, 0.0]], dtype=torch.float32), up=up)
|
| 249 |
+
|
| 250 |
+
cam_K= np.array([[572, 0.0, image_size[0]//2], [0.0, 572, image_size[1]//2], [0.0, 0.0, 1.0]])
|
| 251 |
+
fx,_,cx,_,fy,cy,_,_,_=cam_K.reshape(9)
|
| 252 |
+
fov_x, fov_y = _compute_fov(cam_K, 420, 420)
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
# prepare the renderer
|
| 256 |
+
class MeshRendererWithDepth(torch.nn.Module):
|
| 257 |
+
def __init__(self, rasterizer, shader):
|
| 258 |
+
super().__init__()
|
| 259 |
+
self.rasterizer = rasterizer
|
| 260 |
+
self.shader = shader
|
| 261 |
+
|
| 262 |
+
def forward(self, meshes_world, **kwargs) -> torch.Tensor:
|
| 263 |
+
fragments = self.rasterizer(meshes_world, **kwargs)
|
| 264 |
+
images = self.shader(fragments, meshes_world, **kwargs)
|
| 265 |
+
return images, fragments.zbuf
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
blend_params = BlendParams(background_color=(0.0, 0.0, 0.0)) # Blue background
|
| 269 |
+
|
| 270 |
+
batch_size = 10
|
| 271 |
+
all_images=[]
|
| 272 |
+
all_fragments=[]
|
| 273 |
+
|
| 274 |
+
# move the data to the device
|
| 275 |
+
meshes = meshes.extend(batch_size).to(device)
|
| 276 |
+
for i in range(0,R.shape[0],batch_size):
|
| 277 |
+
R_batch = R[i:i+batch_size]
|
| 278 |
+
T_batch = T[i:i+batch_size]
|
| 279 |
+
cameras_batch = PerspectiveCameras(device=device, R=R_batch, T=T_batch, image_size=((420,420),),
|
| 280 |
+
focal_length=torch.tensor([[fx, fy]], dtype=torch.float32),
|
| 281 |
+
principal_point=torch.tensor([[cx, cy]], dtype=torch.float32),
|
| 282 |
+
in_ndc=False).to(device)
|
| 283 |
+
|
| 284 |
+
# prepare the lights
|
| 285 |
+
raster_settings = RasterizationSettings(image_size=image_size)
|
| 286 |
+
lights = PointLights(location=torch.tensor([0.0, 1.0, -2.0], device=device)[None],
|
| 287 |
+
ambient_color=(light,),diffuse_color=(light,),device=device)
|
| 288 |
+
|
| 289 |
+
renderer = MeshRendererWithDepth(
|
| 290 |
+
rasterizer=MeshRasterizer(
|
| 291 |
+
cameras=cameras_batch,
|
| 292 |
+
raster_settings=raster_settings,
|
| 293 |
+
),
|
| 294 |
+
# Set background color to blue [R, G, B]
|
| 295 |
+
shader=HardPhongShader(
|
| 296 |
+
device=device,
|
| 297 |
+
cameras=cameras_batch,
|
| 298 |
+
lights=lights,
|
| 299 |
+
blend_params=blend_params
|
| 300 |
+
)
|
| 301 |
+
)
|
| 302 |
+
images,fragments = renderer(meshes)
|
| 303 |
+
all_images.append(images)
|
| 304 |
+
all_fragments.append(fragments)
|
| 305 |
+
all_images = torch.cat(all_images,dim=0)
|
| 306 |
+
all_fragments = torch.cat(all_fragments,dim=0)
|
| 307 |
+
cameras = PerspectiveCameras(device=device, R=R, T=T, image_size=((420,420),),
|
| 308 |
+
focal_length=torch.tensor([[fx, fy]], dtype=torch.float32),
|
| 309 |
+
principal_point=torch.tensor([[cx, cy]], dtype=torch.float32),
|
| 310 |
+
in_ndc=False).to(device)
|
| 311 |
+
return all_images,all_fragments,cameras
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
# def fuse_feature_rgbd(extractor,images,fragments,cameras):
|
| 315 |
+
# dino_feat_masked_list = []
|
| 316 |
+
# feature_point_cloud_list = []
|
| 317 |
+
# for i in range(images.shape[0]):
|
| 318 |
+
# image = images.cpu().numpy()[i, :, :, :3]
|
| 319 |
+
# image_mask = images[i, ..., 3].cpu().numpy()!=0
|
| 320 |
+
# crop_size = (420, 420)
|
| 321 |
+
# crop_image, crop_mask, bbox = center_crop(image, image_mask, crop_size)
|
| 322 |
+
# cropped_image_np = cv2.resize(crop_image, crop_size, interpolation=cv2.INTER_AREA)
|
| 323 |
+
# #cropped_mask = cv2.resize(crop_mask*1.0, crop_size, interpolation=cv2.INTER_NEAREST)!=0 # Use nearest neighbor interpolation for masks
|
| 324 |
+
# orignal_size = (int(bbox[2]-bbox[0]), int(bbox[3]-bbox[1])) #K,K
|
| 325 |
+
|
| 326 |
+
# to_tensor = transforms.ToTensor()
|
| 327 |
+
# input_image = to_tensor(cropped_image_np).cuda(0)
|
| 328 |
+
# input_image = input_image.unsqueeze(0)
|
| 329 |
+
# #input_image=extractor.preprocess_pil(input_image)
|
| 330 |
+
# mean = torch.tensor([0.485, 0.456, 0.406]).cuda(0)
|
| 331 |
+
# std = torch.tensor([0.229, 0.224, 0.225]).cuda(0)
|
| 332 |
+
# input_image = (input_image - mean[None, :, None, None]) / std[None, :, None, None]
|
| 333 |
+
|
| 334 |
+
# _desc_q = extractor.extract_descriptors(input_image,layer=11, facet='key', include_cls=True).squeeze(1) # (1,900,384)
|
| 335 |
+
# # _desc_q = extractor.forward_features(input_image)["x_prenorm"][:, :] # (1,900,384)
|
| 336 |
+
# #_desc_q = extractor.extract_descriptors(input_image,layer=11,facet='token',include_cls=True).squeeze(1) # B,L,C
|
| 337 |
+
# # _norm_q = torch.linalg.norm(_desc_q, dim=-1)[:, :, None]
|
| 338 |
+
# # _desc_q = _desc_q / (_norm_q)
|
| 339 |
+
|
| 340 |
+
# desc = _desc_q[:,1:,:][None]
|
| 341 |
+
# #cls_token_q = _desc_q[:,0,:] #B,C`
|
| 342 |
+
|
| 343 |
+
# input_mask = to_tensor(crop_mask).cuda(0)
|
| 344 |
+
# input_mask = input_mask.unsqueeze(0)
|
| 345 |
+
|
| 346 |
+
# img_mask = to_tensor(image_mask)
|
| 347 |
+
|
| 348 |
+
# img_mask = img_mask.permute(1,2,0)
|
| 349 |
+
|
| 350 |
+
# dino_feat = patch2pixel_feats(desc, original_size=orignal_size) #reize back to K,K =>( K, K, 384)
|
| 351 |
+
# # create dino-feat with orignal size
|
| 352 |
+
# dino_height, dino_width, feat_dim = (image_size[0],image_size[1], desc.shape[-1])
|
| 353 |
+
# dino_feat_orig = torch.zeros(dino_height,dino_width,feat_dim)
|
| 354 |
+
# # Fill the dino features into the original tensor at the specified bounding box
|
| 355 |
+
# dino_feat_orig[bbox[1]:bbox[3], bbox[0]:bbox[2],:] = dino_feat #reize back to K,K =>(420, 420, 384) #gradint is not supported for this operation
|
| 356 |
+
# # Apply the mask
|
| 357 |
+
# dino_feat_masked = dino_feat_orig * img_mask
|
| 358 |
+
# dino_feat_masked = dino_feat_masked.permute(2,0,1).unsqueeze(0)
|
| 359 |
+
# dino_feat_masked_low = F.interpolate(dino_feat_masked, size=(30, 30), mode='bilinear')
|
| 360 |
+
|
| 361 |
+
# image_mask = images[i, ..., 3][None,None]
|
| 362 |
+
# depth_image = fragments[i, ..., 0][None]*image_mask
|
| 363 |
+
|
| 364 |
+
# # # Define the kernel for erosion (3x3 ones kernel)
|
| 365 |
+
# # kernel = torch.ones((1, 1, 5, 5), dtype=torch.float).cuda()
|
| 366 |
+
# # # Number of erosion iterations
|
| 367 |
+
# # iterations = 5
|
| 368 |
+
|
| 369 |
+
# # # Perform iterative erosion
|
| 370 |
+
# # for i in range(iterations):
|
| 371 |
+
# # # Apply erosion using 2D convolution
|
| 372 |
+
# # eroded_mask = F.conv2d(image_mask, kernel, padding=2)
|
| 373 |
+
# # image_mask = (eroded_mask == kernel.sum()).float() # Update mask to eroded version
|
| 374 |
+
|
| 375 |
+
# feature_point_cloud = get_feature_point_cloud(cameras[i], dino_feat_masked.to(device), depth_map=depth_image,mask=image_mask)#everthing on GPU
|
| 376 |
+
|
| 377 |
+
# index = np.random.choice(feature_point_cloud.points_list()[0].shape[0], 4096, replace=True)
|
| 378 |
+
# points = feature_point_cloud.points_list()[0].detach().cpu()[index,:]
|
| 379 |
+
# colors = feature_point_cloud.features_list()[0].detach().cpu()[index,:]
|
| 380 |
+
# # points = feature_point_cloud.points_list()[0].detach().cpu()[:,:]
|
| 381 |
+
# # colors = feature_point_cloud.features_list()[0].detach().cpu()[:,:]
|
| 382 |
+
# feature_point_cloud = torch.cat((points, colors), dim=1)
|
| 383 |
+
|
| 384 |
+
# dino_feat_masked_list.append(dino_feat_masked_low.detach().cpu())
|
| 385 |
+
# feature_point_cloud_list.append(feature_point_cloud)
|
| 386 |
+
# feature_point_cloud = torch.cat(feature_point_cloud_list, dim=0)
|
| 387 |
+
# dino_feat_masked = torch.cat(dino_feat_masked_list, dim=0)
|
| 388 |
+
# return feature_point_cloud,dino_feat_masked, feature_point_cloud_list
|
| 389 |
+
def fuse_feature_rgbd(extractor,images,fragments,cameras):
|
| 390 |
+
dino_feat_masked_list = []
|
| 391 |
+
feature_point_cloud_list = []
|
| 392 |
+
for i in range(images.shape[0]):
|
| 393 |
+
image = images.cpu().numpy()[i, :, :, :3]
|
| 394 |
+
image_mask = images[i, ..., 3].cpu().numpy()!=0
|
| 395 |
+
crop_size = (420, 420)
|
| 396 |
+
crop_image, crop_mask, bbox = center_crop(image, image_mask, crop_size)
|
| 397 |
+
cropped_image_np = cv2.resize(crop_image, crop_size, interpolation=cv2.INTER_AREA)
|
| 398 |
+
#cropped_mask = cv2.resize(crop_mask*1.0, crop_size, interpolation=cv2.INTER_NEAREST)!=0 # Use nearest neighbor interpolation for masks
|
| 399 |
+
orignal_size = (int(bbox[2]-bbox[0]), int(bbox[3]-bbox[1])) #K,K
|
| 400 |
+
|
| 401 |
+
to_tensor = transforms.ToTensor()
|
| 402 |
+
input_image = to_tensor(cropped_image_np).cuda(0)
|
| 403 |
+
input_image = input_image.unsqueeze(0)
|
| 404 |
+
#input_image=extractor.preprocess_pil(input_image)
|
| 405 |
+
mean = torch.tensor([0.485, 0.456, 0.406]).cuda(0)
|
| 406 |
+
std = torch.tensor([0.229, 0.224, 0.225]).cuda(0)
|
| 407 |
+
input_image = (input_image - mean[None, :, None, None]) / std[None, :, None, None]
|
| 408 |
+
|
| 409 |
+
_desc_q = extractor.extract_descriptors(input_image,layer=11, facet='key', include_cls=True).squeeze(1) # (1,900,384)
|
| 410 |
+
# _desc_q = extractor.forward_features(input_image)["x_prenorm"][:, :] # (1,900,384)
|
| 411 |
+
#_desc_q = extractor.extract_descriptors(input_image,layer=11,facet='token',include_cls=True).squeeze(1) # B,L,C
|
| 412 |
+
# _norm_q = torch.linalg.norm(_desc_q, dim=-1)[:, :, None]
|
| 413 |
+
# _desc_q = _desc_q / (_norm_q)
|
| 414 |
+
|
| 415 |
+
desc = _desc_q[:,1:,:][None]
|
| 416 |
+
#cls_token_q = _desc_q[:,0,:] #B,C`
|
| 417 |
+
|
| 418 |
+
input_mask = to_tensor(crop_mask).cuda(0)
|
| 419 |
+
input_mask = input_mask.unsqueeze(0)
|
| 420 |
+
|
| 421 |
+
img_mask = to_tensor(image_mask)
|
| 422 |
+
|
| 423 |
+
img_mask = img_mask.permute(1,2,0)
|
| 424 |
+
|
| 425 |
+
dino_feat = patch2pixel_feats(desc, original_size=orignal_size) #reize back to K,K =>( K, K, 384)
|
| 426 |
+
# create dino-feat with orignal size
|
| 427 |
+
dino_height, dino_width, feat_dim = (image_size[0],image_size[1], desc.shape[-1])
|
| 428 |
+
dino_feat_orig = torch.zeros(dino_height,dino_width,feat_dim)
|
| 429 |
+
# Fill the dino features into the original tensor at the specified bounding box
|
| 430 |
+
dino_feat_orig[bbox[1]:bbox[3], bbox[0]:bbox[2],:] = dino_feat #reize back to K,K =>(420, 420, 384) #gradint is not supported for this operation
|
| 431 |
+
# Apply the mask
|
| 432 |
+
dino_feat_masked = dino_feat_orig * img_mask
|
| 433 |
+
dino_feat_masked = dino_feat_masked.permute(2,0,1).unsqueeze(0)
|
| 434 |
+
dino_feat_masked_low = F.interpolate(dino_feat_masked, size=(30, 30), mode='bilinear')
|
| 435 |
+
|
| 436 |
+
image_mask = images[i, ..., 3][None,None]
|
| 437 |
+
depth_image = fragments[i, ..., 0][None]*image_mask
|
| 438 |
+
|
| 439 |
+
# # Define the kernel for erosion (3x3 ones kernel)
|
| 440 |
+
# kernel = torch.ones((1, 1, 5, 5), dtype=torch.float).cuda()
|
| 441 |
+
# # Number of erosion iterations
|
| 442 |
+
# iterations = 5
|
| 443 |
+
|
| 444 |
+
# # Perform iterative erosion
|
| 445 |
+
# for i in range(iterations):
|
| 446 |
+
# # Apply erosion using 2D convolution
|
| 447 |
+
# eroded_mask = F.conv2d(image_mask, kernel, padding=2)
|
| 448 |
+
# image_mask = (eroded_mask == kernel.sum()).float() # Update mask to eroded version
|
| 449 |
+
|
| 450 |
+
feature_point_cloud = get_rgbd_point_cloud(cameras[i], dino_feat_masked.to(device), depth_map=depth_image,mask=image_mask)#everthing on GPU
|
| 451 |
+
|
| 452 |
+
index = np.random.choice(feature_point_cloud.points_list()[0].shape[0], 4096, replace=True)
|
| 453 |
+
points = feature_point_cloud.points_list()[0].detach().cpu()[index,:]
|
| 454 |
+
colors = feature_point_cloud.features_list()[0].detach().cpu()[index,:]
|
| 455 |
+
# points = feature_point_cloud.points_list()[0].detach().cpu()[:,:]
|
| 456 |
+
# colors = feature_point_cloud.features_list()[0].detach().cpu()[:,:]
|
| 457 |
+
feature_point_cloud = torch.cat((points, colors), dim=1)
|
| 458 |
+
|
| 459 |
+
dino_feat_masked_list.append(dino_feat_masked_low.detach().cpu())
|
| 460 |
+
feature_point_cloud_list.append(feature_point_cloud)
|
| 461 |
+
feature_point_cloud = torch.cat(feature_point_cloud_list, dim=0)
|
| 462 |
+
dino_feat_masked = torch.cat(dino_feat_masked_list, dim=0)
|
| 463 |
+
return feature_point_cloud,dino_feat_masked, feature_point_cloud_list
|
| 464 |
+
|
| 465 |
+
def downsample_with_knn_feature_aggregation(feature_point_cloud,num_pts=1024,k_nearest_neighbors=100, instance_points=None):
|
| 466 |
+
#N_1, C_1 = 2048, 384 # Example number of points and features
|
| 467 |
+
num_points_to_sample = num_pts
|
| 468 |
+
k_nearest_neighbors = k_nearest_neighbors
|
| 469 |
+
|
| 470 |
+
# Example input pointcloud and features (N_1, C_1), where N_1 is the number of points and C_1 is the feature dimension
|
| 471 |
+
pointcloud = feature_point_cloud[None,:,:3].cuda(0) # Shape (1, N_1, 3) for 3D coordinates
|
| 472 |
+
features = feature_point_cloud[None,:,3:].cuda(0) # Shape (1, N_1, C_1) for features
|
| 473 |
+
|
| 474 |
+
# Step 1: FPS to downsample the points
|
| 475 |
+
# We use sample_farthest_points to select num_points_to_sample points
|
| 476 |
+
sampled_points, sampled_indices = sample_farthest_points(pointcloud, K=num_points_to_sample) # Shape: (1, 1024, 3), (1, 1024)
|
| 477 |
+
if instance_points is not None:
|
| 478 |
+
sampled_points = instance_points
|
| 479 |
+
|
| 480 |
+
# Step 2: KNN to find nearest neighbors
|
| 481 |
+
# Find the k nearest neighbors for each sampled point in the original pointcloud
|
| 482 |
+
dists, knn_indices, _ = knn_points(sampled_points, pointcloud, K=k_nearest_neighbors, return_nn=False)
|
| 483 |
+
|
| 484 |
+
# Step 3: Gather the features of the k-nearest neighbors using the knn indices
|
| 485 |
+
# Use knn_gather to get neighbor features for each sampled point
|
| 486 |
+
neighbor_features = knn_gather(features, knn_indices) # Shape: (1, 1024, k, C_1)
|
| 487 |
+
|
| 488 |
+
# Step 4: Aggregate features from the neighbors (e.g., by averaging)
|
| 489 |
+
#aggregated_features,_ = torch.max(neighbor_features,dim=-2) # Shape: (1, 1024, C_1)
|
| 490 |
+
aggregated_features = torch.mean(neighbor_features,dim=-2) # Shape: (1, 1024, C_1)
|
| 491 |
+
return sampled_points, aggregated_features
|
| 492 |
+
|
| 493 |
+
|
| 494 |
+
def vis_pca(feature):
|
| 495 |
+
n_components=3 # the first component is to seperate the object from the background
|
| 496 |
+
|
| 497 |
+
pca = sklearnPCA(n_components=n_components)
|
| 498 |
+
feature = pca.fit_transform(feature.detach().cpu().numpy())
|
| 499 |
+
for show_channel in range(n_components):
|
| 500 |
+
# min max normalize the feature map
|
| 501 |
+
feature[:, show_channel] = (feature[:, show_channel] - feature[:, show_channel].mean()) / (feature[:, show_channel].std()*10)
|
| 502 |
+
feature_resized = np.clip(feature[:,:]+0.5,0,1)
|
| 503 |
+
return feature_resized
|
| 504 |
+
|
| 505 |
+
def patch2pixel_feats(patch_features, original_size):
|
| 506 |
+
"""
|
| 507 |
+
修改版:自动根据 T(patch 数量)和原图比例推算 (Hp, Wp)
|
| 508 |
+
"""
|
| 509 |
+
H, W = original_size
|
| 510 |
+
B = patch_features.shape[0]
|
| 511 |
+
T = patch_features.shape[2]
|
| 512 |
+
C = patch_features.shape[3]
|
| 513 |
+
|
| 514 |
+
# ✅ 【修改1】自动寻找 (Hp, Wp),而不是用 sqrt(T)
|
| 515 |
+
aspect = H / W
|
| 516 |
+
best = None
|
| 517 |
+
for h in range(1, int(math.sqrt(T)) + 1):
|
| 518 |
+
if T % h == 0:
|
| 519 |
+
w = T // h
|
| 520 |
+
for hh, ww in [(h, w), (w, h)]:
|
| 521 |
+
score = abs((hh / ww) - aspect)
|
| 522 |
+
if best is None or score < best[2]:
|
| 523 |
+
best = (hh, ww, score)
|
| 524 |
+
Hp, Wp, _ = best # 比如 27, 25
|
| 525 |
+
|
| 526 |
+
# ✅ 【修改2】用 Hp, Wp 替代 num_patches
|
| 527 |
+
patch_features = patch_features.reshape(B, Hp, Wp, C)
|
| 528 |
+
|
| 529 |
+
# ✅ 【修改3】后面不变
|
| 530 |
+
patch_features = patch_features.permute(0, 3, 1, 2)
|
| 531 |
+
pixel_features = F.interpolate(
|
| 532 |
+
patch_features, size=(H, W), mode='bilinear', align_corners=False
|
| 533 |
+
)
|
| 534 |
+
pixel_features = pixel_features.squeeze().permute(1, 2, 0)
|
| 535 |
+
|
| 536 |
+
return pixel_features
|
| 537 |
+
|
| 538 |
+
def vis_pca_pixelwise(feature):
|
| 539 |
+
n_components = 4 # The number of PCA components to use
|
| 540 |
+
batch, feat_dim, height,width = feature.shape
|
| 541 |
+
|
| 542 |
+
# Reshape the feature to (num_pixels, feat_dim)
|
| 543 |
+
num_pixels = height * width
|
| 544 |
+
feature_reshaped = np.array(feature).transpose(0,2,3,1).reshape(-1, feat_dim)
|
| 545 |
+
|
| 546 |
+
|
| 547 |
+
# Apply PCA
|
| 548 |
+
pca = sklearnPCA(n_components=n_components)
|
| 549 |
+
feature_pca = pca.fit_transform(feature_reshaped)
|
| 550 |
+
|
| 551 |
+
# Min-max normalization for each component
|
| 552 |
+
# for show_channel in range(n_components):
|
| 553 |
+
# feature_pca[:, show_channel] = (feature_pca[:, show_channel] - feature_pca[:, show_channel].min()) / \
|
| 554 |
+
# (feature_pca[:, show_channel].max() - feature_pca[:, show_channel].min() + 1e-8) # Small epsilon to avoid division by zero
|
| 555 |
+
for show_channel in range(n_components):
|
| 556 |
+
feature_pca[:, show_channel] = (feature_pca[:, show_channel] - feature_pca[:, show_channel].mean()) / \
|
| 557 |
+
(feature_pca[:, show_channel].std()*10 + 1e-8) # Small epsilon to avoid division by zero
|
| 558 |
+
|
| 559 |
+
feature_pca = np.clip(feature_pca+0.5, 0, 1)
|
| 560 |
+
# Reshape the PCA result back to (height, width, n_components)
|
| 561 |
+
feature_resized = feature_pca.reshape(batch,height,width,n_components)[...,1:4]
|
| 562 |
+
return feature_resized
|
| 563 |
+
|
| 564 |
+
def normalize_mesh_verts(data):
|
| 565 |
+
# data [N, 3]
|
| 566 |
+
min_vals, _ = torch.min(data, dim=0)
|
| 567 |
+
max_vals, _ = torch.max(data, dim=0)
|
| 568 |
+
bbox_sizes = max_vals - min_vals
|
| 569 |
+
scale = torch.norm(bbox_sizes)
|
| 570 |
+
# print("Scale:", scale)
|
| 571 |
+
normalized_verts = verts / scale
|
| 572 |
+
return normalized_verts
|
| 573 |
+
|
| 574 |
+
def plot_pointclouds_with_color_mapping(pc1_f, pc2_f,pc1,pc2, query_points, similarity_threshold=None):
|
| 575 |
+
"""
|
| 576 |
+
Visualizes two 3D point clouds. The second point cloud (pc2) is color-mapped
|
| 577 |
+
using the 'viridis' colormap based on its similarity (proximity) to the sampled
|
| 578 |
+
query points in the first point cloud (pc1).
|
| 579 |
+
|
| 580 |
+
Parameters:
|
| 581 |
+
- pc1: np.ndarray of shape (N, 3), first point cloud #partial
|
| 582 |
+
- pc2: np.ndarray of shape (M, 3), second point cloud # global
|
| 583 |
+
- query_points: list of indices in pc1, representing the query points to compare.
|
| 584 |
+
- similarity_threshold: float, optional, threshold to cap the similarity distance.
|
| 585 |
+
"""
|
| 586 |
+
|
| 587 |
+
|
| 588 |
+
pc1_f = pc1_f / np.linalg.norm(pc1_f, axis=1)[:, None] # Normalize the features
|
| 589 |
+
pc2_f = pc2_f / np.linalg.norm(pc2_f, axis=1)[:, None] # Normalize the features
|
| 590 |
+
# Create a figure with subplots
|
| 591 |
+
fig = plt.figure(figsize=(12, 10))
|
| 592 |
+
num_query_points = len(query_points)
|
| 593 |
+
# Set limits and labels
|
| 594 |
+
size = pc2.max() - pc2.min()
|
| 595 |
+
# Plot the first point cloud in the first subplot
|
| 596 |
+
ax1 = fig.add_subplot(1, num_query_points + 1, 1, projection='3d')
|
| 597 |
+
ax1.scatter(pc2[:, 0], pc2[:, 1], pc2[:, 2], color='grey', label='Point Cloud 1 (Left)', alpha=0.1,s=10)
|
| 598 |
+
|
| 599 |
+
# Define a color list for each query point
|
| 600 |
+
query_colors = cm.tab10(np.linspace(0, 1, num_query_points)) # Use tab10 colormap for distinct colors
|
| 601 |
+
|
| 602 |
+
# Highlight query points in pc1 with different colors
|
| 603 |
+
for i, idx in enumerate(query_points):
|
| 604 |
+
ax1.scatter(pc1[idx, 0], pc1[idx, 1], pc1[idx, 2],
|
| 605 |
+
color=query_colors[i], s=100, edgecolor='k', label=f'Query Point {idx}')
|
| 606 |
+
|
| 607 |
+
ax1.set_title('Point Cloud 1 with Query Points')
|
| 608 |
+
ax1.set_xlabel('X')
|
| 609 |
+
ax1.set_ylabel('Y')
|
| 610 |
+
ax1.set_zlabel('Z')
|
| 611 |
+
ax1.set_xlim(-size / 1.4, size / 1.4)
|
| 612 |
+
ax1.set_ylim(-size / 1.4, size / 1.4)
|
| 613 |
+
ax1.set_zlim(-size / 1.4, size / 1.4)
|
| 614 |
+
ax1.view_init(elev=45, azim=-45)
|
| 615 |
+
ax1.grid(True)
|
| 616 |
+
ax1.legend()
|
| 617 |
+
|
| 618 |
+
# Plot the second point cloud in the subsequent subplots
|
| 619 |
+
for k in range(num_query_points):
|
| 620 |
+
|
| 621 |
+
ax = fig.add_subplot(1, num_query_points + 1, k + 2, projection='3d')
|
| 622 |
+
|
| 623 |
+
# Calculate distances between query points in pc1 and all points in pc2
|
| 624 |
+
similarity =(pc1_f[query_points[k]][None]@ pc2_f.T).reshape(-1) # (1, 3) x (M, 3) = (1, M)
|
| 625 |
+
# For each point in pc2, take the minimum distance to any query point
|
| 626 |
+
min_similarity = np.min(similarity, axis=0)
|
| 627 |
+
# Optionally cap the similarity distances to a threshold (to avoid extreme values)
|
| 628 |
+
similarity_threshold= 0.3
|
| 629 |
+
if similarity_threshold is not None:
|
| 630 |
+
similarity = np.clip(similarity, similarity_threshold,1)
|
| 631 |
+
# Normalize the distances to a range of 0 to 1 for colormap mapping
|
| 632 |
+
similarity = (similarity - np.min(similarity)) / (np.max(similarity) - np.min(similarity))
|
| 633 |
+
colors = cm.plasma(similarity)
|
| 634 |
+
|
| 635 |
+
# Plot the second point cloud with color mapping based on similarity
|
| 636 |
+
ax.scatter(pc2[:, 0], pc2[:, 1], pc2[:, 2], color=colors, s=15, alpha=1.0, label='Point Cloud 2 (Right)', edgecolor='k')
|
| 637 |
+
|
| 638 |
+
ax.set_xlim(-size / 1.4, size / 1.4)
|
| 639 |
+
ax.set_ylim(-size / 1.4, size / 1.4)
|
| 640 |
+
ax.set_zlim(-size / 1.4, size / 1.4)
|
| 641 |
+
ax.set_title(f'QP_{query_points[k]}')
|
| 642 |
+
ax.set_xlabel('X')
|
| 643 |
+
ax.set_ylabel('Y')
|
| 644 |
+
ax.set_zlabel('Z')
|
| 645 |
+
ax.view_init(elev=45, azim=-45)
|
| 646 |
+
ax.grid(True)
|
| 647 |
+
ax.legend()
|
| 648 |
+
|
| 649 |
+
# Show the plot
|
| 650 |
+
plt.tight_layout()
|
| 651 |
+
plt.show()
|
| 652 |
+
|
| 653 |
+
|
| 654 |
+
def plot_pointclouds_3d_with_copca_old(global_sem_pcd, partial_sem_pcd, global_pcd, partial_pcd):
|
| 655 |
+
"""
|
| 656 |
+
Visualizes two point clouds in 3D, coloring them based on their PCA components.
|
| 657 |
+
|
| 658 |
+
Parameters:
|
| 659 |
+
- global_pointcloud: numpy array of shape (N, D) for global point cloud.
|
| 660 |
+
- partial_pointcloud: numpy array of shape (M, D) for partial point cloud.
|
| 661 |
+
"""
|
| 662 |
+
|
| 663 |
+
|
| 664 |
+
n_components = 3
|
| 665 |
+
# Step 1: Perform PCA on both global and partial point clouds
|
| 666 |
+
sem_pca = PCA(n_components=n_components)
|
| 667 |
+
sem_pca = sem_pca.fit(global_sem_pcd) # shape (N+M, 3)
|
| 668 |
+
|
| 669 |
+
transformed_sem_pcd_list = [sem_pca.transform(pcd) for pcd in [global_sem_pcd,partial_sem_pcd]]
|
| 670 |
+
sem_pcd_pca = np.concatenate(transformed_sem_pcd_list,axis=0)
|
| 671 |
+
for show_channel in range(n_components):
|
| 672 |
+
sem_pcd_pca[:, show_channel] = (sem_pcd_pca[:, show_channel] - sem_pcd_pca[:, show_channel].mean()) / \
|
| 673 |
+
(sem_pcd_pca[:, show_channel].std()*5 + 1e-8) # Small epsilon to avoid division by zero
|
| 674 |
+
|
| 675 |
+
# sem_pcd_pca_min = sem_pcd_pca.min()
|
| 676 |
+
# sem_pcd_pca_max = sem_pcd_pca.max()
|
| 677 |
+
# sem_pcd_pca = (sem_pcd_pca- sem_pcd_pca_min) / (sem_pcd_pca_max - sem_pcd_pca_min) # Normalize to [0, 1]
|
| 678 |
+
|
| 679 |
+
sem_pcd_pca = np.clip(sem_pcd_pca[:,:]+0.5, 0, 1)
|
| 680 |
+
global_pca = sem_pcd_pca[:global_sem_pcd.shape[0]] # shape (N, 3)
|
| 681 |
+
partial_pca = sem_pcd_pca[-partial_sem_pcd.shape[0]:] # shape (M, 3)
|
| 682 |
+
|
| 683 |
+
# Step 2: Create a 3D scatter plot
|
| 684 |
+
fig = plt.figure(figsize=(12, 6))
|
| 685 |
+
ax = fig.add_subplot(121, projection='3d')
|
| 686 |
+
|
| 687 |
+
|
| 688 |
+
# Global point cloud
|
| 689 |
+
ax.scatter(global_pcd[:, 0], global_pcd[:, 1], global_pcd[:, 2],
|
| 690 |
+
c=global_pca, marker='o', s=100, alpha=1.0, label='Global Point Cloud')
|
| 691 |
+
|
| 692 |
+
# Set labels for each axis
|
| 693 |
+
# ax.set_xlabel('X axis')
|
| 694 |
+
# ax.set_ylabel('Y axis')
|
| 695 |
+
# ax.set_zlabel('Z axis')
|
| 696 |
+
ax.set_xlim(-0.5, 0.5)
|
| 697 |
+
ax.set_ylim(-0.5, 0.5)
|
| 698 |
+
ax.set_zlim(-0.5, 0.5)
|
| 699 |
+
|
| 700 |
+
ax1 = fig.add_subplot(122, projection='3d')
|
| 701 |
+
|
| 702 |
+
# Partial point cloud
|
| 703 |
+
ax1.scatter(partial_pcd[:, 0], partial_pcd[:, 1], partial_pcd[:, 2],
|
| 704 |
+
c=partial_pca, marker='o', s=100, alpha=1.0, label='Partial Point Cloud')
|
| 705 |
+
|
| 706 |
+
# ax1.scatter(global_pcd[:, 0], global_pcd[:, 1], global_pcd[:, 2],
|
| 707 |
+
# marker='o', s=10, alpha=0.1)
|
| 708 |
+
# Set labels for each axis
|
| 709 |
+
# ax1.set_xlabel('X axis')
|
| 710 |
+
# ax1.set_ylabel('Y axis')
|
| 711 |
+
# ax1.set_zlabel('Z axis')
|
| 712 |
+
|
| 713 |
+
|
| 714 |
+
ax1.set_xlim(-0.5, 0.5)
|
| 715 |
+
ax1.set_ylim(-0.5, 0.5)
|
| 716 |
+
ax1.set_zlim(-0.5, 0.5)
|
| 717 |
+
plt.tight_layout()
|
| 718 |
+
|
| 719 |
+
ax.view_init(120,-95)
|
| 720 |
+
ax1.view_init(120,-95)
|
| 721 |
+
|
| 722 |
+
|
| 723 |
+
ax.set_axis_off()
|
| 724 |
+
ax.set_facecolor((0, 0, 0, 0))
|
| 725 |
+
ax1.set_axis_off()
|
| 726 |
+
ax1.set_facecolor((0, 0, 0, 0))
|
| 727 |
+
|
| 728 |
+
plt.show()
|
| 729 |
+
|
| 730 |
+
|
| 731 |
+
def plot_pointclouds_3d_with_pca(global_sem_pcd, global_pcd):
|
| 732 |
+
"""
|
| 733 |
+
Visualizes two point clouds in 3D, coloring them based on their PCA components.
|
| 734 |
+
|
| 735 |
+
Parameters:
|
| 736 |
+
- global_pointcloud: numpy array of shape (N, D) for global point cloud.
|
| 737 |
+
- partial_pointcloud: numpy array of shape (M, D) for partial point cloud.
|
| 738 |
+
"""
|
| 739 |
+
#sem_pcd = np.concatenate((global_sem_pcd,partial_sem_pcd), axis=0) # shape (N+M, D)
|
| 740 |
+
|
| 741 |
+
# Step 1: Perform PCA on both global and partial point clouds
|
| 742 |
+
sem_pca = PCA(n_components=3)
|
| 743 |
+
sem_pcd_pca = sem_pca.fit_transform(global_sem_pcd) # shape (N+M, 3)
|
| 744 |
+
|
| 745 |
+
for i in range(3): # Iterate over each component (3 in total for RGB)
|
| 746 |
+
sem_pcd_pca_mean = sem_pcd_pca[:, i].mean()
|
| 747 |
+
sem_pcd_pca_std = sem_pcd_pca[:, i].std()
|
| 748 |
+
sem_pcd_pca[:, i] = (sem_pcd_pca[:, i] - sem_pcd_pca_mean) / (sem_pcd_pca_std*5+1e-8) # Normalize to [0, 1]
|
| 749 |
+
|
| 750 |
+
|
| 751 |
+
global_pca = np.clip(sem_pcd_pca+0.5,0,1)
|
| 752 |
+
# scatter plot
|
| 753 |
+
fig = plt.figure(figsize=(6, 6))
|
| 754 |
+
ax = fig.add_subplot(111, projection='3d')
|
| 755 |
+
|
| 756 |
+
# Global point cloud
|
| 757 |
+
ax.scatter(global_pcd[:, 0], global_pcd[:, 1], global_pcd[:, 2],
|
| 758 |
+
c=global_pca, marker='o', s=50, alpha=1.0, label='Global Point Cloud')
|
| 759 |
+
|
| 760 |
+
# Remove axes and background
|
| 761 |
+
ax.set_axis_off()
|
| 762 |
+
|
| 763 |
+
# Set background color to none
|
| 764 |
+
ax.set_facecolor((0, 0, 0, 0))
|
| 765 |
+
# # Set labels for each axis
|
| 766 |
+
# ax.set_xlabel('X axis')
|
| 767 |
+
# ax.set_ylabel('Y axis')
|
| 768 |
+
# ax.set_zlabel('Z axis')
|
| 769 |
+
ax.set_xlim(-0.5, 0.5)
|
| 770 |
+
ax.set_ylim(-0.5, 0.5)
|
| 771 |
+
ax.set_zlim(-0.5, 0.5)
|
| 772 |
+
|
| 773 |
+
ax.view_init(-73,102)
|
| 774 |
+
|
| 775 |
+
return fig
|
| 776 |
+
|
| 777 |
+
|
| 778 |
+
def plot_pointclouds_3d_with_copca(global_sem_pcd_list, global_pcd_list,co_pca=True):
|
| 779 |
+
"""
|
| 780 |
+
Visualizes multiple point clouds in 3D, each in a separate subplot, after applying CoPCA.
|
| 781 |
+
Coloring them based on their PCA components.
|
| 782 |
+
|
| 783 |
+
Parameters:
|
| 784 |
+
- global_sem_pcd_list: list of numpy arrays for semantic point clouds (one per object).
|
| 785 |
+
- global_pcd_list: list of numpy arrays for global point clouds (one per object).
|
| 786 |
+
"""
|
| 787 |
+
num_pcds = len(global_sem_pcd_list) # Number of point clouds
|
| 788 |
+
# Step 1: Perform CoPCA (Common PCA) on the semantic point clouds
|
| 789 |
+
# Concatenate all point clouds to perform common PCA
|
| 790 |
+
if co_pca:
|
| 791 |
+
concatenated_pcds = np.concatenate(global_sem_pcd_list, axis=0) # shape (N_total, D)
|
| 792 |
+
copca = PCA(n_components=3, random_state=0)
|
| 793 |
+
copca.fit(concatenated_pcds[:1024]) # Fit PCA on all point clouds together
|
| 794 |
+
transformed_sem_pcd_list = [copca.transform(pcd) for pcd in global_sem_pcd_list]
|
| 795 |
+
|
| 796 |
+
|
| 797 |
+
signs = np.sign(np.sum(transformed_sem_pcd_list[0], axis=0))
|
| 798 |
+
# Post-process to ensure consistent orientation of PCA components
|
| 799 |
+
for i, transformed_pcd in enumerate(transformed_sem_pcd_list):
|
| 800 |
+
# For each component (column), align sign based on the sum of values in the column
|
| 801 |
+
transformed_sem_pcd_list[i] = transformed_pcd * signs
|
| 802 |
+
else:
|
| 803 |
+
copca = PCA(n_components=3)
|
| 804 |
+
transformed_sem_pcd_list = [copca.fit_transform(pcd) for pcd in global_sem_pcd_list]
|
| 805 |
+
# Post-process to ensure consistent orientation of PCA components
|
| 806 |
+
for i, transformed_pcd in enumerate(transformed_sem_pcd_list):
|
| 807 |
+
signs = np.sign(np.sum(transformed_pcd, axis=0))
|
| 808 |
+
# For each component (column), align sign based on the sum of values in the column
|
| 809 |
+
transformed_sem_pcd_list[i] = transformed_pcd * signs
|
| 810 |
+
|
| 811 |
+
|
| 812 |
+
|
| 813 |
+
# Create a figure with subplots arranged in a grid (based on number of point clouds)
|
| 814 |
+
fig = plt.figure(figsize=(6 * num_pcds, 6)) # Adjust figure size based on the number of subplots
|
| 815 |
+
|
| 816 |
+
# Loop over the point clouds
|
| 817 |
+
for idx, (sem_pcd_pca, global_pcd) in enumerate(zip(transformed_sem_pcd_list, global_pcd_list)):
|
| 818 |
+
ax = fig.add_subplot(1, num_pcds, idx + 1, projection='3d')
|
| 819 |
+
|
| 820 |
+
# Step 2: Normalize the PCA-transformed data to use as colors
|
| 821 |
+
for i in range(3): # Iterate over each component (3 in total for RGB)
|
| 822 |
+
pca_mean = sem_pcd_pca[:, i].mean()
|
| 823 |
+
pca_std = sem_pcd_pca[:, i].std()
|
| 824 |
+
sem_pcd_pca[:, i] = (sem_pcd_pca[:, i] - pca_mean) / (pca_std * 5 + 1e-8) # Normalize
|
| 825 |
+
|
| 826 |
+
global_pca_colors = np.clip(sem_pcd_pca + 0.5, 0, 1) # Map to [0, 1] for RGB
|
| 827 |
+
|
| 828 |
+
# Scatter plot for this point cloud in the current subplot
|
| 829 |
+
ax.scatter(global_pcd[:, 0], global_pcd[:, 1], global_pcd[:, 2],
|
| 830 |
+
c=global_pca_colors, marker='o', s=10, alpha=1.0)
|
| 831 |
+
|
| 832 |
+
# Remove axes and background
|
| 833 |
+
ax.set_axis_off()
|
| 834 |
+
ax.set_facecolor((0, 0, 0, 0))
|
| 835 |
+
|
| 836 |
+
# Set axis limits for each subplot
|
| 837 |
+
ax.set_xlim(-0.5, 0.5)
|
| 838 |
+
ax.set_ylim(-0.5, 0.5)
|
| 839 |
+
ax.set_zlim(-0.5, 0.5)
|
| 840 |
+
|
| 841 |
+
# Set view angle
|
| 842 |
+
ax.view_init(-73, 102)
|
| 843 |
+
|
| 844 |
+
# Adjust spacing between subplots
|
| 845 |
+
plt.tight_layout()
|
| 846 |
+
|
| 847 |
+
return fig
|
| 848 |
+
|
| 849 |
+
|
| 850 |
+
|
| 851 |
+
def unnormalize(x):
|
| 852 |
+
# x.shape : [H,W,3]
|
| 853 |
+
mean = np.array([0.485, 0.456, 0.406])
|
| 854 |
+
std = np.array([0.229, 0.224, 0.225])
|
| 855 |
+
return x * std + mean
|
| 856 |
+
|
| 857 |
+
def parse_object_name(folder_name):
|
| 858 |
+
"""
|
| 859 |
+
Parse folder name to extract category and instance name.
|
| 860 |
+
|
| 861 |
+
Examples:
|
| 862 |
+
google_scan-backpack_0288 -> category: backpack, instance: backpack_0288
|
| 863 |
+
omniobject3d-hammer_001 -> category: hammer, instance: hammer_001
|
| 864 |
+
|
| 865 |
+
Args:
|
| 866 |
+
folder_name: Name of the folder containing the mesh
|
| 867 |
+
|
| 868 |
+
Returns:
|
| 869 |
+
category: Object category
|
| 870 |
+
instance_name: Full instance name (category_id)
|
| 871 |
+
"""
|
| 872 |
+
# Split by '-' to remove prefix (google_scan, omniobject3d, etc.)
|
| 873 |
+
if '-' in folder_name:
|
| 874 |
+
parts = folder_name.split('-', 1)
|
| 875 |
+
object_part = parts[1]
|
| 876 |
+
else:
|
| 877 |
+
object_part = folder_name
|
| 878 |
+
|
| 879 |
+
# Split by '_' to get category and id
|
| 880 |
+
parts = object_part.rsplit('_', 1)
|
| 881 |
+
|
| 882 |
+
if len(parts) == 2:
|
| 883 |
+
category = parts[0]
|
| 884 |
+
object_id = parts[1]
|
| 885 |
+
instance_name = f"{category}_{object_id}"
|
| 886 |
+
else:
|
| 887 |
+
# Fallback if no underscore found
|
| 888 |
+
category = object_part
|
| 889 |
+
instance_name = object_part
|
| 890 |
+
|
| 891 |
+
return category, instance_name
|
| 892 |
+
|
| 893 |
+
def find_original_folder(instance_name, dirlist):
|
| 894 |
+
"""
|
| 895 |
+
Find the original folder name that corresponds to the given instance name.
|
| 896 |
+
|
| 897 |
+
Args:
|
| 898 |
+
instance_name (str): e.g. 'backpack_0288'
|
| 899 |
+
dirlist (list[str]): list of all folder names
|
| 900 |
+
|
| 901 |
+
Returns:
|
| 902 |
+
str or None: matching folder name (e.g. 'google_scan-backpack_0288') or None if not found
|
| 903 |
+
"""
|
| 904 |
+
for folder in dirlist:
|
| 905 |
+
if instance_name in folder:
|
| 906 |
+
return folder
|
| 907 |
+
return None
|
| 908 |
+
|
| 909 |
+
def load_ply_as_obj(ply_path, device="cpu"):
|
| 910 |
+
"""
|
| 911 |
+
Return (verts, faces, aux) in a PyTorch3D-OBJ-like shape for .ply files.
|
| 912 |
+
|
| 913 |
+
- faces: .verts_idx (F,3) long, .normals_idx None, .textures_idx (F,3) or None
|
| 914 |
+
- aux: .verts_uvs (V,2) float or None,
|
| 915 |
+
.normals (V,3) float or None,
|
| 916 |
+
.texture_images {material_name: img_tensor(H,W,3) in [0,1]},
|
| 917 |
+
.materials [material_name, ...],
|
| 918 |
+
.material_colors None
|
| 919 |
+
"""
|
| 920 |
+
ply_path = Path(ply_path)
|
| 921 |
+
ply = PlyData.read(str(ply_path))
|
| 922 |
+
|
| 923 |
+
# ---- vertices ----
|
| 924 |
+
v = ply["vertex"].data # structured ndarray
|
| 925 |
+
verts_np = np.column_stack([v["x"], v["y"], v["z"]]).astype(np.float32)
|
| 926 |
+
verts = torch.from_numpy(verts_np).to(device)
|
| 927 |
+
|
| 928 |
+
# ---- faces (triangles only) ----
|
| 929 |
+
faces_raw = ply["face"].data["vertex_indices"] # array of python lists
|
| 930 |
+
tri = [idx for idx in faces_raw if len(idx) == 3]
|
| 931 |
+
faces_idx = torch.as_tensor(np.asarray(tri, dtype=np.int64), device=device)
|
| 932 |
+
|
| 933 |
+
faces = SimpleNamespace()
|
| 934 |
+
faces.verts_idx = faces_idx
|
| 935 |
+
faces.normals_idx = None
|
| 936 |
+
faces.textures_idx = None # will mirror verts_idx if UVs exist
|
| 937 |
+
|
| 938 |
+
# ---- aux ----
|
| 939 |
+
aux = SimpleNamespace()
|
| 940 |
+
names = v.dtype.names
|
| 941 |
+
|
| 942 |
+
# per-vertex normals (optional)
|
| 943 |
+
if {"nx", "ny", "nz"}.issubset(names):
|
| 944 |
+
normals_np = np.column_stack([v["nx"], v["ny"], v["nz"]]).astype(np.float32)
|
| 945 |
+
aux.normals = torch.from_numpy(normals_np).to(device)
|
| 946 |
+
else:
|
| 947 |
+
aux.normals = None
|
| 948 |
+
|
| 949 |
+
# per-vertex UVs (optional)
|
| 950 |
+
if {"texture_u", "texture_v"}.issubset(names):
|
| 951 |
+
uvs_np = np.column_stack([v["texture_u"], v["texture_v"]]).astype(np.float32)
|
| 952 |
+
aux.verts_uvs = torch.from_numpy(uvs_np).to(device)
|
| 953 |
+
faces.textures_idx = faces.verts_idx.clone()
|
| 954 |
+
else:
|
| 955 |
+
aux.verts_uvs = None
|
| 956 |
+
|
| 957 |
+
# texture image(s) from header comment like: "comment TextureFile obj_000400.png"
|
| 958 |
+
texture_images = {}
|
| 959 |
+
materials = []
|
| 960 |
+
|
| 961 |
+
for c in getattr(ply, "comments", []):
|
| 962 |
+
c = c.strip()
|
| 963 |
+
if c.lower().startswith("texturefile"):
|
| 964 |
+
# e.g. "TextureFile obj_000400.png"
|
| 965 |
+
parts = c.split(None, 1)
|
| 966 |
+
if len(parts) == 2:
|
| 967 |
+
tex_name = parts[1].strip()
|
| 968 |
+
tex_path = (ply_path.parent / tex_name)
|
| 969 |
+
if tex_path.exists():
|
| 970 |
+
try:
|
| 971 |
+
img = Image.open(tex_path).convert("RGB")
|
| 972 |
+
arr = np.asarray(img, dtype=np.float32) / 255.0 # H,W,3
|
| 973 |
+
texture_images["default"] = torch.from_numpy(arr) # dict value is tensor
|
| 974 |
+
materials.append("default")
|
| 975 |
+
except Exception:
|
| 976 |
+
pass # if unreadable, just skip
|
| 977 |
+
|
| 978 |
+
aux.texture_images = texture_images # DICT, not list
|
| 979 |
+
aux.materials = materials # keep order aligned with dict keys
|
| 980 |
+
aux.material_colors = None
|
| 981 |
+
|
| 982 |
+
return verts, faces, aux
|
| 983 |
+
|
| 984 |
+
def load_models_info(models_info_path):
|
| 985 |
+
"""
|
| 986 |
+
Build mapping: index(int) -> (category:str, instance:str)
|
| 987 |
+
|
| 988 |
+
Rules:
|
| 989 |
+
- "clip/002/link1" -> category="clip-link1", instance="002"
|
| 990 |
+
- "bottle/003" -> category="bottle", instance="003"
|
| 991 |
+
- "hammer" -> category="hammer", instance="unknown"
|
| 992 |
+
Fallbacks:
|
| 993 |
+
- If 3+ segments but the 2nd isn't purely digits, we pick the first all-digit token as instance.
|
| 994 |
+
- If no digit token found, instance="unknown".
|
| 995 |
+
"""
|
| 996 |
+
with open(models_info_path, "r") as f:
|
| 997 |
+
data = json.load(f)
|
| 998 |
+
|
| 999 |
+
def is_digits(s: str) -> bool:
|
| 1000 |
+
return re.fullmatch(r"\d+", s) is not None
|
| 1001 |
+
|
| 1002 |
+
mapping = {}
|
| 1003 |
+
for k, v in data.items():
|
| 1004 |
+
# Keys in JSON might be "0".."1260" (str) or int.
|
| 1005 |
+
try:
|
| 1006 |
+
idx = int(k)
|
| 1007 |
+
except Exception:
|
| 1008 |
+
continue
|
| 1009 |
+
|
| 1010 |
+
identifier = v.get("identifier", "")
|
| 1011 |
+
if "/" in identifier:
|
| 1012 |
+
identifier = (v.get("identifier") or "").strip()
|
| 1013 |
+
parts = [p for p in identifier.split('/') if p]
|
| 1014 |
+
if len(parts) == 3:
|
| 1015 |
+
# first + last for category, middle should be the numeric id
|
| 1016 |
+
cat_first, cat_last = parts[0], parts[-1]
|
| 1017 |
+
category = f"{cat_first}-{cat_last}"
|
| 1018 |
+
mid = parts[1]
|
| 1019 |
+
if is_digits(mid):
|
| 1020 |
+
instance = mid
|
| 1021 |
+
else:
|
| 1022 |
+
instance = "unknown"
|
| 1023 |
+
elif len(parts) == 2:
|
| 1024 |
+
category = parts[0]
|
| 1025 |
+
if is_digits(parts[1]):
|
| 1026 |
+
instance = parts[1]
|
| 1027 |
+
else:
|
| 1028 |
+
instance = "unknown"
|
| 1029 |
+
mapping[idx] = (category, instance)
|
| 1030 |
+
else:
|
| 1031 |
+
# Fallback: whole identifier as category, instance unknown
|
| 1032 |
+
mapping[idx] = (identifier, "unknown")
|
| 1033 |
+
return mapping
|
| 1034 |
+
|
| 1035 |
+
def load_trans2canon(json_path):
|
| 1036 |
+
"""
|
| 1037 |
+
Load pace_convert.json and return a mapping:
|
| 1038 |
+
name(str) -> 4x4 numpy array
|
| 1039 |
+
Expects top-level key 'trans2canon'.
|
| 1040 |
+
"""
|
| 1041 |
+
with open(json_path, 'r') as f:
|
| 1042 |
+
data = json.load(f)
|
| 1043 |
+
tdict = data.get("trans2canon", {})
|
| 1044 |
+
out = {}
|
| 1045 |
+
for k, v in tdict.items():
|
| 1046 |
+
M = np.asarray(v, dtype=float)
|
| 1047 |
+
if M.shape == (3, 3):
|
| 1048 |
+
out[k] = M
|
| 1049 |
+
else:
|
| 1050 |
+
raise ValueError(f"trans2canon[{k}] is not 3x3, got {M.shape}")
|
| 1051 |
+
return out
|
| 1052 |
+
|
| 1053 |
+
def lookup_transform(category, trans_map):
|
| 1054 |
+
"""
|
| 1055 |
+
Try several name variants to find a transform for this category.
|
| 1056 |
+
Returns 4x4 np.ndarray if found, else None.
|
| 1057 |
+
"""
|
| 1058 |
+
if category in trans_map:
|
| 1059 |
+
return trans_map[category]
|
| 1060 |
+
cat_safe = category.strip().replace(" ", "_")
|
| 1061 |
+
cat_safe = cat_safe.replace("-", "/")
|
| 1062 |
+
if cat_safe in trans_map:
|
| 1063 |
+
return trans_map[cat_safe]
|
| 1064 |
+
cat_lower = category.lower()
|
| 1065 |
+
if cat_lower in trans_map:
|
| 1066 |
+
return trans_map[cat_lower]
|
| 1067 |
+
cat_lower_safe = cat_lower.replace(" ", "_")
|
| 1068 |
+
return trans_map.get(cat_lower_safe, None)
|
| 1069 |
+
|
| 1070 |
+
def extract_index_from_fname(path: Path):
|
| 1071 |
+
"""
|
| 1072 |
+
From 'obj_000123.ply' -> 123 (int).
|
| 1073 |
+
Works with any digits after 'obj_'.
|
| 1074 |
+
"""
|
| 1075 |
+
m = re.match(r"obj_(\d+)\.", path.name)
|
| 1076 |
+
if not m:
|
| 1077 |
+
return None
|
| 1078 |
+
return int(m.group(1))
|
| 1079 |
+
|
| 1080 |
+
def load_ply_with_rotation(ply_path, R=None, device="cpu"):
|
| 1081 |
+
"""
|
| 1082 |
+
Load a .ply mesh and optionally apply a 3x3 rotation matrix R.
|
| 1083 |
+
Returns (verts, faces, aux) in PyTorch3D-like format.
|
| 1084 |
+
|
| 1085 |
+
- ply_path: str or Path to the .ply file
|
| 1086 |
+
- R: 3x3 rotation tensor or ndarray (optional)
|
| 1087 |
+
- device: CPU or CUDA
|
| 1088 |
+
"""
|
| 1089 |
+
# --- 1. Load mesh using your existing loader ---
|
| 1090 |
+
verts, faces, aux = load_ply_as_obj(ply_path, device=device)
|
| 1091 |
+
|
| 1092 |
+
# --- 2. Apply rotation if provided ---
|
| 1093 |
+
if R is not None:
|
| 1094 |
+
if not torch.is_tensor(R):
|
| 1095 |
+
R = torch.as_tensor(R, dtype=torch.float32)
|
| 1096 |
+
R = R.to(device).float()
|
| 1097 |
+
|
| 1098 |
+
# v' = v @ R^T (if R is column-major, which is the usual math convention)
|
| 1099 |
+
verts = verts @ R.T
|
| 1100 |
+
|
| 1101 |
+
if getattr(aux, "normals", None) is not None:
|
| 1102 |
+
aux.normals = aux.normals @ R.T
|
| 1103 |
+
aux.normals = torch.nn.functional.normalize(aux.normals, dim=1)
|
| 1104 |
+
|
| 1105 |
+
# --- 3. Return transformed mesh ---
|
| 1106 |
+
return verts, faces, aux
|
| 1107 |
+
|
| 1108 |
+
from custom_utils.housecat6d_dataset import HouseCat6DTrainingDataset
|
| 1109 |
+
# trainset = HouseCat6DTrainingDataset(image_size=420, sample_num=1024,data_dir='/media/hyunjun/NewDisk1/weihang/HouseCat6D')
|
| 1110 |
+
|
| 1111 |
+
vis = True
|
| 1112 |
+
device = "cuda"
|
| 1113 |
+
|
| 1114 |
+
cat = 'glass'
|
| 1115 |
+
#cat_list = ['bottle','box','can','cup','cutlery','remote','shoe','tube','teapot']
|
| 1116 |
+
#cat_list = ['bottle']
|
| 1117 |
+
|
| 1118 |
+
|
| 1119 |
+
#cat_list = ['teapot']
|
| 1120 |
+
cat_list = ['bottle','box','can','cup','cutlery','glass','remote','shoe','tube','teapot']
|
| 1121 |
+
sem_global_list = []
|
| 1122 |
+
sem_global_pcd_list = []
|
| 1123 |
+
|
| 1124 |
+
save_dir = './wlcop'
|
| 1125 |
+
if False:
|
| 1126 |
+
for cat in cat_list:
|
| 1127 |
+
sem_global_list = []
|
| 1128 |
+
sem_global_pcd_list = []
|
| 1129 |
+
with open(f'/home/xyz/anything6d_project/Datasets/housecat_{cat}/raw/housecat1_train.txt', 'r') as f:
|
| 1130 |
+
instances = [line.strip() for line in f.readlines()]
|
| 1131 |
+
|
| 1132 |
+
print(instances)
|
| 1133 |
+
|
| 1134 |
+
# Load the mean shape point cloud
|
| 1135 |
+
meanshape_path = f'/home/xyz/anything6d_project/Sem-GCE-AG-Pose/saved_pcd/{cat}/mean_shape/mean_shape_pcd_1.txt'
|
| 1136 |
+
meanshape_pcd_np = np.loadtxt(meanshape_path)
|
| 1137 |
+
meanshape_pcd_tensor = torch.from_numpy(meanshape_pcd_np)
|
| 1138 |
+
M = meanshape_pcd_tensor.shape[0]
|
| 1139 |
+
meanshape_points = meanshape_pcd_tensor.view(1, M, 3).float()
|
| 1140 |
+
average_aggregated_features = torch.load(f'{save_dir}/sem_cat_pcd_tex/{cat}_dino_feature.pt')
|
| 1141 |
+
sem_global_pcd_list.append(meanshape_points[0])
|
| 1142 |
+
sem_global_list.append(average_aggregated_features[0].detach().cpu())
|
| 1143 |
+
#fig =plot_pointclouds_3d_with_pca(average_aggregated_features[0].detach().cpu(),meanshape_points[0])
|
| 1144 |
+
#fig.savefig('test.png')
|
| 1145 |
+
for j,instance in enumerate(instances):
|
| 1146 |
+
|
| 1147 |
+
|
| 1148 |
+
print("Processing", instance)
|
| 1149 |
+
obj_path = f'/media/xyz/data/HouseCat6D/obj_models_small_size_final/{cat}/{instance}.obj'
|
| 1150 |
+
instance_pcd_path = f'/home/xyz/anything6d_project/Sem-GCE-AG-Pose/saved_pcd/{cat}/test/{instance}.txt'
|
| 1151 |
+
|
| 1152 |
+
# Load the instance point cloud
|
| 1153 |
+
instance_pcd_np = np.loadtxt(instance_pcd_path)
|
| 1154 |
+
instance_pcd_tensor = torch.from_numpy(instance_pcd_np)
|
| 1155 |
+
N = instance_pcd_tensor.shape[0]
|
| 1156 |
+
instance_points = instance_pcd_tensor.view(1, N, 3).float()
|
| 1157 |
+
try:
|
| 1158 |
+
aggregated_features = torch.load(f'{save_dir}/saved_dino_pcd_tex/{cat}/{instance}_dino_feature.pt')
|
| 1159 |
+
except:
|
| 1160 |
+
continue
|
| 1161 |
+
# plot_pointclouds_3d_with_pca(aggregated_features[0].detach().cpu(),
|
| 1162 |
+
# instance_points[0])
|
| 1163 |
+
sem_global_pcd_list.append(instance_points[0])
|
| 1164 |
+
sem_global_list.append(aggregated_features[0].detach().cpu())
|
| 1165 |
+
if j>6:
|
| 1166 |
+
break
|
| 1167 |
+
|
| 1168 |
+
plot_pointclouds_3d_with_copca(sem_global_list,sem_global_pcd_list,co_pca=True)
|
| 1169 |
+
plt.show()
|
| 1170 |
+
plt.close()
|
| 1171 |
+
a
|
| 1172 |
+
|
| 1173 |
+
|
| 1174 |
+
# model_dict={'small':'dinov2_vits14',
|
| 1175 |
+
# 'base':'dinov2_vitb14',
|
| 1176 |
+
# 'large':'dinov2_vitl14',
|
| 1177 |
+
# 'giant':'dinov2_vitg14'}
|
| 1178 |
+
# extractor = ViTExtractor(model_dict['small'],14)
|
| 1179 |
+
# extractor.model = extractor.model.cuda(0) # the stride of first conv control outputs resolution
|
| 1180 |
+
|
| 1181 |
+
# TODO: Change extractor model to dinov3
|
| 1182 |
+
# 1) Build a ViT-S/16 backbone from timm (shape-compatible with your hooks)
|
| 1183 |
+
extractor = DINOv3ExtractorAdapter(
|
| 1184 |
+
model_id="facebook/dinov3-vits16-pretrain-lvd1689m", # ViT-S/16
|
| 1185 |
+
device="cuda"
|
| 1186 |
+
)
|
| 1187 |
+
extractor.model = extractor.model.cuda(0)
|
| 1188 |
+
# End TODO
|
| 1189 |
+
|
| 1190 |
+
# --- 加载元数据 ---
|
| 1191 |
+
metadata_path = os.path.join("/media/hyunjun/NewDisk1/Datasets/wlcop/raw", "metadata.json")
|
| 1192 |
+
if not os.path.exists(metadata_path):
|
| 1193 |
+
raise FileNotFoundError("metadata.json not found. Please run create_metadata.py first.")
|
| 1194 |
+
with open(metadata_path, "r") as f:
|
| 1195 |
+
metadata_dict = json.load(f)
|
| 1196 |
+
# --- 构建有序的路径列表 (self.all_paths),这部分保持不变 ---
|
| 1197 |
+
path_to_idx = {path: int(index) for index, path in metadata_dict.items()}
|
| 1198 |
+
|
| 1199 |
+
|
| 1200 |
+
# load mean shape
|
| 1201 |
+
meanshap_path = "/media/hyunjun/NewDisk1/weihang/deep-linear-shapes/runs/wlcop173_supervisedK173_Affine_3/last_epoch_linearshape_model.pkl"
|
| 1202 |
+
# obj = torch.load(meanshap_path, map_location="cpu", weights_only=False)
|
| 1203 |
+
with open(meanshap_path, "rb") as f:
|
| 1204 |
+
pickle_data = pickle.load(f)
|
| 1205 |
+
# Convert to tensor dictionary
|
| 1206 |
+
id2meanshape_pcd_tensor = {
|
| 1207 |
+
i: torch.tensor(v["pos"]) for i, v in pickle_data.items() if v["pos"] is not None
|
| 1208 |
+
}
|
| 1209 |
+
|
| 1210 |
+
|
| 1211 |
+
# load id to name mapping
|
| 1212 |
+
shape_file = "/media/hyunjun/NewDisk1/Datasets/wlcop/raw/wlcop173_shape_names.txt"
|
| 1213 |
+
with open(shape_file, "r") as f:
|
| 1214 |
+
id2name = {i: line.strip() for i, line in enumerate(f) if line.strip()}
|
| 1215 |
+
|
| 1216 |
+
cat_list = [name for i, name in id2name.items() if name]
|
| 1217 |
+
|
| 1218 |
+
|
| 1219 |
+
# load source dir list of omni6d and pace
|
| 1220 |
+
omni6d_source_dir = "/media/hyunjun/NewDisk1/Omni6DPoseAPI/data/Omni6DPose/PAM/object_meshes"
|
| 1221 |
+
pace_source_dir = "/media/hyunjun/4ED38B1B5AFB74D5/PACE/models"
|
| 1222 |
+
|
| 1223 |
+
omni6d_dirlist = [
|
| 1224 |
+
os.path.join(omni6d_source_dir, d)
|
| 1225 |
+
for d in os.listdir(omni6d_source_dir)
|
| 1226 |
+
if os.path.isdir(os.path.join(omni6d_source_dir, d))
|
| 1227 |
+
]
|
| 1228 |
+
|
| 1229 |
+
pace_dirlist = [
|
| 1230 |
+
os.path.join(pace_source_dir, d)
|
| 1231 |
+
for d in os.listdir(pace_source_dir)
|
| 1232 |
+
]
|
| 1233 |
+
|
| 1234 |
+
# load the transformation matrix from pace to omni6d
|
| 1235 |
+
models_info_path = "/media/hyunjun/4ED38B1B5AFB74D5/PACE/models/models_info.json"
|
| 1236 |
+
id_map = load_models_info(models_info_path)
|
| 1237 |
+
trans_map = load_trans2canon("/media/hyunjun/NewDisk1/Datasets/pace_convert.json") # adjust path
|
| 1238 |
+
|
| 1239 |
+
#TODO: if condition for tex rendering
|
| 1240 |
+
for idx, cat in enumerate(cat_list):
|
| 1241 |
+
|
| 1242 |
+
if cat != 'drawing':
|
| 1243 |
+
continue
|
| 1244 |
+
|
| 1245 |
+
instances = [path for path in path_to_idx.keys() if cat == path.split('/')[-2]]
|
| 1246 |
+
|
| 1247 |
+
print(instances)
|
| 1248 |
+
|
| 1249 |
+
aggregated_features_list = [] # N * [1, 1024, 384]
|
| 1250 |
+
# Load the mean shape point cloud
|
| 1251 |
+
meanshape_pcd_tensor = id2meanshape_pcd_tensor[idx]
|
| 1252 |
+
M = meanshape_pcd_tensor.shape[0]
|
| 1253 |
+
meanshape_points = meanshape_pcd_tensor.view(1, M, 3).float().cuda(0)
|
| 1254 |
+
|
| 1255 |
+
|
| 1256 |
+
for j, instance in enumerate(instances):
|
| 1257 |
+
# if instance != 'bottle-85_alcool':
|
| 1258 |
+
# continue
|
| 1259 |
+
print("Processing", instance)
|
| 1260 |
+
instance_name = instance.split('/')[-1].replace('.txt','')
|
| 1261 |
+
# quickly check if the instance has been processed
|
| 1262 |
+
target_vis_file = f'{save_dir}/{cat}_rgb_dino/{instance_name}_dino.png'
|
| 1263 |
+
if os.path.exists(target_vis_file):
|
| 1264 |
+
aggregated_features_list.append(torch.load(f'{save_dir}/saved_dino_pcd_tex/{cat}/{instance_name}_dino_feature.pt'))
|
| 1265 |
+
# print(f"Skipping '{instance}', file already exists at: {target_vis_file}")
|
| 1266 |
+
continue # continue 会立即结束本次循环,进入下一次循环
|
| 1267 |
+
|
| 1268 |
+
obj_path = None # pcd file like .txt or .ply
|
| 1269 |
+
if "obj_" in instance.split('/')[-1]:
|
| 1270 |
+
name = instance.split('/')[-1].replace('.txt','.ply')
|
| 1271 |
+
obj_path = find_original_folder(name, pace_dirlist)
|
| 1272 |
+
else:
|
| 1273 |
+
name = instance.split('/')[-1].replace('.txt','')
|
| 1274 |
+
obj_path_base = find_original_folder(name, omni6d_dirlist)
|
| 1275 |
+
obj_path_base = Path(obj_path_base)
|
| 1276 |
+
obj_path = obj_path_base / 'Aligned.obj'
|
| 1277 |
+
if os.path.exists(obj_path):
|
| 1278 |
+
obj_path = os.path.join(omni6d_source_dir, obj_path)
|
| 1279 |
+
else:
|
| 1280 |
+
obj_path = list(obj_path_base.glob('*.obj'))[0]
|
| 1281 |
+
# obj_path = f'/media/hyunjun/NewDisk1/Datasets/wlcop/raw/{cat}/{instance}.obj'
|
| 1282 |
+
# instance_pcd_path = f'/media/hyunjun/NewDisk1/Datasets/wlcop/reconstructions/{cat}/{instance}.txt'
|
| 1283 |
+
|
| 1284 |
+
instance_pcd_path = instance.replace('.txt','.ply').replace('/raw/','/reconstructions/') # mesh file, like .obj, .ply
|
| 1285 |
+
|
| 1286 |
+
# Load the instance point cloud
|
| 1287 |
+
# instance_pcd_np = np.loadtxt(instance_pcd_path, delimiter=",")
|
| 1288 |
+
instance_pcd = o3d.io.read_point_cloud(instance_pcd_path)
|
| 1289 |
+
instance_pcd_np = np.asarray(instance_pcd.points) # shape (N, 3)
|
| 1290 |
+
instance_pcd_tensor = torch.from_numpy(instance_pcd_np)
|
| 1291 |
+
N = instance_pcd_tensor.shape[0]
|
| 1292 |
+
if N != 1024:
|
| 1293 |
+
print(f"Warning: {instance_name} has {N} points, expected 1024. Skipping.")
|
| 1294 |
+
continue
|
| 1295 |
+
instance_points = instance_pcd_tensor.view(1, N, 3).float().cuda(0)
|
| 1296 |
+
|
| 1297 |
+
try:
|
| 1298 |
+
suffix = Path(obj_path).suffix.lower() # works for both Path and str
|
| 1299 |
+
|
| 1300 |
+
if suffix == ".ply":
|
| 1301 |
+
idx = extract_index_from_fname(Path(obj_path))
|
| 1302 |
+
category, _ = id_map[idx]
|
| 1303 |
+
R = lookup_transform(category, trans_map)
|
| 1304 |
+
verts, faces, aux = load_ply_with_rotation(obj_path, R=R, device=device)
|
| 1305 |
+
elif suffix == ".obj":
|
| 1306 |
+
verts, faces, aux = load_obj(str(obj_path))
|
| 1307 |
+
except ValueError as e:
|
| 1308 |
+
print(f"Warning: {e}, attempting to load without material.")
|
| 1309 |
+
|
| 1310 |
+
try:
|
| 1311 |
+
if suffix == ".ply":
|
| 1312 |
+
vverts, faces, aux = load_ply_with_rotation(obj_path, R=R, device=device)
|
| 1313 |
+
elif suffix == ".obj":
|
| 1314 |
+
verts, faces, aux = load_obj(str(obj_path))
|
| 1315 |
+
except ValueError as e2:
|
| 1316 |
+
print(f"Failed to load {obj_path} without material: {e2}")
|
| 1317 |
+
continue
|
| 1318 |
+
|
| 1319 |
+
# 检查 verts_uvs 是否为 None
|
| 1320 |
+
if aux.verts_uvs is not None:
|
| 1321 |
+
verts_uvs = aux.verts_uvs[None, ...] # (1, V, 2)
|
| 1322 |
+
faces_uvs = faces.textures_idx[None, ...] # (1, F, 3)
|
| 1323 |
+
tex_maps = aux.texture_images
|
| 1324 |
+
|
| 1325 |
+
# tex_maps is a dictionary of {material name: texture image}.
|
| 1326 |
+
# Take the first image:
|
| 1327 |
+
# if tex_maps:
|
| 1328 |
+
# texture_image = list(tex_maps.values())[0]
|
| 1329 |
+
# texture_image = texture_image[None, ...] # (1, H, W, 3)
|
| 1330 |
+
dev = verts_uvs.device # the device we want everything on
|
| 1331 |
+
tex_maps = aux.texture_images # dict[str, Tensor(H,W,3)]
|
| 1332 |
+
if tex_maps:
|
| 1333 |
+
texture_image = list(tex_maps.values())[0]
|
| 1334 |
+
# ensure shape (1,H,W,3), dtype float32, device match
|
| 1335 |
+
if texture_image.dim() == 3:
|
| 1336 |
+
texture_image = texture_image.unsqueeze(0)
|
| 1337 |
+
texture_image = texture_image.to(dev).float().contiguous()
|
| 1338 |
+
|
| 1339 |
+
# Create a textures object
|
| 1340 |
+
tex = TexturesUV(verts_uvs=verts_uvs, faces_uvs=faces_uvs, maps=texture_image)
|
| 1341 |
+
else:
|
| 1342 |
+
# 如果 verts_uvs 是 None,直接跳过纹理处理,或者你可以设置默认行为
|
| 1343 |
+
print(f"No UV coordinates for {instance_name}, skipping texture mapping.")
|
| 1344 |
+
tex = None
|
| 1345 |
+
|
| 1346 |
+
# Initialise the mesh with textures
|
| 1347 |
+
verts = normalize_mesh_verts(verts) # Housecat meshes are absolute scale
|
| 1348 |
+
#meshes = Meshes(verts=[verts], faces=[faces.verts_idx], textures=None)
|
| 1349 |
+
meshes = Meshes(verts=[verts], faces=[faces.verts_idx], textures=tex)
|
| 1350 |
+
|
| 1351 |
+
|
| 1352 |
+
if meshes.textures is None:
|
| 1353 |
+
meshes.textures = TexturesVertex(
|
| 1354 |
+
verts_features=torch.ones_like(meshes.verts_padded(), device=device)
|
| 1355 |
+
)
|
| 1356 |
+
|
| 1357 |
+
# render the mesh with 8 views, scale means the distance from the object to the camera
|
| 1358 |
+
image_size=(420,420)
|
| 1359 |
+
# images,fragments,cameras = render_batch(meshes,image_size=image_size,scale=2.0)
|
| 1360 |
+
images,fragments,cameras = render(meshes,image_size=image_size,scale=2.0)
|
| 1361 |
+
|
| 1362 |
+
# get the feature point cloud
|
| 1363 |
+
feature_point_cloud, dino_feat_masked, feature_point_cloud_list = fuse_feature_rgbd(extractor,images,fragments,cameras)
|
| 1364 |
+
|
| 1365 |
+
# get the downsampled aggregated feature point cloud
|
| 1366 |
+
num_pts= 1024
|
| 1367 |
+
nn_num= 1024 # larger nn_num will make the feature more smooth
|
| 1368 |
+
sampled_points,aggregated_features = downsample_with_knn_feature_aggregation(feature_point_cloud,num_pts,nn_num,instance_points)
|
| 1369 |
+
|
| 1370 |
+
# #Needed
|
| 1371 |
+
# index = np.random.choice(partial_feature_point_cloud.shape[0], 1024, replace=False)
|
| 1372 |
+
# plot_pointclouds_3d_with_copca(average_aggregated_features.squeeze(0).detach().cpu().numpy(),
|
| 1373 |
+
# partial_feature_point_cloud[index,3:],
|
| 1374 |
+
# sampled_points.squeeze(0).detach().cpu().numpy(),
|
| 1375 |
+
# partial_feature_point_cloud[index,:3])
|
| 1376 |
+
|
| 1377 |
+
|
| 1378 |
+
q=0
|
| 1379 |
+
|
| 1380 |
+
os.makedirs(f'{save_dir}/saved_dino_pcd_tex/{cat}', exist_ok=True)
|
| 1381 |
+
torch.save(aggregated_features, f'{save_dir}/saved_dino_pcd_tex/{cat}/{instance_name}_dino_feature.pt')
|
| 1382 |
+
|
| 1383 |
+
aggregated_features_list.append(aggregated_features)
|
| 1384 |
+
# #break
|
| 1385 |
+
vis_dino = vis_pca_pixelwise(np.array(dino_feat_masked))
|
| 1386 |
+
vis_img = np.clip(vis_dino[:,:,:,:],a_min=0,a_max=1)
|
| 1387 |
+
image_grid(vis_img, rows=2, cols=4, rgb=True)
|
| 1388 |
+
|
| 1389 |
+
os.makedirs(f'{save_dir}/{cat}_rgb_dino', exist_ok=True)
|
| 1390 |
+
plt.savefig(f'{save_dir}/{cat}_rgb_dino/{instance_name}_dino.png')
|
| 1391 |
+
plt.close()
|
| 1392 |
+
if False:
|
| 1393 |
+
|
| 1394 |
+
rgb = images.cpu().numpy()[:, :, :, :3]
|
| 1395 |
+
mask = images[:, ..., 3].cpu().numpy()!=0
|
| 1396 |
+
depth_image = fragments[:, ..., 0].cpu().numpy()*mask
|
| 1397 |
+
image_grid(rgb, rows=1, cols=8, rgb=True)
|
| 1398 |
+
# os.makedirs(f'/home/tulrfpf/code/PointFlowRenderer/{cat}_rgb_dino', exist_ok=True)
|
| 1399 |
+
# plt.savefig(f'/home/tulrfpf/code/PointFlowRenderer/{cat}_rgb_dino/{instance}_rgb.png')
|
| 1400 |
+
# image_grid(depth_image[...,None], rows=2, cols=4, rgb=True)
|
| 1401 |
+
# image_grid(mask[...,None], rows=2, cols=4, rgb=True)
|
| 1402 |
+
|
| 1403 |
+
|
| 1404 |
+
|
| 1405 |
+
fig = plt.figure(figsize=(10, 10))
|
| 1406 |
+
ax = fig.add_subplot(111, projection="3d")
|
| 1407 |
+
#ax.scatter(sampled_points[:, 2], sampled_points[:,0], sampled_points[:, 1], c="b")
|
| 1408 |
+
pca_color =vis_pca(feature_point_cloud[:, 3:])
|
| 1409 |
+
ax.scatter(feature_point_cloud[:, 2], feature_point_cloud[:, 0], feature_point_cloud[:, 1], c=pca_color,s=0.1)
|
| 1410 |
+
#create_camera_geometry_batch(ax=ax,R_batch=R,T_batch=T,order=(2,0,1))
|
| 1411 |
+
ax.set_xlabel("z")
|
| 1412 |
+
ax.set_ylabel("x")
|
| 1413 |
+
ax.set_zlabel("y")
|
| 1414 |
+
ax.set_xlim(-2, 2)
|
| 1415 |
+
ax.set_ylim(-2, 2)
|
| 1416 |
+
ax.set_zlim(-2, 2)
|
| 1417 |
+
plt.title("Sampled Dense Points from Mesh")
|
| 1418 |
+
plt.show()
|
| 1419 |
+
|
| 1420 |
+
fig = plt.figure(figsize=(10, 10))
|
| 1421 |
+
ax = fig.add_subplot(111, projection="3d")
|
| 1422 |
+
pca_color =vis_pca(aggregated_features.squeeze(0))
|
| 1423 |
+
sampled_points= sampled_points.squeeze(0).cpu().detach().numpy()
|
| 1424 |
+
ax.scatter(sampled_points[:, 2], sampled_points[:, 0], sampled_points[:, 1], c=pca_color,s=50)
|
| 1425 |
+
#create_camera_geometry_batch(ax=ax,R_batch=R,T_batch=T,order=(2,0,1))
|
| 1426 |
+
ax.set_xlabel("z")
|
| 1427 |
+
ax.set_ylabel("x")
|
| 1428 |
+
ax.set_zlabel("y")
|
| 1429 |
+
ax.set_xlim(-2, 2)
|
| 1430 |
+
ax.set_ylim(-2, 2)
|
| 1431 |
+
ax.set_zlim(-2, 2)
|
| 1432 |
+
plt.title("Sampled Sparse Points from Mesh")
|
| 1433 |
+
plt.show()
|
| 1434 |
+
#break
|
| 1435 |
+
# Assign the aggregated features to the mean shape point cloud
|
| 1436 |
+
if len(aggregated_features_list) == 0:
|
| 1437 |
+
print(f"No valid instances found for category {cat}, skipping saving average features.")
|
| 1438 |
+
continue
|
| 1439 |
+
|
| 1440 |
+
# quickly check if the category has been processed
|
| 1441 |
+
# target_feature_file = f'{save_dir}/sem_cat_pcd_tex/{cat}_dino_feature.pt'
|
| 1442 |
+
# if os.path.exists(target_feature_file):
|
| 1443 |
+
# # print(f"Skipping '{cat}', file already exists at: {target_feature_file}")
|
| 1444 |
+
# continue # continue 会立即结束本次循环,进入下一次循环
|
| 1445 |
+
|
| 1446 |
+
aggregated_features_tensor = torch.cat(aggregated_features_list, dim=0) #[N, 1024, 384]
|
| 1447 |
+
average_aggregated_features = aggregated_features_tensor.mean(dim=0, keepdim=True)
|
| 1448 |
+
print("Average Aggregated Features Shape:", average_aggregated_features.shape) # Should be (1, 1024, 384)
|
| 1449 |
+
|
| 1450 |
+
os.makedirs(f'{save_dir}/sem_cat_pcd_tex', exist_ok=True)
|
| 1451 |
+
torch.save(average_aggregated_features, f'{save_dir}/sem_cat_pcd_tex/{cat}_dino_feature.pt')
|
| 1452 |
+
|
| 1453 |
+
# fig = plt.figure(figsize=(10, 10))
|
| 1454 |
+
# ax = fig.add_subplot(111, projection="3d")
|
| 1455 |
+
# pca_color =vis_pca(average_aggregated_features.squeeze(0))
|
| 1456 |
+
# # sampled_points= sampled_points.squeeze(0).cpu().detach().numpy()
|
| 1457 |
+
# meanshape_points = meanshape_points.squeeze(0).cpu().detach().numpy()
|
| 1458 |
+
# ax.scatter(meanshape_points[:, 2], meanshape_points[:, 0], meanshape_points[:, 1], c=pca_color,s=10.0, marker='o')
|
| 1459 |
+
# ax.set_xlabel("z")
|
| 1460 |
+
# ax.set_ylabel("x")
|
| 1461 |
+
# ax.set_zlabel("y")
|
| 1462 |
+
# ax.set_xlim(-2, 2)
|
| 1463 |
+
# ax.set_ylim(-2, 2)
|
| 1464 |
+
# ax.set_zlim(-2, 2)
|
| 1465 |
+
# plt.title("Shape Prior Dino")
|
| 1466 |
+
# plt.show()
|
| 1467 |
+
|
RGBD_DINO_HouseCat6D_final_copy.py
ADDED
|
@@ -0,0 +1,1083 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from custom_utils import ShapeNetCore
|
| 3 |
+
from custom_utils import _compute_fov,_sample_points_from_faces
|
| 4 |
+
from custom_utils import image_grid
|
| 5 |
+
from custom_utils.shapenet_base import HouseCatDataset
|
| 6 |
+
import matplotlib.pyplot as plt
|
| 7 |
+
import numpy as np
|
| 8 |
+
import k3d
|
| 9 |
+
import os
|
| 10 |
+
import json
|
| 11 |
+
import torch
|
| 12 |
+
from PIL import Image
|
| 13 |
+
|
| 14 |
+
import cv2
|
| 15 |
+
import imageio
|
| 16 |
+
import numpy as np
|
| 17 |
+
from PIL import Image
|
| 18 |
+
import matplotlib.pyplot as plt
|
| 19 |
+
from torchvision import transforms
|
| 20 |
+
from custom_utils.extractor import ViTExtractor
|
| 21 |
+
import torch.nn.functional as F
|
| 22 |
+
from sklearn.decomposition import PCA as sklearnPCA
|
| 23 |
+
import math
|
| 24 |
+
from custom_utils.utils_general import center_crop
|
| 25 |
+
|
| 26 |
+
from pytorch3d.io import load_objs_as_meshes, load_obj
|
| 27 |
+
from pytorch3d.implicitron.tools.point_cloud_utils import get_rgbd_point_cloud
|
| 28 |
+
from pytorch3d.structures import Meshes
|
| 29 |
+
from pytorch3d.renderer import (
|
| 30 |
+
PerspectiveCameras,
|
| 31 |
+
FoVPerspectiveCameras,
|
| 32 |
+
PointLights,
|
| 33 |
+
MeshRasterizer,
|
| 34 |
+
MeshRenderer,
|
| 35 |
+
RasterizationSettings,
|
| 36 |
+
HardPhongShader,
|
| 37 |
+
TexturesVertex,
|
| 38 |
+
look_at_view_transform,
|
| 39 |
+
ray_bundle_to_ray_points,
|
| 40 |
+
NDCMultinomialRaysampler,
|
| 41 |
+
TexturesUV,
|
| 42 |
+
BlendParams,
|
| 43 |
+
|
| 44 |
+
TexturesVertex
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
from pytorch3d.implicitron.tools.point_cloud_utils import get_rgbd_point_cloud
|
| 48 |
+
from pytorch3d.structures import Pointclouds
|
| 49 |
+
import torch
|
| 50 |
+
from pytorch3d.ops import sample_farthest_points, knn_points, knn_gather
|
| 51 |
+
|
| 52 |
+
from matplotlib import cm
|
| 53 |
+
import numpy as np
|
| 54 |
+
import matplotlib.pyplot as plt
|
| 55 |
+
from sklearn.decomposition import PCA
|
| 56 |
+
from mpl_toolkits.mplot3d import Axes3D
|
| 57 |
+
import open3d as o3d
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def sample_points_on_sphere(num_points=80):
|
| 61 |
+
points = []
|
| 62 |
+
phi = (1 + math.sqrt(5)) / 2 # golden ratio
|
| 63 |
+
|
| 64 |
+
for i in range(num_points):
|
| 65 |
+
theta = 2 * math.pi * i / phi # azimuthal angle
|
| 66 |
+
z = 1 - (2 * i + 1) / num_points # z-coordinate, uniform from -1 to 1
|
| 67 |
+
radius = math.sqrt(1 - z * z) # radius for the xy-plane
|
| 68 |
+
x = radius * math.cos(theta)
|
| 69 |
+
y = radius * math.sin(theta)
|
| 70 |
+
points.append([x, y, z])
|
| 71 |
+
|
| 72 |
+
return torch.tensor(points, dtype=torch.float32)
|
| 73 |
+
|
| 74 |
+
def get_cube_vertices():
|
| 75 |
+
# Cube vertices (8 vertices)
|
| 76 |
+
return torch.tensor([[1, 1, 1],
|
| 77 |
+
[1, 1, -1],
|
| 78 |
+
[1, -1, 1],
|
| 79 |
+
[1, -1, -1],
|
| 80 |
+
[-1, 1, 1],
|
| 81 |
+
[-1, 1, -1],
|
| 82 |
+
[-1, -1, 1],
|
| 83 |
+
[-1, -1, -1]], dtype=torch.float32) # Ensure float type
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def render(meshes,scale=3.0,image_size=(420,420),light=(0.3,0.3,0.3)):
|
| 87 |
+
# prepare the camera
|
| 88 |
+
num_views = 8
|
| 89 |
+
# Get the cube vertices
|
| 90 |
+
#cube_vertices = get_cube_vertices()*scale
|
| 91 |
+
cube_vertices = sample_points_on_sphere(num_views)*scale
|
| 92 |
+
#up = torch.randn(1, 3)
|
| 93 |
+
up=torch.tensor([[0.0, 0.0, 1.0]], dtype=torch.float32)
|
| 94 |
+
up = up / torch.norm(up, dim=1)[:, None]
|
| 95 |
+
R, T = look_at_view_transform(eye=cube_vertices, at=torch.tensor([[0.0, 0.0, 0.0]], dtype=torch.float32), up=up)
|
| 96 |
+
cam_K= np.array([[572, 0.0, image_size[0]//2], [0.0, 572, image_size[1]//2], [0.0, 0.0, 1.0]])
|
| 97 |
+
fx,_,cx,_,fy,cy,_,_,_=cam_K.reshape(9)
|
| 98 |
+
fov_x, fov_y = _compute_fov(cam_K, 420, 420)
|
| 99 |
+
|
| 100 |
+
cameras = PerspectiveCameras(device=device, R=R, T=T, image_size=((420,420),),
|
| 101 |
+
focal_length=torch.tensor([[fx, fy]], dtype=torch.float32),
|
| 102 |
+
principal_point=torch.tensor([[cx, cy]], dtype=torch.float32),
|
| 103 |
+
in_ndc=False)
|
| 104 |
+
|
| 105 |
+
# prepare the lights
|
| 106 |
+
raster_settings = RasterizationSettings(image_size=image_size)
|
| 107 |
+
lights = PointLights(location=torch.tensor([0.0, 1.0, -2.0], device=device)[None], ambient_color=(light,),diffuse_color=(light,),device=device)
|
| 108 |
+
|
| 109 |
+
# move the data to the device
|
| 110 |
+
meshes = meshes.to(device)
|
| 111 |
+
cameras = cameras.to(device)
|
| 112 |
+
if len(cameras) != 1 and len(cameras) % len(meshes) != 0:
|
| 113 |
+
raise ValueError("Mismatch between batch dims of cameras and meshes.")
|
| 114 |
+
if len(cameras) > 1:
|
| 115 |
+
meshes = meshes.extend(len(cameras) // len(meshes))
|
| 116 |
+
|
| 117 |
+
# prepare the renderer
|
| 118 |
+
class MeshRendererWithDepth(torch.nn.Module):
|
| 119 |
+
def __init__(self, rasterizer, shader):
|
| 120 |
+
super().__init__()
|
| 121 |
+
self.rasterizer = rasterizer
|
| 122 |
+
self.shader = shader
|
| 123 |
+
|
| 124 |
+
def forward(self, meshes_world, **kwargs) -> torch.Tensor:
|
| 125 |
+
fragments = self.rasterizer(meshes_world, **kwargs)
|
| 126 |
+
images = self.shader(fragments, meshes_world, **kwargs)
|
| 127 |
+
return images, fragments.zbuf
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
blend_params = BlendParams(background_color=(0.0, 0.0, 0.0)) # Blue background
|
| 131 |
+
renderer = MeshRendererWithDepth(
|
| 132 |
+
rasterizer=MeshRasterizer(
|
| 133 |
+
cameras=cameras,
|
| 134 |
+
raster_settings=raster_settings,
|
| 135 |
+
),
|
| 136 |
+
# Set background color to blue [R, G, B]
|
| 137 |
+
|
| 138 |
+
shader=HardPhongShader(
|
| 139 |
+
device=device,
|
| 140 |
+
cameras=cameras,
|
| 141 |
+
lights=lights,
|
| 142 |
+
blend_params=blend_params
|
| 143 |
+
)
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
images,fragments = renderer(meshes)
|
| 147 |
+
return images,fragments,cameras
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def render_batch(meshes,scale=3.0,image_size=(420,420),light=(0.3,0.3,0.3)):
|
| 151 |
+
# prepare the camera
|
| 152 |
+
num_views = 8
|
| 153 |
+
# Get the cube vertices
|
| 154 |
+
cube_vertices = get_cube_vertices()*scale
|
| 155 |
+
#cube_vertices = sample_points_on_sphere(num_views)*scale
|
| 156 |
+
up = torch.randn(1, 3)
|
| 157 |
+
# up=torch.tensor([[0.0, 0.0, 1.0]], dtype=torch.float32)
|
| 158 |
+
up = up / torch.norm(up, dim=1)[:, None]
|
| 159 |
+
R, T = look_at_view_transform(eye=cube_vertices, at=torch.tensor([[0.0, 0.0, 0.0]], dtype=torch.float32), up=up)
|
| 160 |
+
|
| 161 |
+
cam_K= np.array([[572, 0.0, image_size[0]//2], [0.0, 572, image_size[1]//2], [0.0, 0.0, 1.0]])
|
| 162 |
+
fx,_,cx,_,fy,cy,_,_,_=cam_K.reshape(9)
|
| 163 |
+
fov_x, fov_y = _compute_fov(cam_K, 420, 420)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
# prepare the renderer
|
| 167 |
+
class MeshRendererWithDepth(torch.nn.Module):
|
| 168 |
+
def __init__(self, rasterizer, shader):
|
| 169 |
+
super().__init__()
|
| 170 |
+
self.rasterizer = rasterizer
|
| 171 |
+
self.shader = shader
|
| 172 |
+
|
| 173 |
+
def forward(self, meshes_world, **kwargs) -> torch.Tensor:
|
| 174 |
+
fragments = self.rasterizer(meshes_world, **kwargs)
|
| 175 |
+
images = self.shader(fragments, meshes_world, **kwargs)
|
| 176 |
+
return images, fragments.zbuf
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
blend_params = BlendParams(background_color=(0.0, 0.0, 0.0)) # Blue background
|
| 180 |
+
|
| 181 |
+
batch_size = 10
|
| 182 |
+
all_images=[]
|
| 183 |
+
all_fragments=[]
|
| 184 |
+
|
| 185 |
+
# move the data to the device
|
| 186 |
+
meshes = meshes.extend(batch_size).to(device)
|
| 187 |
+
for i in range(0,R.shape[0],batch_size):
|
| 188 |
+
R_batch = R[i:i+batch_size]
|
| 189 |
+
T_batch = T[i:i+batch_size]
|
| 190 |
+
cameras_batch = PerspectiveCameras(device=device, R=R_batch, T=T_batch, image_size=((420,420),),
|
| 191 |
+
focal_length=torch.tensor([[fx, fy]], dtype=torch.float32),
|
| 192 |
+
principal_point=torch.tensor([[cx, cy]], dtype=torch.float32),
|
| 193 |
+
in_ndc=False).to(device)
|
| 194 |
+
|
| 195 |
+
# prepare the lights
|
| 196 |
+
raster_settings = RasterizationSettings(image_size=image_size)
|
| 197 |
+
lights = PointLights(location=torch.tensor([0.0, 1.0, -2.0], device=device)[None],
|
| 198 |
+
ambient_color=(light,),diffuse_color=(light,),device=device)
|
| 199 |
+
|
| 200 |
+
renderer = MeshRendererWithDepth(
|
| 201 |
+
rasterizer=MeshRasterizer(
|
| 202 |
+
cameras=cameras_batch,
|
| 203 |
+
raster_settings=raster_settings,
|
| 204 |
+
),
|
| 205 |
+
# Set background color to blue [R, G, B]
|
| 206 |
+
shader=HardPhongShader(
|
| 207 |
+
device=device,
|
| 208 |
+
cameras=cameras_batch,
|
| 209 |
+
lights=lights,
|
| 210 |
+
blend_params=blend_params
|
| 211 |
+
)
|
| 212 |
+
)
|
| 213 |
+
images,fragments = renderer(meshes)
|
| 214 |
+
all_images.append(images)
|
| 215 |
+
all_fragments.append(fragments)
|
| 216 |
+
all_images = torch.cat(all_images,dim=0)
|
| 217 |
+
all_fragments = torch.cat(all_fragments,dim=0)
|
| 218 |
+
cameras = PerspectiveCameras(device=device, R=R, T=T, image_size=((420,420),),
|
| 219 |
+
focal_length=torch.tensor([[fx, fy]], dtype=torch.float32),
|
| 220 |
+
principal_point=torch.tensor([[cx, cy]], dtype=torch.float32),
|
| 221 |
+
in_ndc=False).to(device)
|
| 222 |
+
return all_images,all_fragments,cameras
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
def fuse_feature_rgbd(extractor,images,fragments,cameras):
|
| 226 |
+
dino_feat_masked_list = []
|
| 227 |
+
feature_point_cloud_list = []
|
| 228 |
+
for i in range(images.shape[0]):
|
| 229 |
+
image = images.cpu().numpy()[i, :, :, :3]
|
| 230 |
+
image_mask = images[i, ..., 3].cpu().numpy()!=0
|
| 231 |
+
crop_size = (420, 420)
|
| 232 |
+
crop_image, crop_mask, bbox = center_crop(image, image_mask, crop_size)
|
| 233 |
+
cropped_image_np = cv2.resize(crop_image, crop_size, interpolation=cv2.INTER_AREA)
|
| 234 |
+
#cropped_mask = cv2.resize(crop_mask*1.0, crop_size, interpolation=cv2.INTER_NEAREST)!=0 # Use nearest neighbor interpolation for masks
|
| 235 |
+
orignal_size = (int(bbox[2]-bbox[0]), int(bbox[3]-bbox[1])) #K,K
|
| 236 |
+
|
| 237 |
+
to_tensor = transforms.ToTensor()
|
| 238 |
+
input_image = to_tensor(cropped_image_np).cuda()
|
| 239 |
+
input_image = input_image.unsqueeze(0)
|
| 240 |
+
#input_image=extractor.preprocess_pil(input_image)
|
| 241 |
+
mean = torch.tensor([0.485, 0.456, 0.406]).cuda()
|
| 242 |
+
std = torch.tensor([0.229, 0.224, 0.225]).cuda()
|
| 243 |
+
input_image = (input_image - mean[None, :, None, None]) / std[None, :, None, None]
|
| 244 |
+
|
| 245 |
+
_desc_q = extractor.extract_descriptors(input_image,layer=11,include_cls=True).squeeze(1) # (1,900,384)
|
| 246 |
+
#_desc_q = extractor.forward_features(input_image)["x_prenorm"][:, :] # (1,900,384)
|
| 247 |
+
#_desc_q = extractor.extract_descriptors(input_image,layer=11,facet='token',include_cls=True).squeeze(1) # B,L,C
|
| 248 |
+
# _norm_q = torch.linalg.norm(_desc_q, dim=-1)[:, :, None]
|
| 249 |
+
# _desc_q = _desc_q / (_norm_q)
|
| 250 |
+
|
| 251 |
+
desc = _desc_q[:,1:,:][None]
|
| 252 |
+
#cls_token_q = _desc_q[:,0,:] #B,C`
|
| 253 |
+
|
| 254 |
+
input_mask = to_tensor(crop_mask).cuda()
|
| 255 |
+
input_mask = input_mask.unsqueeze(0)
|
| 256 |
+
|
| 257 |
+
img_mask = to_tensor(image_mask)
|
| 258 |
+
|
| 259 |
+
img_mask = img_mask.permute(1,2,0)
|
| 260 |
+
|
| 261 |
+
dino_feat = patch2pixel_feats(desc, original_size=orignal_size) #reize back to K,K =>( K, K, 384)
|
| 262 |
+
# create dino-feat with orignal size
|
| 263 |
+
dino_height, dino_width, feat_dim = (image_size[0],image_size[1], desc.shape[-1])
|
| 264 |
+
dino_feat_orig = torch.zeros(dino_height,dino_width,feat_dim)
|
| 265 |
+
# Fill the dino features into the original tensor at the specified bounding box
|
| 266 |
+
dino_feat_orig[bbox[1]:bbox[3], bbox[0]:bbox[2],:] = dino_feat #reize back to K,K =>(420, 420, 384) #gradint is not supported for this operation
|
| 267 |
+
# Apply the mask
|
| 268 |
+
dino_feat_masked = dino_feat_orig * img_mask
|
| 269 |
+
dino_feat_masked = dino_feat_masked.permute(2,0,1).unsqueeze(0)
|
| 270 |
+
dino_feat_masked_low = F.interpolate(dino_feat_masked, size=(30, 30), mode='bilinear')
|
| 271 |
+
|
| 272 |
+
image_mask = images[i, ..., 3][None,None]
|
| 273 |
+
depth_image = fragments[i, ..., 0][None]*image_mask
|
| 274 |
+
|
| 275 |
+
# # Define the kernel for erosion (3x3 ones kernel)
|
| 276 |
+
# kernel = torch.ones((1, 1, 5, 5), dtype=torch.float).cuda()
|
| 277 |
+
# # Number of erosion iterations
|
| 278 |
+
# iterations = 5
|
| 279 |
+
|
| 280 |
+
# # Perform iterative erosion
|
| 281 |
+
# for i in range(iterations):
|
| 282 |
+
# # Apply erosion using 2D convolution
|
| 283 |
+
# eroded_mask = F.conv2d(image_mask, kernel, padding=2)
|
| 284 |
+
# image_mask = (eroded_mask == kernel.sum()).float() # Update mask to eroded version
|
| 285 |
+
|
| 286 |
+
feature_point_cloud = get_rgbd_point_cloud(cameras[i], dino_feat_masked.to(device), depth_map=depth_image,mask=image_mask)#everthing on GPU
|
| 287 |
+
|
| 288 |
+
index = np.random.choice(feature_point_cloud.points_list()[0].shape[0], 4096, replace=True)
|
| 289 |
+
points = feature_point_cloud.points_list()[0].detach().cpu()[index,:]
|
| 290 |
+
colors = feature_point_cloud.features_list()[0].detach().cpu()[index,:]
|
| 291 |
+
# points = feature_point_cloud.points_list()[0].detach().cpu()[:,:]
|
| 292 |
+
# colors = feature_point_cloud.features_list()[0].detach().cpu()[:,:]
|
| 293 |
+
feature_point_cloud = torch.cat((points, colors), dim=1)
|
| 294 |
+
|
| 295 |
+
dino_feat_masked_list.append(dino_feat_masked_low.detach().cpu())
|
| 296 |
+
feature_point_cloud_list.append(feature_point_cloud)
|
| 297 |
+
feature_point_cloud = torch.cat(feature_point_cloud_list, dim=0)
|
| 298 |
+
dino_feat_masked = torch.cat(dino_feat_masked_list, dim=0)
|
| 299 |
+
return feature_point_cloud,dino_feat_masked, feature_point_cloud_list
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
def downsample_with_knn_feature_aggregation(feature_point_cloud,num_pts=1024,k_nearest_neighbors=100, instance_points=None):
|
| 303 |
+
#N_1, C_1 = 2048, 384 # Example number of points and features
|
| 304 |
+
num_points_to_sample = num_pts
|
| 305 |
+
k_nearest_neighbors = k_nearest_neighbors
|
| 306 |
+
|
| 307 |
+
# Example input pointcloud and features (N_1, C_1), where N_1 is the number of points and C_1 is the feature dimension
|
| 308 |
+
pointcloud = feature_point_cloud[None,:,:3].cuda() # Shape (1, N_1, 3) for 3D coordinates
|
| 309 |
+
features = feature_point_cloud[None,:,3:].cuda() # Shape (1, N_1, C_1) for features
|
| 310 |
+
|
| 311 |
+
# Step 1: FPS to downsample the points
|
| 312 |
+
# We use sample_farthest_points to select num_points_to_sample points
|
| 313 |
+
sampled_points, sampled_indices = sample_farthest_points(pointcloud, K=num_points_to_sample) # Shape: (1, 1024, 3), (1, 1024)
|
| 314 |
+
if instance_points is not None:
|
| 315 |
+
sampled_points = instance_points
|
| 316 |
+
|
| 317 |
+
# Step 2: KNN to find nearest neighbors
|
| 318 |
+
# Find the k nearest neighbors for each sampled point in the original pointcloud
|
| 319 |
+
dists, knn_indices, _ = knn_points(sampled_points, pointcloud, K=k_nearest_neighbors, return_nn=False)
|
| 320 |
+
|
| 321 |
+
# Step 3: Gather the features of the k-nearest neighbors using the knn indices
|
| 322 |
+
# Use knn_gather to get neighbor features for each sampled point
|
| 323 |
+
neighbor_features = knn_gather(features, knn_indices) # Shape: (1, 1024, k, C_1)
|
| 324 |
+
|
| 325 |
+
# Step 4: Aggregate features from the neighbors (e.g., by averaging)
|
| 326 |
+
#aggregated_features,_ = torch.max(neighbor_features,dim=-2) # Shape: (1, 1024, C_1)
|
| 327 |
+
aggregated_features = torch.mean(neighbor_features,dim=-2) # Shape: (1, 1024, C_1)
|
| 328 |
+
return sampled_points, aggregated_features
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
def vis_pca(feature):
|
| 332 |
+
n_components=3 # the first component is to seperate the object from the background
|
| 333 |
+
|
| 334 |
+
pca = sklearnPCA(n_components=n_components)
|
| 335 |
+
feature = pca.fit_transform(feature.detach().cpu().numpy())
|
| 336 |
+
for show_channel in range(n_components):
|
| 337 |
+
# min max normalize the feature map
|
| 338 |
+
feature[:, show_channel] = (feature[:, show_channel] - feature[:, show_channel].mean()) / (feature[:, show_channel].std()*10)
|
| 339 |
+
feature_resized = np.clip(feature[:,:]+0.5,0,1)
|
| 340 |
+
return feature_resized
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
def patch2pixel_feats(patch_features, original_size):
|
| 344 |
+
# Calculate the number of patches along each dimension
|
| 345 |
+
num_patches = int(math.sqrt(patch_features.shape[2]))
|
| 346 |
+
|
| 347 |
+
batch_num = patch_features.shape[0]
|
| 348 |
+
feat_dim = patch_features.shape[3]
|
| 349 |
+
patch_features = patch_features.reshape(batch_num, num_patches, num_patches, feat_dim)
|
| 350 |
+
patch_features = patch_features.permute(0,3,1,2)
|
| 351 |
+
|
| 352 |
+
pixel_features = F.interpolate(patch_features, size=(original_size[0], original_size[1]), mode='bilinear')
|
| 353 |
+
pixel_features = pixel_features.squeeze().permute(1,2,0)
|
| 354 |
+
|
| 355 |
+
return pixel_features
|
| 356 |
+
|
| 357 |
+
def vis_pca_pixelwise(feature):
|
| 358 |
+
n_components = 4 # The number of PCA components to use
|
| 359 |
+
batch, feat_dim, height,width = feature.shape
|
| 360 |
+
|
| 361 |
+
# Reshape the feature to (num_pixels, feat_dim)
|
| 362 |
+
num_pixels = height * width
|
| 363 |
+
feature_reshaped = np.array(feature).transpose(0,2,3,1).reshape(-1, feat_dim)
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
# Apply PCA
|
| 367 |
+
pca = sklearnPCA(n_components=n_components)
|
| 368 |
+
feature_pca = pca.fit_transform(feature_reshaped)
|
| 369 |
+
|
| 370 |
+
# Min-max normalization for each component
|
| 371 |
+
# for show_channel in range(n_components):
|
| 372 |
+
# feature_pca[:, show_channel] = (feature_pca[:, show_channel] - feature_pca[:, show_channel].min()) / \
|
| 373 |
+
# (feature_pca[:, show_channel].max() - feature_pca[:, show_channel].min() + 1e-8) # Small epsilon to avoid division by zero
|
| 374 |
+
for show_channel in range(n_components):
|
| 375 |
+
feature_pca[:, show_channel] = (feature_pca[:, show_channel] - feature_pca[:, show_channel].mean()) / \
|
| 376 |
+
(feature_pca[:, show_channel].std()*10 + 1e-8) # Small epsilon to avoid division by zero
|
| 377 |
+
|
| 378 |
+
feature_pca = np.clip(feature_pca+0.5, 0, 1)
|
| 379 |
+
# Reshape the PCA result back to (height, width, n_components)
|
| 380 |
+
feature_resized = feature_pca.reshape(batch,height,width,n_components)[...,1:4]
|
| 381 |
+
return feature_resized
|
| 382 |
+
|
| 383 |
+
def normalize_mesh_verts(data):
|
| 384 |
+
# data [N, 3]
|
| 385 |
+
min_vals, _ = torch.min(data, dim=0)
|
| 386 |
+
max_vals, _ = torch.max(data, dim=0)
|
| 387 |
+
bbox_sizes = max_vals - min_vals
|
| 388 |
+
scale = torch.norm(bbox_sizes)
|
| 389 |
+
print("Scale:", scale)
|
| 390 |
+
normalized_verts = verts / scale
|
| 391 |
+
return normalized_verts
|
| 392 |
+
|
| 393 |
+
def plot_pointclouds_with_color_mapping(pc1_f, pc2_f,pc1,pc2, query_points, similarity_threshold=None):
|
| 394 |
+
"""
|
| 395 |
+
Visualizes two 3D point clouds. The second point cloud (pc2) is color-mapped
|
| 396 |
+
using the 'viridis' colormap based on its similarity (proximity) to the sampled
|
| 397 |
+
query points in the first point cloud (pc1).
|
| 398 |
+
|
| 399 |
+
Parameters:
|
| 400 |
+
- pc1: np.ndarray of shape (N, 3), first point cloud #partial
|
| 401 |
+
- pc2: np.ndarray of shape (M, 3), second point cloud # global
|
| 402 |
+
- query_points: list of indices in pc1, representing the query points to compare.
|
| 403 |
+
- similarity_threshold: float, optional, threshold to cap the similarity distance.
|
| 404 |
+
"""
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
pc1_f = pc1_f / np.linalg.norm(pc1_f, axis=1)[:, None] # Normalize the features
|
| 408 |
+
pc2_f = pc2_f / np.linalg.norm(pc2_f, axis=1)[:, None] # Normalize the features
|
| 409 |
+
# Create a figure with subplots
|
| 410 |
+
fig = plt.figure(figsize=(12, 10))
|
| 411 |
+
num_query_points = len(query_points)
|
| 412 |
+
# Set limits and labels
|
| 413 |
+
size = pc2.max() - pc2.min()
|
| 414 |
+
# Plot the first point cloud in the first subplot
|
| 415 |
+
ax1 = fig.add_subplot(1, num_query_points + 1, 1, projection='3d')
|
| 416 |
+
ax1.scatter(pc2[:, 0], pc2[:, 1], pc2[:, 2], color='grey', label='Point Cloud 1 (Left)', alpha=0.1,s=10)
|
| 417 |
+
|
| 418 |
+
# Define a color list for each query point
|
| 419 |
+
query_colors = cm.tab10(np.linspace(0, 1, num_query_points)) # Use tab10 colormap for distinct colors
|
| 420 |
+
|
| 421 |
+
# Highlight query points in pc1 with different colors
|
| 422 |
+
for i, idx in enumerate(query_points):
|
| 423 |
+
ax1.scatter(pc1[idx, 0], pc1[idx, 1], pc1[idx, 2],
|
| 424 |
+
color=query_colors[i], s=100, edgecolor='k', label=f'Query Point {idx}')
|
| 425 |
+
|
| 426 |
+
ax1.set_title('Point Cloud 1 with Query Points')
|
| 427 |
+
ax1.set_xlabel('X')
|
| 428 |
+
ax1.set_ylabel('Y')
|
| 429 |
+
ax1.set_zlabel('Z')
|
| 430 |
+
ax1.set_xlim(-size / 1.4, size / 1.4)
|
| 431 |
+
ax1.set_ylim(-size / 1.4, size / 1.4)
|
| 432 |
+
ax1.set_zlim(-size / 1.4, size / 1.4)
|
| 433 |
+
ax1.view_init(elev=45, azim=-45)
|
| 434 |
+
ax1.grid(True)
|
| 435 |
+
ax1.legend()
|
| 436 |
+
|
| 437 |
+
# Plot the second point cloud in the subsequent subplots
|
| 438 |
+
for k in range(num_query_points):
|
| 439 |
+
|
| 440 |
+
ax = fig.add_subplot(1, num_query_points + 1, k + 2, projection='3d')
|
| 441 |
+
|
| 442 |
+
# Calculate distances between query points in pc1 and all points in pc2
|
| 443 |
+
similarity =(pc1_f[query_points[k]][None]@ pc2_f.T).reshape(-1) # (1, 3) x (M, 3) = (1, M)
|
| 444 |
+
# For each point in pc2, take the minimum distance to any query point
|
| 445 |
+
min_similarity = np.min(similarity, axis=0)
|
| 446 |
+
# Optionally cap the similarity distances to a threshold (to avoid extreme values)
|
| 447 |
+
similarity_threshold= 0.3
|
| 448 |
+
if similarity_threshold is not None:
|
| 449 |
+
similarity = np.clip(similarity, similarity_threshold,1)
|
| 450 |
+
# Normalize the distances to a range of 0 to 1 for colormap mapping
|
| 451 |
+
similarity = (similarity - np.min(similarity)) / (np.max(similarity) - np.min(similarity))
|
| 452 |
+
colors = cm.plasma(similarity)
|
| 453 |
+
|
| 454 |
+
# Plot the second point cloud with color mapping based on similarity
|
| 455 |
+
ax.scatter(pc2[:, 0], pc2[:, 1], pc2[:, 2], color=colors, s=15, alpha=1.0, label='Point Cloud 2 (Right)', edgecolor='k')
|
| 456 |
+
|
| 457 |
+
ax.set_xlim(-size / 1.4, size / 1.4)
|
| 458 |
+
ax.set_ylim(-size / 1.4, size / 1.4)
|
| 459 |
+
ax.set_zlim(-size / 1.4, size / 1.4)
|
| 460 |
+
ax.set_title(f'QP_{query_points[k]}')
|
| 461 |
+
ax.set_xlabel('X')
|
| 462 |
+
ax.set_ylabel('Y')
|
| 463 |
+
ax.set_zlabel('Z')
|
| 464 |
+
ax.view_init(elev=45, azim=-45)
|
| 465 |
+
ax.grid(True)
|
| 466 |
+
ax.legend()
|
| 467 |
+
|
| 468 |
+
# Show the plot
|
| 469 |
+
plt.tight_layout()
|
| 470 |
+
plt.show()
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
def plot_pointclouds_3d_with_copca_old(global_sem_pcd, partial_sem_pcd, global_pcd, partial_pcd):
|
| 474 |
+
"""
|
| 475 |
+
Visualizes two point clouds in 3D, coloring them based on their PCA components.
|
| 476 |
+
|
| 477 |
+
Parameters:
|
| 478 |
+
- global_pointcloud: numpy array of shape (N, D) for global point cloud.
|
| 479 |
+
- partial_pointcloud: numpy array of shape (M, D) for partial point cloud.
|
| 480 |
+
"""
|
| 481 |
+
|
| 482 |
+
|
| 483 |
+
n_components = 3
|
| 484 |
+
# Step 1: Perform PCA on both global and partial point clouds
|
| 485 |
+
sem_pca = PCA(n_components=n_components)
|
| 486 |
+
sem_pca = sem_pca.fit(global_sem_pcd) # shape (N+M, 3)
|
| 487 |
+
|
| 488 |
+
transformed_sem_pcd_list = [sem_pca.transform(pcd) for pcd in [global_sem_pcd,partial_sem_pcd]]
|
| 489 |
+
sem_pcd_pca = np.concatenate(transformed_sem_pcd_list,axis=0)
|
| 490 |
+
for show_channel in range(n_components):
|
| 491 |
+
sem_pcd_pca[:, show_channel] = (sem_pcd_pca[:, show_channel] - sem_pcd_pca[:, show_channel].mean()) / \
|
| 492 |
+
(sem_pcd_pca[:, show_channel].std()*5 + 1e-8) # Small epsilon to avoid division by zero
|
| 493 |
+
|
| 494 |
+
# sem_pcd_pca_min = sem_pcd_pca.min()
|
| 495 |
+
# sem_pcd_pca_max = sem_pcd_pca.max()
|
| 496 |
+
# sem_pcd_pca = (sem_pcd_pca- sem_pcd_pca_min) / (sem_pcd_pca_max - sem_pcd_pca_min) # Normalize to [0, 1]
|
| 497 |
+
|
| 498 |
+
sem_pcd_pca = np.clip(sem_pcd_pca[:,:]+0.5, 0, 1)
|
| 499 |
+
global_pca = sem_pcd_pca[:global_sem_pcd.shape[0]] # shape (N, 3)
|
| 500 |
+
partial_pca = sem_pcd_pca[-partial_sem_pcd.shape[0]:] # shape (M, 3)
|
| 501 |
+
|
| 502 |
+
# Step 2: Create a 3D scatter plot
|
| 503 |
+
fig = plt.figure(figsize=(12, 6))
|
| 504 |
+
ax = fig.add_subplot(121, projection='3d')
|
| 505 |
+
|
| 506 |
+
|
| 507 |
+
# Global point cloud
|
| 508 |
+
ax.scatter(global_pcd[:, 0], global_pcd[:, 1], global_pcd[:, 2],
|
| 509 |
+
c=global_pca, marker='o', s=100, alpha=1.0, label='Global Point Cloud')
|
| 510 |
+
|
| 511 |
+
# Set labels for each axis
|
| 512 |
+
# ax.set_xlabel('X axis')
|
| 513 |
+
# ax.set_ylabel('Y axis')
|
| 514 |
+
# ax.set_zlabel('Z axis')
|
| 515 |
+
ax.set_xlim(-0.5, 0.5)
|
| 516 |
+
ax.set_ylim(-0.5, 0.5)
|
| 517 |
+
ax.set_zlim(-0.5, 0.5)
|
| 518 |
+
|
| 519 |
+
ax1 = fig.add_subplot(122, projection='3d')
|
| 520 |
+
|
| 521 |
+
# Partial point cloud
|
| 522 |
+
ax1.scatter(partial_pcd[:, 0], partial_pcd[:, 1], partial_pcd[:, 2],
|
| 523 |
+
c=partial_pca, marker='o', s=100, alpha=1.0, label='Partial Point Cloud')
|
| 524 |
+
|
| 525 |
+
# ax1.scatter(global_pcd[:, 0], global_pcd[:, 1], global_pcd[:, 2],
|
| 526 |
+
# marker='o', s=10, alpha=0.1)
|
| 527 |
+
# Set labels for each axis
|
| 528 |
+
# ax1.set_xlabel('X axis')
|
| 529 |
+
# ax1.set_ylabel('Y axis')
|
| 530 |
+
# ax1.set_zlabel('Z axis')
|
| 531 |
+
|
| 532 |
+
|
| 533 |
+
ax1.set_xlim(-0.5, 0.5)
|
| 534 |
+
ax1.set_ylim(-0.5, 0.5)
|
| 535 |
+
ax1.set_zlim(-0.5, 0.5)
|
| 536 |
+
plt.tight_layout()
|
| 537 |
+
|
| 538 |
+
ax.view_init(120,-95)
|
| 539 |
+
ax1.view_init(120,-95)
|
| 540 |
+
|
| 541 |
+
|
| 542 |
+
ax.set_axis_off()
|
| 543 |
+
ax.set_facecolor((0, 0, 0, 0))
|
| 544 |
+
ax1.set_axis_off()
|
| 545 |
+
ax1.set_facecolor((0, 0, 0, 0))
|
| 546 |
+
|
| 547 |
+
plt.show()
|
| 548 |
+
|
| 549 |
+
|
| 550 |
+
def plot_pointclouds_3d_with_pca(global_sem_pcd, global_pcd):
|
| 551 |
+
"""
|
| 552 |
+
Visualizes two point clouds in 3D, coloring them based on their PCA components.
|
| 553 |
+
|
| 554 |
+
Parameters:
|
| 555 |
+
- global_pointcloud: numpy array of shape (N, D) for global point cloud.
|
| 556 |
+
- partial_pointcloud: numpy array of shape (M, D) for partial point cloud.
|
| 557 |
+
"""
|
| 558 |
+
#sem_pcd = np.concatenate((global_sem_pcd,partial_sem_pcd), axis=0) # shape (N+M, D)
|
| 559 |
+
|
| 560 |
+
# Step 1: Perform PCA on both global and partial point clouds
|
| 561 |
+
sem_pca = PCA(n_components=3)
|
| 562 |
+
sem_pcd_pca = sem_pca.fit_transform(global_sem_pcd) # shape (N+M, 3)
|
| 563 |
+
|
| 564 |
+
for i in range(3): # Iterate over each component (3 in total for RGB)
|
| 565 |
+
sem_pcd_pca_mean = sem_pcd_pca[:, i].mean()
|
| 566 |
+
sem_pcd_pca_std = sem_pcd_pca[:, i].std()
|
| 567 |
+
sem_pcd_pca[:, i] = (sem_pcd_pca[:, i] - sem_pcd_pca_mean) / (sem_pcd_pca_std*5+1e-8) # Normalize to [0, 1]
|
| 568 |
+
|
| 569 |
+
|
| 570 |
+
global_pca = np.clip(sem_pcd_pca+0.5,0,1)
|
| 571 |
+
# scatter plot
|
| 572 |
+
fig = plt.figure(figsize=(6, 6))
|
| 573 |
+
ax = fig.add_subplot(111, projection='3d')
|
| 574 |
+
|
| 575 |
+
# Global point cloud
|
| 576 |
+
ax.scatter(global_pcd[:, 0], global_pcd[:, 1], global_pcd[:, 2],
|
| 577 |
+
c=global_pca, marker='o', s=50, alpha=1.0, label='Global Point Cloud')
|
| 578 |
+
|
| 579 |
+
# Remove axes and background
|
| 580 |
+
ax.set_axis_off()
|
| 581 |
+
|
| 582 |
+
# Set background color to none
|
| 583 |
+
ax.set_facecolor((0, 0, 0, 0))
|
| 584 |
+
# # Set labels for each axis
|
| 585 |
+
# ax.set_xlabel('X axis')
|
| 586 |
+
# ax.set_ylabel('Y axis')
|
| 587 |
+
# ax.set_zlabel('Z axis')
|
| 588 |
+
ax.set_xlim(-0.5, 0.5)
|
| 589 |
+
ax.set_ylim(-0.5, 0.5)
|
| 590 |
+
ax.set_zlim(-0.5, 0.5)
|
| 591 |
+
|
| 592 |
+
ax.view_init(-73,102)
|
| 593 |
+
|
| 594 |
+
return fig
|
| 595 |
+
|
| 596 |
+
|
| 597 |
+
def plot_pointclouds_3d_with_copca(global_sem_pcd_list, global_pcd_list,co_pca=True):
|
| 598 |
+
"""
|
| 599 |
+
Visualizes multiple point clouds in 3D, each in a separate subplot, after applying CoPCA.
|
| 600 |
+
Coloring them based on their PCA components.
|
| 601 |
+
|
| 602 |
+
Parameters:
|
| 603 |
+
- global_sem_pcd_list: list of numpy arrays for semantic point clouds (one per object).
|
| 604 |
+
- global_pcd_list: list of numpy arrays for global point clouds (one per object).
|
| 605 |
+
"""
|
| 606 |
+
num_pcds = len(global_sem_pcd_list) # Number of point clouds
|
| 607 |
+
print("Number of point clouds to visualize:", num_pcds)
|
| 608 |
+
# Step 1: Perform CoPCA (Common PCA) on the semantic point clouds
|
| 609 |
+
# Concatenate all point clouds to perform common PCA
|
| 610 |
+
if co_pca:
|
| 611 |
+
|
| 612 |
+
concatenated_pcds = np.concatenate(global_sem_pcd_list, axis=0) # shape (N_total, D)
|
| 613 |
+
copca = PCA(n_components=3, random_state=0)
|
| 614 |
+
copca.fit(concatenated_pcds[:1024]) # Fit PCA on all point clouds together
|
| 615 |
+
transformed_sem_pcd_list = [copca.transform(pcd) for pcd in global_sem_pcd_list]
|
| 616 |
+
|
| 617 |
+
|
| 618 |
+
signs = np.sign(np.sum(transformed_sem_pcd_list[0], axis=0))
|
| 619 |
+
# Post-process to ensure consistent orientation of PCA components
|
| 620 |
+
for i, transformed_pcd in enumerate(transformed_sem_pcd_list):
|
| 621 |
+
# For each component (column), align sign based on the sum of values in the column
|
| 622 |
+
transformed_sem_pcd_list[i] = transformed_pcd * signs
|
| 623 |
+
else:
|
| 624 |
+
copca = PCA(n_components=3)
|
| 625 |
+
transformed_sem_pcd_list = [copca.fit_transform(pcd) for pcd in global_sem_pcd_list]
|
| 626 |
+
# Post-process to ensure consistent orientation of PCA components
|
| 627 |
+
for i, transformed_pcd in enumerate(transformed_sem_pcd_list):
|
| 628 |
+
signs = np.sign(np.sum(transformed_pcd, axis=0))
|
| 629 |
+
# For each component (column), align sign based on the sum of values in the column
|
| 630 |
+
transformed_sem_pcd_list[i] = transformed_pcd * signs
|
| 631 |
+
|
| 632 |
+
|
| 633 |
+
|
| 634 |
+
# Create a figure with subplots arranged in a grid (based on number of point clouds)
|
| 635 |
+
fig = plt.figure(figsize=(6 * num_pcds, 6)) # Adjust figure size based on the number of subplots
|
| 636 |
+
|
| 637 |
+
# Loop over the point clouds
|
| 638 |
+
for idx, (sem_pcd_pca, global_pcd) in enumerate(zip(transformed_sem_pcd_list, global_pcd_list)):
|
| 639 |
+
ax = fig.add_subplot(1, num_pcds, idx + 1, projection='3d')
|
| 640 |
+
|
| 641 |
+
# Step 2: Normalize the PCA-transformed data to use as colors
|
| 642 |
+
for i in range(3): # Iterate over each component (3 in total for RGB)
|
| 643 |
+
pca_mean = sem_pcd_pca[:, i].mean()
|
| 644 |
+
pca_std = sem_pcd_pca[:, i].std()
|
| 645 |
+
sem_pcd_pca[:, i] = (sem_pcd_pca[:, i] - pca_mean) / (pca_std * 5 + 1e-8) # Normalize
|
| 646 |
+
|
| 647 |
+
global_pca_colors = np.clip(sem_pcd_pca + 0.5, 0, 1) # Map to [0, 1] for RGB
|
| 648 |
+
|
| 649 |
+
# Scatter plot for this point cloud in the current subplot
|
| 650 |
+
ax.scatter(global_pcd[:, 0], global_pcd[:, 1], global_pcd[:, 2],
|
| 651 |
+
c=global_pca_colors, marker='o', s=50, alpha=1.0)
|
| 652 |
+
|
| 653 |
+
# Remove axes and background
|
| 654 |
+
ax.set_axis_off()
|
| 655 |
+
ax.set_facecolor((0, 0, 0, 0))
|
| 656 |
+
|
| 657 |
+
# Set axis limits for each subplot
|
| 658 |
+
ax.set_xlim(-0.5, 0.5)
|
| 659 |
+
ax.set_ylim(-0.5, 0.5)
|
| 660 |
+
ax.set_zlim(-0.5, 0.5)
|
| 661 |
+
|
| 662 |
+
# Set view angle
|
| 663 |
+
ax.view_init(-55, 102)
|
| 664 |
+
|
| 665 |
+
# Adjust spacing between subplots
|
| 666 |
+
plt.tight_layout()
|
| 667 |
+
|
| 668 |
+
return fig
|
| 669 |
+
|
| 670 |
+
|
| 671 |
+
|
| 672 |
+
def unnormalize(x):
|
| 673 |
+
# x.shape : [H,W,3]
|
| 674 |
+
mean = np.array([0.485, 0.456, 0.406])
|
| 675 |
+
std = np.array([0.229, 0.224, 0.225])
|
| 676 |
+
return x * std + mean
|
| 677 |
+
|
| 678 |
+
|
| 679 |
+
from custom_utils.housecat6d_dataset import HouseCat6DTrainingDataset
|
| 680 |
+
trainset = HouseCat6DTrainingDataset(image_size=420, sample_num=1024,data_dir='/media/xyz/data1/HouseCat6D')
|
| 681 |
+
|
| 682 |
+
vis = True
|
| 683 |
+
device = "cuda"
|
| 684 |
+
import matplotlib
|
| 685 |
+
matplotlib.use('TkAgg')
|
| 686 |
+
|
| 687 |
+
#cat_list = ['bottle','box','can','cup','cutlery','remote','shoe','tube','teapot']
|
| 688 |
+
cat_list = ['cup']
|
| 689 |
+
|
| 690 |
+
|
| 691 |
+
sem_global_list = []
|
| 692 |
+
sem_global_pcd_list = []
|
| 693 |
+
|
| 694 |
+
# load semantc feature and show
|
| 695 |
+
########################################
|
| 696 |
+
save_dir = 'Yung/yung_large_files/semantic_feature/test_notebook/8v'
|
| 697 |
+
#save_dir = './80views_textured_token'
|
| 698 |
+
if True:
|
| 699 |
+
for cat in cat_list:
|
| 700 |
+
# # orriginal
|
| 701 |
+
# with open(f'/mnt/4T/Yung/yung_large_files/semantic_feature/test_notebook/housecat_{cat}/raw/housecat1_train.txt', 'r') as f:
|
| 702 |
+
# instances = [line.strip() for line in f.readlines()]
|
| 703 |
+
|
| 704 |
+
# print(instances)
|
| 705 |
+
# revised
|
| 706 |
+
# instance try cup-grey_handle
|
| 707 |
+
instances = ['cup-grey_handle']
|
| 708 |
+
sem_global_list = []
|
| 709 |
+
sem_global_pcd_list = []
|
| 710 |
+
|
| 711 |
+
# Load the mean shape point cloud
|
| 712 |
+
meanshape_path = f'Yung/yung_large_files/semantic_feature/test_notebook/saved_pcd/{cat}/mean_shape/mean_shape_pcd_1.txt'
|
| 713 |
+
meanshape_pcd_np = np.loadtxt(meanshape_path)
|
| 714 |
+
meanshape_pcd_tensor = torch.from_numpy(meanshape_pcd_np)
|
| 715 |
+
M = meanshape_pcd_tensor.shape[0]
|
| 716 |
+
meanshape_points = meanshape_pcd_tensor.view(1, M, 3).float()
|
| 717 |
+
#make sure map to cuda0
|
| 718 |
+
average_aggregated_features = torch.load(f'//mnt/4T/Yung/yung_large_files/semantic_feature/test_notebook/8v_key/sem_cat_pcd_untex/cup_dino_feature.pt', map_location={"cuda:1": "cuda:0"})
|
| 719 |
+
sem_global_pcd_list.append(meanshape_points[0])
|
| 720 |
+
sem_global_list.append(average_aggregated_features[0].detach().cpu())
|
| 721 |
+
#fig =plot_pointclouds_3d_with_pca(average_aggregated_features[0].detach().cpu(),meanshape_points[0])
|
| 722 |
+
#fig.savefig('test.png')
|
| 723 |
+
for j,instance in enumerate(instances):
|
| 724 |
+
#break
|
| 725 |
+
print("Processing", instance)
|
| 726 |
+
#obj_path = f'/media/xyz/data/HouseCat6D/obj_models_small_size_final/{cat}/{instance}.obj'
|
| 727 |
+
#instance_pcd_tensor = torch.load(f'{save_dir}/saved_pcd_untex/{cat}/{instance}_pcd.pt')[0]
|
| 728 |
+
#obj_path = f'/media/xyz/data1/HouseCat6D/obj_models_small_size_final/{cat}/{instance}.obj'
|
| 729 |
+
# if instance != 'cup-grey_handle':
|
| 730 |
+
# # original pcd
|
| 731 |
+
instance_pcd_path = f'Yung/yung_large_files/semantic_feature/test_notebook/saved_pcd/{cat}/test/{instance}.txt'
|
| 732 |
+
# Load the instance point cloud
|
| 733 |
+
instance_pcd_np = np.loadtxt(instance_pcd_path)
|
| 734 |
+
reference_scale = np.linalg.norm(instance_pcd_np.max(axis=0) - instance_pcd_np.min(axis=0))
|
| 735 |
+
|
| 736 |
+
# else:
|
| 737 |
+
# instance_pcd_path = f'Yung/yung_large_files/pose_can_results/housecat6d_sonata_feature/scene01/000000/cup-grey_handle/normalized_groundtruth_pca.ply'
|
| 738 |
+
# pcd = o3d.io.read_point_cloud(instance_pcd_path)
|
| 739 |
+
# instance_pcd_np = np.asarray(pcd.points)
|
| 740 |
+
|
| 741 |
+
current_scale = np.linalg.norm(instance_pcd_np.max(axis=0) - instance_pcd_np.min(axis=0))
|
| 742 |
+
scale_factor = reference_scale / current_scale
|
| 743 |
+
instance_pcd_np = instance_pcd_np * scale_factor
|
| 744 |
+
|
| 745 |
+
scale = np.linalg.norm(instance_pcd_np.max(axis=0) - instance_pcd_np.min(axis=0))
|
| 746 |
+
print("Scale:", scale)
|
| 747 |
+
|
| 748 |
+
instance_pcd_tensor = torch.from_numpy(instance_pcd_np)
|
| 749 |
+
N = instance_pcd_tensor.shape[0]
|
| 750 |
+
instance_points = instance_pcd_tensor.view(1, N, 3).float()
|
| 751 |
+
try:
|
| 752 |
+
# aggregated_features = torch.load(f'{save_dir}/saved_dino_pcd_untex/{cat}/{instance}_dino_feature.pt')
|
| 753 |
+
aggregated_features = average_aggregated_features
|
| 754 |
+
except:
|
| 755 |
+
print(f"Warning: {instance} not found.")
|
| 756 |
+
continue
|
| 757 |
+
# plot_pointclouds_3d_with_pca(aggregated_features[0].detach().cpu(),
|
| 758 |
+
# instance_points[0])
|
| 759 |
+
|
| 760 |
+
sem_global_pcd_list.append(instance_points[0].detach().cpu())
|
| 761 |
+
sem_global_list.append(aggregated_features[0].detach().cpu())
|
| 762 |
+
if len(sem_global_list)>4:
|
| 763 |
+
break
|
| 764 |
+
|
| 765 |
+
fig = plot_pointclouds_3d_with_copca(sem_global_list,sem_global_pcd_list,co_pca=True)
|
| 766 |
+
fig.savefig(f'./{save_dir}/{cat}.png')
|
| 767 |
+
###############################
|
| 768 |
+
|
| 769 |
+
|
| 770 |
+
model_dict={'small':'dinov2_vits14',
|
| 771 |
+
'base':'dinov2_vitb14',
|
| 772 |
+
'large':'dinov2_vitl14',
|
| 773 |
+
'giant':'dinov2_vitg14'}
|
| 774 |
+
extractor = ViTExtractor(model_dict['small'],14)
|
| 775 |
+
# use GPPU0
|
| 776 |
+
extractor.model = extractor.model.cuda(0) # the stride of first conv control outputs resolution
|
| 777 |
+
|
| 778 |
+
# extractor = torch.hub.load('facebookresearch/dinov2', model_dict['small'], pretrained=True).cuda()
|
| 779 |
+
|
| 780 |
+
|
| 781 |
+
# cat_list = ['bottle','box','can','cup','cutlery','glass','remote','shoe','tube','teapot']
|
| 782 |
+
cat_list = ['cup']
|
| 783 |
+
|
| 784 |
+
#cat_list = ['teapot']
|
| 785 |
+
#TODO: if condition for tex rendering
|
| 786 |
+
for cat in cat_list:
|
| 787 |
+
# orriginal
|
| 788 |
+
with open(f'/mnt/4T/Yung/yung_large_files/semantic_feature/test_notebook/housecat_{cat}/raw/housecat1_train.txt', 'r') as f:
|
| 789 |
+
instances = [line.strip() for line in f.readlines()]
|
| 790 |
+
|
| 791 |
+
print(instances)
|
| 792 |
+
# #revised
|
| 793 |
+
# # instance try cup-grey_handle
|
| 794 |
+
# instances = ['cup-grey_handle']
|
| 795 |
+
|
| 796 |
+
aggregated_features_list = [] # N * [1, 1024, 384]
|
| 797 |
+
# Load the mean shape point cloud
|
| 798 |
+
meanshape_path = f'Yung/yung_large_files/semantic_feature/test_notebook/saved_pcd/{cat}/mean_shape/mean_shape_pcd_1.txt'
|
| 799 |
+
meanshape_pcd_np = np.loadtxt(meanshape_path)
|
| 800 |
+
meanshape_pcd_tensor = torch.from_numpy(meanshape_pcd_np)
|
| 801 |
+
M = meanshape_pcd_tensor.shape[0]
|
| 802 |
+
# modify for cuda0
|
| 803 |
+
meanshape_points = meanshape_pcd_tensor.view(1, M, 3).float().cuda(0)
|
| 804 |
+
|
| 805 |
+
|
| 806 |
+
for j,instance in enumerate(instances):
|
| 807 |
+
# if instance != 'bottle-85_alcool':
|
| 808 |
+
# continue
|
| 809 |
+
print("Processing", instance)
|
| 810 |
+
obj_path = f'pose_dataset/HouseCat6D/obj_models_small_size_final/{cat}/{instance}.obj'
|
| 811 |
+
instance_pcd_path = f'Yung/yung_large_files/semantic_feature/test_notebook/saved_pcd/{cat}/test/{instance}.txt'
|
| 812 |
+
|
| 813 |
+
# Load the instance point cloud
|
| 814 |
+
instance_pcd_np = np.loadtxt(instance_pcd_path)
|
| 815 |
+
instance_pcd_tensor = torch.from_numpy(instance_pcd_np)
|
| 816 |
+
N = instance_pcd_tensor.shape[0]
|
| 817 |
+
# modify for cuda0
|
| 818 |
+
instance_points = instance_pcd_tensor.view(1, N, 3).float().cuda(0)
|
| 819 |
+
|
| 820 |
+
try:
|
| 821 |
+
verts, faces, aux = load_obj(obj_path)
|
| 822 |
+
except ValueError as e:
|
| 823 |
+
print(f"Warning: {e}, attempting to load without material.")
|
| 824 |
+
|
| 825 |
+
try:
|
| 826 |
+
verts, faces, aux = load_obj(obj_path, load_textures=True)
|
| 827 |
+
except ValueError as e2:
|
| 828 |
+
print(f"Failed to load {obj_path} without material: {e2}")
|
| 829 |
+
continue
|
| 830 |
+
|
| 831 |
+
# 检查 verts_uvs 是否为 None
|
| 832 |
+
if aux.verts_uvs is not None:
|
| 833 |
+
verts_uvs = aux.verts_uvs[None, ...] # (1, V, 2)
|
| 834 |
+
faces_uvs = faces.textures_idx[None, ...] # (1, F, 3)
|
| 835 |
+
tex_maps = aux.texture_images
|
| 836 |
+
|
| 837 |
+
# tex_maps is a dictionary of {material name: texture image}.
|
| 838 |
+
# Take the first image:
|
| 839 |
+
if tex_maps:
|
| 840 |
+
texture_image = list(tex_maps.values())[0]
|
| 841 |
+
texture_image = texture_image[None, ...] # (1, H, W, 3)
|
| 842 |
+
|
| 843 |
+
# Create a textures object
|
| 844 |
+
tex = TexturesUV(verts_uvs=verts_uvs, faces_uvs=faces_uvs, maps=texture_image)
|
| 845 |
+
print(f"Loaded texture for {instance}.")
|
| 846 |
+
else:
|
| 847 |
+
# 如果 verts_uvs 是 None,直接跳过纹理处理,或者你可以设置默认行为
|
| 848 |
+
print(f"No UV coordinates for {instance}, skipping texture mapping.")
|
| 849 |
+
tex = None
|
| 850 |
+
|
| 851 |
+
# Initialise the mesh with textures
|
| 852 |
+
verts = normalize_mesh_verts(verts) # Housecat meshes are absolute scale
|
| 853 |
+
# meshes = Meshes(verts=[verts], faces=[faces.verts_idx], textures=None)
|
| 854 |
+
# Rotate mesh 180 degrees around Y axis
|
| 855 |
+
# rotation_matrix = torch.tensor([
|
| 856 |
+
# [-1.0, 0.0, 0.0],
|
| 857 |
+
# [0.0, 1.0, 0.0],
|
| 858 |
+
# [0.0, 0.0, -1.0]
|
| 859 |
+
# ], dtype=torch.float32, device="cpu")
|
| 860 |
+
# verts = torch.matmul(verts, rotation_matrix.T)
|
| 861 |
+
|
| 862 |
+
meshes = Meshes(verts=[verts], faces=[faces.verts_idx], textures=None)
|
| 863 |
+
|
| 864 |
+
if meshes.textures is None:
|
| 865 |
+
meshes.textures = TexturesVertex(
|
| 866 |
+
verts_features=torch.ones_like(meshes.verts_padded(), device=device)
|
| 867 |
+
)
|
| 868 |
+
|
| 869 |
+
# render the mesh with 8 views, scale means the distance from the object to the camera
|
| 870 |
+
image_size=(420,420)
|
| 871 |
+
#images,fragments,cameras = render_batch(meshes,image_size=image_size,scale=1.0)
|
| 872 |
+
images,fragments,cameras = render(meshes,image_size=image_size,scale=2.0)
|
| 873 |
+
|
| 874 |
+
os.makedirs(f'{save_dir}/{cat}_rgb_dino_untex-try', exist_ok=True)
|
| 875 |
+
rgb = images.cpu().numpy()[:, :, :, :3]
|
| 876 |
+
image_grid(rgb, rows=1, cols=8, rgb=True)
|
| 877 |
+
plt.savefig(f'{save_dir}/{cat}_rgb_dino_untex-try/{instance}_rendering-notexture.png')
|
| 878 |
+
plt.close()
|
| 879 |
+
|
| 880 |
+
# get the feature point cloud
|
| 881 |
+
feature_point_cloud, dino_feat_masked, feature_point_cloud_list = fuse_feature_rgbd(extractor,images,fragments,cameras)
|
| 882 |
+
|
| 883 |
+
# get the downsampled aggregated feature point cloud
|
| 884 |
+
num_pts= 1024
|
| 885 |
+
nn_num= 100 # larger nn_num will make the feature more smooth
|
| 886 |
+
sampled_points,aggregated_features = downsample_with_knn_feature_aggregation(feature_point_cloud,num_pts,nn_num)
|
| 887 |
+
|
| 888 |
+
# #Needed
|
| 889 |
+
# index = np.random.choice(partial_feature_point_cloud.shape[0], 1024, replace=False)
|
| 890 |
+
# plot_pointclouds_3d_with_copca(average_aggregated_features.squeeze(0).detach().cpu().numpy(),
|
| 891 |
+
# partial_feature_point_cloud[index,3:],
|
| 892 |
+
# sampled_points.squeeze(0).detach().cpu().numpy(),
|
| 893 |
+
# partial_feature_point_cloud[index,:3])
|
| 894 |
+
|
| 895 |
+
|
| 896 |
+
q=0
|
| 897 |
+
|
| 898 |
+
if False:
|
| 899 |
+
q+=1
|
| 900 |
+
inputs = trainset[q]
|
| 901 |
+
rgb = inputs['rgb'][None].cuda()
|
| 902 |
+
pts = inputs['pts'][None]
|
| 903 |
+
choose = inputs['choose'][None]
|
| 904 |
+
model = inputs['model'][None].cuda()
|
| 905 |
+
rgb = inputs['rgb'][None].cuda()
|
| 906 |
+
|
| 907 |
+
_desc_q = extractor.forward_features(rgb)["x_prenorm"][:, :]
|
| 908 |
+
#_desc_q = extractor.extract_descriptors(rgb,layer=11,facet='token',include_cls=True).squeeze(1) # B,L,C
|
| 909 |
+
# _norm_q = torch.linalg.norm(_desc_q, dim=-1)[:, :, None]
|
| 910 |
+
# _desc_q = _desc_q / (_norm_q)
|
| 911 |
+
|
| 912 |
+
dino_feature = _desc_q[:,1:,:]
|
| 913 |
+
|
| 914 |
+
|
| 915 |
+
#dino_feature = self.rgb_extractor.forward_features(rgb)["x_prenorm"][:, 1:]
|
| 916 |
+
#rgb=self.rgb_extractor.preprocess_pil(rgb)
|
| 917 |
+
#dino_feature = self.rgb_extractor.extract_descriptors(rgb,layer=11,facet='key') # (1,900,384)
|
| 918 |
+
f_dim = dino_feature.shape[-1]
|
| 919 |
+
num_patches =int(dino_feature.shape[1]**0.5) # 1
|
| 920 |
+
b=1
|
| 921 |
+
dino_feature = dino_feature.reshape(b, num_patches, num_patches, f_dim).permute(0,3,1,2)
|
| 922 |
+
|
| 923 |
+
dino_feature = F.interpolate(dino_feature, size=(num_patches * 14, num_patches * 14), mode='nearest')
|
| 924 |
+
dino_feature_2d_vis = dino_feature.detach().cpu()[0] #384, 224,224
|
| 925 |
+
|
| 926 |
+
b, d = dino_feature.shape[0:2]
|
| 927 |
+
dino_feature = dino_feature.reshape(b,d,-1)
|
| 928 |
+
choose_2 = choose.unsqueeze(1).repeat(1, d, 1).cuda()
|
| 929 |
+
dino_feature = torch.gather(dino_feature,2,choose_2).contiguous() # b,d,n
|
| 930 |
+
|
| 931 |
+
#dino_feature = dino_feature / torch.std(dino_feature, dim=1, keepdim=True)
|
| 932 |
+
#dino_feature = torch.norm(dino_feature, dim=1, keepdim=True)
|
| 933 |
+
#choose_dino = choose.unsqueeze(1).repeat(1, d, 1Z
|
| 934 |
+
#sem_model = sem_model / torch.std(sem_model, dim=-1, keepdim=True)
|
| 935 |
+
#visual_global_sem_high = sem_model.detach().cpu().numpy()[0] #1024,384
|
| 936 |
+
visual_partial_sem_high = dino_feature.permute(0,2,1).detach().cpu().numpy()[0] #1024,128
|
| 937 |
+
|
| 938 |
+
#visual_global_sem_low = self.feature_mlp(sem_model.permute(0,2,1)).permute(0,2,1).detach().cpu().numpy()[0]
|
| 939 |
+
#visual_partial_sem_low = rgb_local.permute(0,2,1).detach().cpu().numpy()[0]
|
| 940 |
+
# transform the pts with GT 9D Pose into object coordinate
|
| 941 |
+
translation_gt = inputs['translation_label'][None]
|
| 942 |
+
rotation_gt = inputs['rotation_label'][None]
|
| 943 |
+
size_gt = inputs['size_label'][None]
|
| 944 |
+
pts_obj_frame = (inputs['pts'] - translation_gt.unsqueeze(1)) / (torch.norm(size_gt, dim=1).view(b, 1, 1) + 1e-8) @ rotation_gt
|
| 945 |
+
#kpt_obj_frame = (kpt_3d - translation_gt.unsqueeze(1)) / (torch.norm(size_gt, dim=1).view(b, 1, 1) + 1e-8) @ rotation_gt
|
| 946 |
+
|
| 947 |
+
# dino_feature_2d_vis_pca = vis_pca_pixelwise(dino_feature_2d_vis[None])[0]
|
| 948 |
+
# plt.imshow(dino_feature_2d_vis_pca[:,:,:3])
|
| 949 |
+
# plt.show()
|
| 950 |
+
# fig =plt.figure()
|
| 951 |
+
# rgb_unnorm = unnormalize(rgb[0].permute(1,2,0).detach().cpu())
|
| 952 |
+
# plt.imshow(rgb_unnorm)
|
| 953 |
+
# plt.show()
|
| 954 |
+
# image_mask = ((rgb_unnorm.clone().sum(axis=2) >0.1)*1.0)[None,None] # 224,224
|
| 955 |
+
|
| 956 |
+
# rgb_mask = np.array(image_mask[0,0,:,:,None]).repeat(384, axis=2).transpose(2,0,1)
|
| 957 |
+
|
| 958 |
+
# dino_feature_2d_vis[rgb_mask==0] = 0
|
| 959 |
+
# masked_dino_feature_2d_vis_pca = vis_pca_pixelwise(dino_feature_2d_vis[None])[0]
|
| 960 |
+
# plt.imshow(masked_dino_feature_2d_vis_pca[:,:,:])
|
| 961 |
+
# plt.show()
|
| 962 |
+
|
| 963 |
+
|
| 964 |
+
# print('self.pca.cateagg-partial')
|
| 965 |
+
# index = np.random.choice(partial_feature_point_cloud.shape[0], 1024, replace=False)
|
| 966 |
+
# #average_aggregated_features = torch.load(f'sem_cat_pcd/{cat}_dino_feature.pt')
|
| 967 |
+
|
| 968 |
+
average_aggregated_features = torch.load(f'/home/xyz/anything6d_project/Sem-GCE-AG-Pose/sem_cat_pcd/{cat}_dino_feature.pt')
|
| 969 |
+
# #plot_pointclouds_3d_with_copca(aggregated_features.squeeze(0).detach().cpu().numpy(), partial_feature_point_cloud[index,3:], sampled_points.squeeze(0).detach().cpu().numpy(), pts_obj_frame)
|
| 970 |
+
|
| 971 |
+
plot_pointclouds_3d_with_copca_old(average_aggregated_features.squeeze(0).detach().cpu().numpy(),
|
| 972 |
+
visual_partial_sem_high,
|
| 973 |
+
sampled_points.squeeze(0).detach().cpu().numpy(),
|
| 974 |
+
pts_obj_frame[0].detach().cpu().numpy())
|
| 975 |
+
plt.show()
|
| 976 |
+
|
| 977 |
+
|
| 978 |
+
# plot_pointclouds_3d_with_copca(average_aggregated_features.squeeze(0).detach().cpu().numpy(),
|
| 979 |
+
# visual_partial_sem_high,
|
| 980 |
+
# sampled_points.squeeze(0).detach().cpu().numpy(),
|
| 981 |
+
# pts_obj_frame[0].detach().cpu().numpy())
|
| 982 |
+
|
| 983 |
+
|
| 984 |
+
# #query_points =np.random.choice(1024, 3)
|
| 985 |
+
# query_points, sampled_indices = sample_farthest_points(pts_obj_frame, K=4) # Shape: (1, 1024, 3), (1, 1024)
|
| 986 |
+
# plot_pointclouds_with_color_mapping(visual_partial_sem_high,
|
| 987 |
+
# aggregated_features.squeeze(0).detach().cpu().numpy(),
|
| 988 |
+
# pts_obj_frame[0].detach().cpu().numpy(),
|
| 989 |
+
# model[0].detach().cpu().numpy(),
|
| 990 |
+
# sampled_indices[0], similarity_threshold=None)
|
| 991 |
+
|
| 992 |
+
|
| 993 |
+
# # plot_pointclouds_3d_with_copca(average_aggregated_features.squeeze(0).detach().cpu().numpy(), partial_feature_point_cloud[index,3:], sampled_points.squeeze(0).detach().cpu().numpy(), partial_feature_point_cloud[index,:3])
|
| 994 |
+
# # plot_pointclouds_3d_with_pca(average_aggregated_features.squeeze(0).detach().cpu().numpy(), partial_feature_point_cloud[index,3:], sampled_points.squeeze(0).detach().cpu().numpy(), partial_feature_point_cloud[index,:3])
|
| 995 |
+
# partial_feature_point_cloud = feature_point_cloud_list[5]
|
| 996 |
+
# plot_pointclouds_3d_with_copca(visual_partial_sem_high,
|
| 997 |
+
# partial_feature_point_cloud[index,3:],
|
| 998 |
+
# pts_obj_frame[0].detach().cpu().numpy(),
|
| 999 |
+
# partial_feature_point_cloud[index,:3])
|
| 1000 |
+
|
| 1001 |
+
# plot_pointclouds_3d_with_copca(average_aggregated_features.squeeze(0).detach().cpu().numpy(), aggregated_features.squeeze(0).detach().cpu().numpy(), sampled_points.squeeze(0).detach().cpu().numpy(), sampled_points.squeeze(0).detach().cpu().numpy())
|
| 1002 |
+
|
| 1003 |
+
os.makedirs(f'{save_dir}/saved_dino_pcd_untex-try/{cat}', exist_ok=True)
|
| 1004 |
+
torch.save(aggregated_features, f'{save_dir}/saved_dino_pcd_untex-try/{cat}/{instance}_dino_feature-notexture.pt')
|
| 1005 |
+
|
| 1006 |
+
os.makedirs(f'{save_dir}/saved_pcd_untex-try/{cat}', exist_ok=True)
|
| 1007 |
+
torch.save(sampled_points, f'{save_dir}/saved_pcd_untex-try/{cat}/{instance}_pcd-notexture.pt')
|
| 1008 |
+
|
| 1009 |
+
aggregated_features_list.append(aggregated_features)
|
| 1010 |
+
# #break
|
| 1011 |
+
vis_dino = vis_pca_pixelwise(np.array(dino_feat_masked))
|
| 1012 |
+
vis_img = np.clip(vis_dino[:,:,:,:],a_min=0,a_max=1)
|
| 1013 |
+
image_grid(vis_img, rows=1, cols=8, rgb=True)
|
| 1014 |
+
|
| 1015 |
+
os.makedirs(f'{save_dir}/{cat}_rgb_dino_untex-try', exist_ok=True)
|
| 1016 |
+
plt.savefig(f'{save_dir}/{cat}_rgb_dino_untex-try/{instance}_dino-notexture.png')
|
| 1017 |
+
plt.close()
|
| 1018 |
+
if False:
|
| 1019 |
+
|
| 1020 |
+
rgb = images.cpu().numpy()[:, :, :, :3]
|
| 1021 |
+
mask = images[:, ..., 3].cpu().numpy()!=0
|
| 1022 |
+
depth_image = fragments[:, ..., 0].cpu().numpy()*mask
|
| 1023 |
+
image_grid(rgb, rows=1, cols=8, rgb=True)
|
| 1024 |
+
# os.makedirs(f'/home/tulrfpf/code/PointFlowRenderer/{cat}_rgb_dino', exist_ok=True)
|
| 1025 |
+
# plt.savefig(f'/home/tulrfpf/code/PointFlowRenderer/{cat}_rgb_dino/{instance}_rgb.png')
|
| 1026 |
+
# image_grid(depth_image[...,None], rows=2, cols=4, rgb=True)
|
| 1027 |
+
# image_grid(mask[...,None], rows=2, cols=4, rgb=True)
|
| 1028 |
+
|
| 1029 |
+
|
| 1030 |
+
|
| 1031 |
+
fig = plt.figure(figsize=(10, 10))
|
| 1032 |
+
ax = fig.add_subplot(111, projection="3d")
|
| 1033 |
+
#ax.scatter(sampled_points[:, 2], sampled_points[:,0], sampled_points[:, 1], c="b")
|
| 1034 |
+
pca_color =vis_pca(feature_point_cloud[:, 3:])
|
| 1035 |
+
ax.scatter(feature_point_cloud[:, 2], feature_point_cloud[:, 0], feature_point_cloud[:, 1], c=pca_color,s=0.1)
|
| 1036 |
+
#create_camera_geometry_batch(ax=ax,R_batch=R,T_batch=T,order=(2,0,1))
|
| 1037 |
+
ax.set_xlabel("z")
|
| 1038 |
+
ax.set_ylabel("x")
|
| 1039 |
+
ax.set_zlabel("y")
|
| 1040 |
+
ax.set_xlim(-2, 2)
|
| 1041 |
+
ax.set_ylim(-2, 2)
|
| 1042 |
+
ax.set_zlim(-2, 2)
|
| 1043 |
+
plt.title("Sampled Dense Points from Mesh")
|
| 1044 |
+
plt.show()
|
| 1045 |
+
|
| 1046 |
+
fig = plt.figure(figsize=(10, 10))
|
| 1047 |
+
ax = fig.add_subplot(111, projection="3d")
|
| 1048 |
+
pca_color =vis_pca(aggregated_features.squeeze(0))
|
| 1049 |
+
sampled_points= sampled_points.squeeze(0).cpu().detach().numpy()
|
| 1050 |
+
ax.scatter(sampled_points[:, 2], sampled_points[:, 0], sampled_points[:, 1], c=pca_color,s=50)
|
| 1051 |
+
#create_camera_geometry_batch(ax=ax,R_batch=R,T_batch=T,order=(2,0,1))
|
| 1052 |
+
ax.set_xlabel("z")
|
| 1053 |
+
ax.set_ylabel("x")
|
| 1054 |
+
ax.set_zlabel("y")
|
| 1055 |
+
ax.set_xlim(-2, 2)
|
| 1056 |
+
ax.set_ylim(-2, 2)
|
| 1057 |
+
ax.set_zlim(-2, 2)
|
| 1058 |
+
plt.title("Sampled Sparse Points from Mesh")
|
| 1059 |
+
plt.show()
|
| 1060 |
+
#break
|
| 1061 |
+
# Assign the aggregated features to the mean shape point cloud
|
| 1062 |
+
aggregated_features_tensor = torch.cat(aggregated_features_list, dim=0) #[N, 1024, 384]
|
| 1063 |
+
average_aggregated_features = aggregated_features_tensor.mean(dim=0, keepdim=True)
|
| 1064 |
+
print("Average Aggregated Features Shape:", average_aggregated_features.shape) # Should be (1, 1024, 384)
|
| 1065 |
+
|
| 1066 |
+
os.makedirs(f'{save_dir}/sem_cat_pcd_untex-try', exist_ok=True)
|
| 1067 |
+
torch.save(average_aggregated_features, f'{save_dir}/sem_cat_pcd_untex-try/{cat}_dino_feature.pt')
|
| 1068 |
+
|
| 1069 |
+
# fig = plt.figure(figsize=(10, 10))
|
| 1070 |
+
# ax = fig.add_subplot(111, projection="3d")
|
| 1071 |
+
# pca_color =vis_pca(average_aggregated_features.squeeze(0))
|
| 1072 |
+
# # sampled_points= sampled_points.squeeze(0).cpu().detach().numpy()
|
| 1073 |
+
# meanshape_points = meanshape_points.squeeze(0).cpu().detach().numpy()
|
| 1074 |
+
# ax.scatter(meanshape_points[:, 2], meanshape_points[:, 0], meanshape_points[:, 1], c=pca_color,s=10.0, marker='o')
|
| 1075 |
+
# ax.set_xlabel("z")
|
| 1076 |
+
# ax.set_ylabel("x")
|
| 1077 |
+
# ax.set_zlabel("y")
|
| 1078 |
+
# ax.set_xlim(-2, 2)
|
| 1079 |
+
# ax.set_ylim(-2, 2)
|
| 1080 |
+
# ax.set_zlim(-2, 2)
|
| 1081 |
+
# plt.title("Shape Prior Dino")
|
| 1082 |
+
# plt.show()
|
| 1083 |
+
|
RGBD_DINO_HouseCat6D_final_copy_amodal.py
ADDED
|
@@ -0,0 +1,1109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from custom_utils import ShapeNetCore
|
| 3 |
+
from custom_utils import _compute_fov,_sample_points_from_faces
|
| 4 |
+
from custom_utils import image_grid
|
| 5 |
+
from custom_utils.shapenet_base import HouseCatDataset
|
| 6 |
+
import matplotlib.pyplot as plt
|
| 7 |
+
import numpy as np
|
| 8 |
+
import k3d
|
| 9 |
+
import os
|
| 10 |
+
import json
|
| 11 |
+
import torch
|
| 12 |
+
from PIL import Image
|
| 13 |
+
|
| 14 |
+
import cv2
|
| 15 |
+
import imageio
|
| 16 |
+
import numpy as np
|
| 17 |
+
from PIL import Image
|
| 18 |
+
import matplotlib.pyplot as plt
|
| 19 |
+
from torchvision import transforms
|
| 20 |
+
from custom_utils.extractor import ViTExtractor
|
| 21 |
+
import torch.nn.functional as F
|
| 22 |
+
from sklearn.decomposition import PCA as sklearnPCA
|
| 23 |
+
import math
|
| 24 |
+
from custom_utils.utils_general import center_crop
|
| 25 |
+
|
| 26 |
+
from pytorch3d.io import load_objs_as_meshes, load_obj
|
| 27 |
+
from pytorch3d.implicitron.tools.point_cloud_utils import get_rgbd_point_cloud
|
| 28 |
+
from pytorch3d.structures import Meshes
|
| 29 |
+
from pytorch3d.renderer import (
|
| 30 |
+
PerspectiveCameras,
|
| 31 |
+
FoVPerspectiveCameras,
|
| 32 |
+
PointLights,
|
| 33 |
+
MeshRasterizer,
|
| 34 |
+
MeshRenderer,
|
| 35 |
+
RasterizationSettings,
|
| 36 |
+
HardPhongShader,
|
| 37 |
+
TexturesVertex,
|
| 38 |
+
look_at_view_transform,
|
| 39 |
+
ray_bundle_to_ray_points,
|
| 40 |
+
NDCMultinomialRaysampler,
|
| 41 |
+
TexturesUV,
|
| 42 |
+
BlendParams,
|
| 43 |
+
|
| 44 |
+
TexturesVertex
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
from pytorch3d.implicitron.tools.point_cloud_utils import get_rgbd_point_cloud
|
| 48 |
+
from pytorch3d.structures import Pointclouds
|
| 49 |
+
import torch
|
| 50 |
+
from pytorch3d.ops import sample_farthest_points, knn_points, knn_gather
|
| 51 |
+
|
| 52 |
+
from matplotlib import cm
|
| 53 |
+
import numpy as np
|
| 54 |
+
import matplotlib.pyplot as plt
|
| 55 |
+
from sklearn.decomposition import PCA
|
| 56 |
+
from mpl_toolkits.mplot3d import Axes3D
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def sample_points_on_sphere(num_points=80):
|
| 60 |
+
points = []
|
| 61 |
+
phi = (1 + math.sqrt(5)) / 2 # golden ratio
|
| 62 |
+
|
| 63 |
+
for i in range(num_points):
|
| 64 |
+
theta = 2 * math.pi * i / phi # azimuthal angle
|
| 65 |
+
z = 1 - (2 * i + 1) / num_points # z-coordinate, uniform from -1 to 1
|
| 66 |
+
radius = math.sqrt(1 - z * z) # radius for the xy-plane
|
| 67 |
+
x = radius * math.cos(theta)
|
| 68 |
+
y = radius * math.sin(theta)
|
| 69 |
+
points.append([x, y, z])
|
| 70 |
+
|
| 71 |
+
return torch.tensor(points, dtype=torch.float32)
|
| 72 |
+
|
| 73 |
+
def get_cube_vertices():
|
| 74 |
+
# Cube vertices (8 vertices)
|
| 75 |
+
return torch.tensor([[1, 1, 1],
|
| 76 |
+
[1, 1, -1],
|
| 77 |
+
[1, -1, 1],
|
| 78 |
+
[1, -1, -1],
|
| 79 |
+
[-1, 1, 1],
|
| 80 |
+
[-1, 1, -1],
|
| 81 |
+
[-1, -1, 1],
|
| 82 |
+
[-1, -1, -1]], dtype=torch.float32) # Ensure float type
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def render(meshes,scale=3.0,image_size=(420,420),light=(0.3,0.3,0.3)):
|
| 86 |
+
# prepare the camera
|
| 87 |
+
num_views = 8
|
| 88 |
+
# Get the cube vertices
|
| 89 |
+
#cube_vertices = get_cube_vertices()*scale
|
| 90 |
+
cube_vertices = sample_points_on_sphere(num_views)*scale
|
| 91 |
+
#up = torch.randn(1, 3)
|
| 92 |
+
up=torch.tensor([[0.0, 0.0, 1.0]], dtype=torch.float32)
|
| 93 |
+
up = up / torch.norm(up, dim=1)[:, None]
|
| 94 |
+
R, T = look_at_view_transform(eye=cube_vertices, at=torch.tensor([[0.0, 0.0, 0.0]], dtype=torch.float32), up=up)
|
| 95 |
+
cam_K= np.array([[572, 0.0, image_size[0]//2], [0.0, 572, image_size[1]//2], [0.0, 0.0, 1.0]])
|
| 96 |
+
fx,_,cx,_,fy,cy,_,_,_=cam_K.reshape(9)
|
| 97 |
+
fov_x, fov_y = _compute_fov(cam_K, 420, 420)
|
| 98 |
+
|
| 99 |
+
cameras = PerspectiveCameras(device=device, R=R, T=T, image_size=((420,420),),
|
| 100 |
+
focal_length=torch.tensor([[fx, fy]], dtype=torch.float32),
|
| 101 |
+
principal_point=torch.tensor([[cx, cy]], dtype=torch.float32),
|
| 102 |
+
in_ndc=False)
|
| 103 |
+
|
| 104 |
+
# prepare the lights
|
| 105 |
+
raster_settings = RasterizationSettings(image_size=image_size)
|
| 106 |
+
lights = PointLights(location=torch.tensor([0.0, 1.0, -2.0], device=device)[None], ambient_color=(light,),diffuse_color=(light,),device=device)
|
| 107 |
+
|
| 108 |
+
# move the data to the device
|
| 109 |
+
meshes = meshes.to(device)
|
| 110 |
+
cameras = cameras.to(device)
|
| 111 |
+
if len(cameras) != 1 and len(cameras) % len(meshes) != 0:
|
| 112 |
+
raise ValueError("Mismatch between batch dims of cameras and meshes.")
|
| 113 |
+
if len(cameras) > 1:
|
| 114 |
+
meshes = meshes.extend(len(cameras) // len(meshes))
|
| 115 |
+
|
| 116 |
+
# prepare the renderer
|
| 117 |
+
class MeshRendererWithDepth(torch.nn.Module):
|
| 118 |
+
def __init__(self, rasterizer, shader):
|
| 119 |
+
super().__init__()
|
| 120 |
+
self.rasterizer = rasterizer
|
| 121 |
+
self.shader = shader
|
| 122 |
+
|
| 123 |
+
def forward(self, meshes_world, **kwargs) -> torch.Tensor:
|
| 124 |
+
fragments = self.rasterizer(meshes_world, **kwargs)
|
| 125 |
+
images = self.shader(fragments, meshes_world, **kwargs)
|
| 126 |
+
return images, fragments.zbuf
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
blend_params = BlendParams(background_color=(0.0, 0.0, 0.0)) # Blue background
|
| 130 |
+
renderer = MeshRendererWithDepth(
|
| 131 |
+
rasterizer=MeshRasterizer(
|
| 132 |
+
cameras=cameras,
|
| 133 |
+
raster_settings=raster_settings,
|
| 134 |
+
),
|
| 135 |
+
# Set background color to blue [R, G, B]
|
| 136 |
+
|
| 137 |
+
shader=HardPhongShader(
|
| 138 |
+
device=device,
|
| 139 |
+
cameras=cameras,
|
| 140 |
+
lights=lights,
|
| 141 |
+
blend_params=blend_params
|
| 142 |
+
)
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
images,fragments = renderer(meshes)
|
| 146 |
+
return images,fragments,cameras
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def render_batch(meshes,scale=3.0,image_size=(420,420),light=(0.3,0.3,0.3)):
|
| 150 |
+
# prepare the camera
|
| 151 |
+
num_views = 8
|
| 152 |
+
# Get the cube vertices
|
| 153 |
+
cube_vertices = get_cube_vertices()*scale
|
| 154 |
+
#cube_vertices = sample_points_on_sphere(num_views)*scale
|
| 155 |
+
up = torch.randn(1, 3)
|
| 156 |
+
# up=torch.tensor([[0.0, 0.0, 1.0]], dtype=torch.float32)
|
| 157 |
+
up = up / torch.norm(up, dim=1)[:, None]
|
| 158 |
+
R, T = look_at_view_transform(eye=cube_vertices, at=torch.tensor([[0.0, 0.0, 0.0]], dtype=torch.float32), up=up)
|
| 159 |
+
|
| 160 |
+
cam_K= np.array([[572, 0.0, image_size[0]//2], [0.0, 572, image_size[1]//2], [0.0, 0.0, 1.0]])
|
| 161 |
+
fx,_,cx,_,fy,cy,_,_,_=cam_K.reshape(9)
|
| 162 |
+
fov_x, fov_y = _compute_fov(cam_K, 420, 420)
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
# prepare the renderer
|
| 166 |
+
class MeshRendererWithDepth(torch.nn.Module):
|
| 167 |
+
def __init__(self, rasterizer, shader):
|
| 168 |
+
super().__init__()
|
| 169 |
+
self.rasterizer = rasterizer
|
| 170 |
+
self.shader = shader
|
| 171 |
+
|
| 172 |
+
def forward(self, meshes_world, **kwargs) -> torch.Tensor:
|
| 173 |
+
fragments = self.rasterizer(meshes_world, **kwargs)
|
| 174 |
+
images = self.shader(fragments, meshes_world, **kwargs)
|
| 175 |
+
return images, fragments.zbuf
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
blend_params = BlendParams(background_color=(0.0, 0.0, 0.0)) # Blue background
|
| 179 |
+
|
| 180 |
+
batch_size = 10
|
| 181 |
+
all_images=[]
|
| 182 |
+
all_fragments=[]
|
| 183 |
+
|
| 184 |
+
# move the data to the device
|
| 185 |
+
meshes = meshes.extend(batch_size).to(device)
|
| 186 |
+
for i in range(0,R.shape[0],batch_size):
|
| 187 |
+
R_batch = R[i:i+batch_size]
|
| 188 |
+
T_batch = T[i:i+batch_size]
|
| 189 |
+
cameras_batch = PerspectiveCameras(device=device, R=R_batch, T=T_batch, image_size=((420,420),),
|
| 190 |
+
focal_length=torch.tensor([[fx, fy]], dtype=torch.float32),
|
| 191 |
+
principal_point=torch.tensor([[cx, cy]], dtype=torch.float32),
|
| 192 |
+
in_ndc=False).to(device)
|
| 193 |
+
|
| 194 |
+
# prepare the lights
|
| 195 |
+
raster_settings = RasterizationSettings(image_size=image_size)
|
| 196 |
+
lights = PointLights(location=torch.tensor([0.0, 1.0, -2.0], device=device)[None],
|
| 197 |
+
ambient_color=(light,),diffuse_color=(light,),device=device)
|
| 198 |
+
|
| 199 |
+
renderer = MeshRendererWithDepth(
|
| 200 |
+
rasterizer=MeshRasterizer(
|
| 201 |
+
cameras=cameras_batch,
|
| 202 |
+
raster_settings=raster_settings,
|
| 203 |
+
),
|
| 204 |
+
# Set background color to blue [R, G, B]
|
| 205 |
+
shader=HardPhongShader(
|
| 206 |
+
device=device,
|
| 207 |
+
cameras=cameras_batch,
|
| 208 |
+
lights=lights,
|
| 209 |
+
blend_params=blend_params
|
| 210 |
+
)
|
| 211 |
+
)
|
| 212 |
+
images,fragments = renderer(meshes)
|
| 213 |
+
all_images.append(images)
|
| 214 |
+
all_fragments.append(fragments)
|
| 215 |
+
all_images = torch.cat(all_images,dim=0)
|
| 216 |
+
all_fragments = torch.cat(all_fragments,dim=0)
|
| 217 |
+
cameras = PerspectiveCameras(device=device, R=R, T=T, image_size=((420,420),),
|
| 218 |
+
focal_length=torch.tensor([[fx, fy]], dtype=torch.float32),
|
| 219 |
+
principal_point=torch.tensor([[cx, cy]], dtype=torch.float32),
|
| 220 |
+
in_ndc=False).to(device)
|
| 221 |
+
return all_images,all_fragments,cameras
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def fuse_feature_rgbd(extractor,images,fragments,cameras):
|
| 225 |
+
dino_feat_masked_list = []
|
| 226 |
+
feature_point_cloud_list = []
|
| 227 |
+
for i in range(images.shape[0]):
|
| 228 |
+
image = images.cpu().numpy()[i, :, :, :3]
|
| 229 |
+
image_mask = images[i, ..., 3].cpu().numpy()!=0
|
| 230 |
+
crop_size = (420, 420)
|
| 231 |
+
crop_image, crop_mask, bbox = center_crop(image, image_mask, crop_size)
|
| 232 |
+
cropped_image_np = cv2.resize(crop_image, crop_size, interpolation=cv2.INTER_AREA)
|
| 233 |
+
#cropped_mask = cv2.resize(crop_mask*1.0, crop_size, interpolation=cv2.INTER_NEAREST)!=0 # Use nearest neighbor interpolation for masks
|
| 234 |
+
orignal_size = (int(bbox[2]-bbox[0]), int(bbox[3]-bbox[1])) #K,K
|
| 235 |
+
|
| 236 |
+
to_tensor = transforms.ToTensor()
|
| 237 |
+
input_image = to_tensor(cropped_image_np).cuda()
|
| 238 |
+
input_image = input_image.unsqueeze(0)
|
| 239 |
+
#input_image=extractor.preprocess_pil(input_image)
|
| 240 |
+
mean = torch.tensor([0.485, 0.456, 0.406]).cuda()
|
| 241 |
+
std = torch.tensor([0.229, 0.224, 0.225]).cuda()
|
| 242 |
+
input_image = (input_image - mean[None, :, None, None]) / std[None, :, None, None]
|
| 243 |
+
|
| 244 |
+
_desc_q = extractor.extract_descriptors(input_image,layer=11,include_cls=True).squeeze(1) # (1,900,384)
|
| 245 |
+
#_desc_q = extractor.forward_features(input_image)["x_prenorm"][:, :] # (1,900,384)
|
| 246 |
+
#_desc_q = extractor.extract_descriptors(input_image,layer=11,facet='token',include_cls=True).squeeze(1) # B,L,C
|
| 247 |
+
# _norm_q = torch.linalg.norm(_desc_q, dim=-1)[:, :, None]
|
| 248 |
+
# _desc_q = _desc_q / (_norm_q)
|
| 249 |
+
|
| 250 |
+
desc = _desc_q[:,1:,:][None]
|
| 251 |
+
#cls_token_q = _desc_q[:,0,:] #B,C`
|
| 252 |
+
|
| 253 |
+
input_mask = to_tensor(crop_mask).cuda()
|
| 254 |
+
input_mask = input_mask.unsqueeze(0)
|
| 255 |
+
|
| 256 |
+
img_mask = to_tensor(image_mask)
|
| 257 |
+
|
| 258 |
+
img_mask = img_mask.permute(1,2,0)
|
| 259 |
+
|
| 260 |
+
dino_feat = patch2pixel_feats(desc, original_size=orignal_size) #reize back to K,K =>( K, K, 384)
|
| 261 |
+
# create dino-feat with orignal size
|
| 262 |
+
dino_height, dino_width, feat_dim = (image_size[0],image_size[1], desc.shape[-1])
|
| 263 |
+
dino_feat_orig = torch.zeros(dino_height,dino_width,feat_dim)
|
| 264 |
+
# Fill the dino features into the original tensor at the specified bounding box
|
| 265 |
+
dino_feat_orig[bbox[1]:bbox[3], bbox[0]:bbox[2],:] = dino_feat #reize back to K,K =>(420, 420, 384) #gradint is not supported for this operation
|
| 266 |
+
# Apply the mask
|
| 267 |
+
dino_feat_masked = dino_feat_orig * img_mask
|
| 268 |
+
dino_feat_masked = dino_feat_masked.permute(2,0,1).unsqueeze(0)
|
| 269 |
+
dino_feat_masked_low = F.interpolate(dino_feat_masked, size=(30, 30), mode='bilinear')
|
| 270 |
+
|
| 271 |
+
image_mask = images[i, ..., 3][None,None]
|
| 272 |
+
depth_image = fragments[i, ..., 0][None]*image_mask
|
| 273 |
+
|
| 274 |
+
# # Define the kernel for erosion (3x3 ones kernel)
|
| 275 |
+
# kernel = torch.ones((1, 1, 5, 5), dtype=torch.float).cuda()
|
| 276 |
+
# # Number of erosion iterations
|
| 277 |
+
# iterations = 5
|
| 278 |
+
|
| 279 |
+
# # Perform iterative erosion
|
| 280 |
+
# for i in range(iterations):
|
| 281 |
+
# # Apply erosion using 2D convolution
|
| 282 |
+
# eroded_mask = F.conv2d(image_mask, kernel, padding=2)
|
| 283 |
+
# image_mask = (eroded_mask == kernel.sum()).float() # Update mask to eroded version
|
| 284 |
+
|
| 285 |
+
feature_point_cloud = get_rgbd_point_cloud(cameras[i], dino_feat_masked.to(device), depth_map=depth_image,mask=image_mask)#everthing on GPU
|
| 286 |
+
|
| 287 |
+
index = np.random.choice(feature_point_cloud.points_list()[0].shape[0], 4096, replace=True)
|
| 288 |
+
points = feature_point_cloud.points_list()[0].detach().cpu()[index,:]
|
| 289 |
+
colors = feature_point_cloud.features_list()[0].detach().cpu()[index,:]
|
| 290 |
+
# points = feature_point_cloud.points_list()[0].detach().cpu()[:,:]
|
| 291 |
+
# colors = feature_point_cloud.features_list()[0].detach().cpu()[:,:]
|
| 292 |
+
feature_point_cloud = torch.cat((points, colors), dim=1)
|
| 293 |
+
|
| 294 |
+
dino_feat_masked_list.append(dino_feat_masked_low.detach().cpu())
|
| 295 |
+
feature_point_cloud_list.append(feature_point_cloud)
|
| 296 |
+
feature_point_cloud = torch.cat(feature_point_cloud_list, dim=0)
|
| 297 |
+
dino_feat_masked = torch.cat(dino_feat_masked_list, dim=0)
|
| 298 |
+
return feature_point_cloud,dino_feat_masked, feature_point_cloud_list
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
def downsample_with_knn_feature_aggregation(feature_point_cloud,num_pts=1024,k_nearest_neighbors=100, instance_points=None):
|
| 302 |
+
#N_1, C_1 = 2048, 384 # Example number of points and features
|
| 303 |
+
num_points_to_sample = num_pts
|
| 304 |
+
k_nearest_neighbors = k_nearest_neighbors
|
| 305 |
+
|
| 306 |
+
# Example input pointcloud and features (N_1, C_1), where N_1 is the number of points and C_1 is the feature dimension
|
| 307 |
+
pointcloud = feature_point_cloud[None,:,:3].cuda() # Shape (1, N_1, 3) for 3D coordinates
|
| 308 |
+
features = feature_point_cloud[None,:,3:].cuda() # Shape (1, N_1, C_1) for features
|
| 309 |
+
|
| 310 |
+
# Step 1: FPS to downsample the points
|
| 311 |
+
# We use sample_farthest_points to select num_points_to_sample points
|
| 312 |
+
sampled_points, sampled_indices = sample_farthest_points(pointcloud, K=num_points_to_sample) # Shape: (1, 1024, 3), (1, 1024)
|
| 313 |
+
if instance_points is not None:
|
| 314 |
+
sampled_points = instance_points
|
| 315 |
+
|
| 316 |
+
# Step 2: KNN to find nearest neighbors
|
| 317 |
+
# Find the k nearest neighbors for each sampled point in the original pointcloud
|
| 318 |
+
dists, knn_indices, _ = knn_points(sampled_points, pointcloud, K=k_nearest_neighbors, return_nn=False)
|
| 319 |
+
|
| 320 |
+
# Step 3: Gather the features of the k-nearest neighbors using the knn indices
|
| 321 |
+
# Use knn_gather to get neighbor features for each sampled point
|
| 322 |
+
neighbor_features = knn_gather(features, knn_indices) # Shape: (1, 1024, k, C_1)
|
| 323 |
+
|
| 324 |
+
# Step 4: Aggregate features from the neighbors (e.g., by averaging)
|
| 325 |
+
#aggregated_features,_ = torch.max(neighbor_features,dim=-2) # Shape: (1, 1024, C_1)
|
| 326 |
+
aggregated_features = torch.mean(neighbor_features,dim=-2) # Shape: (1, 1024, C_1)
|
| 327 |
+
return sampled_points, aggregated_features
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
def vis_pca(feature):
|
| 331 |
+
n_components=3 # the first component is to seperate the object from the background
|
| 332 |
+
|
| 333 |
+
pca = sklearnPCA(n_components=n_components)
|
| 334 |
+
feature = pca.fit_transform(feature.detach().cpu().numpy())
|
| 335 |
+
for show_channel in range(n_components):
|
| 336 |
+
# min max normalize the feature map
|
| 337 |
+
feature[:, show_channel] = (feature[:, show_channel] - feature[:, show_channel].mean()) / (feature[:, show_channel].std()*10)
|
| 338 |
+
feature_resized = np.clip(feature[:,:]+0.5,0,1)
|
| 339 |
+
return feature_resized
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
def patch2pixel_feats(patch_features, original_size):
|
| 343 |
+
# Calculate the number of patches along each dimension
|
| 344 |
+
num_patches = int(math.sqrt(patch_features.shape[2]))
|
| 345 |
+
|
| 346 |
+
batch_num = patch_features.shape[0]
|
| 347 |
+
feat_dim = patch_features.shape[3]
|
| 348 |
+
patch_features = patch_features.reshape(batch_num, num_patches, num_patches, feat_dim)
|
| 349 |
+
patch_features = patch_features.permute(0,3,1,2)
|
| 350 |
+
|
| 351 |
+
pixel_features = F.interpolate(patch_features, size=(original_size[0], original_size[1]), mode='bilinear')
|
| 352 |
+
pixel_features = pixel_features.squeeze().permute(1,2,0)
|
| 353 |
+
|
| 354 |
+
return pixel_features
|
| 355 |
+
|
| 356 |
+
def vis_pca_pixelwise(feature):
|
| 357 |
+
n_components = 4 # The number of PCA components to use
|
| 358 |
+
batch, feat_dim, height,width = feature.shape
|
| 359 |
+
|
| 360 |
+
# Reshape the feature to (num_pixels, feat_dim)
|
| 361 |
+
num_pixels = height * width
|
| 362 |
+
feature_reshaped = np.array(feature).transpose(0,2,3,1).reshape(-1, feat_dim)
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
# Apply PCA
|
| 366 |
+
pca = sklearnPCA(n_components=n_components)
|
| 367 |
+
feature_pca = pca.fit_transform(feature_reshaped)
|
| 368 |
+
|
| 369 |
+
# Min-max normalization for each component
|
| 370 |
+
# for show_channel in range(n_components):
|
| 371 |
+
# feature_pca[:, show_channel] = (feature_pca[:, show_channel] - feature_pca[:, show_channel].min()) / \
|
| 372 |
+
# (feature_pca[:, show_channel].max() - feature_pca[:, show_channel].min() + 1e-8) # Small epsilon to avoid division by zero
|
| 373 |
+
for show_channel in range(n_components):
|
| 374 |
+
feature_pca[:, show_channel] = (feature_pca[:, show_channel] - feature_pca[:, show_channel].mean()) / \
|
| 375 |
+
(feature_pca[:, show_channel].std()*10 + 1e-8) # Small epsilon to avoid division by zero
|
| 376 |
+
|
| 377 |
+
feature_pca = np.clip(feature_pca+0.5, 0, 1)
|
| 378 |
+
# Reshape the PCA result back to (height, width, n_components)
|
| 379 |
+
feature_resized = feature_pca.reshape(batch,height,width,n_components)[...,1:4]
|
| 380 |
+
return feature_resized
|
| 381 |
+
|
| 382 |
+
def normalize_mesh_verts(data):
|
| 383 |
+
# data [N, 3]
|
| 384 |
+
min_vals, _ = torch.min(data, dim=0)
|
| 385 |
+
max_vals, _ = torch.max(data, dim=0)
|
| 386 |
+
bbox_sizes = max_vals - min_vals
|
| 387 |
+
scale = torch.norm(bbox_sizes)
|
| 388 |
+
print("Scale:", scale)
|
| 389 |
+
normalized_verts = verts / scale
|
| 390 |
+
return normalized_verts
|
| 391 |
+
|
| 392 |
+
def plot_pointclouds_with_color_mapping(pc1_f, pc2_f,pc1,pc2, query_points, similarity_threshold=None):
|
| 393 |
+
"""
|
| 394 |
+
Visualizes two 3D point clouds. The second point cloud (pc2) is color-mapped
|
| 395 |
+
using the 'viridis' colormap based on its similarity (proximity) to the sampled
|
| 396 |
+
query points in the first point cloud (pc1).
|
| 397 |
+
|
| 398 |
+
Parameters:
|
| 399 |
+
- pc1: np.ndarray of shape (N, 3), first point cloud #partial
|
| 400 |
+
- pc2: np.ndarray of shape (M, 3), second point cloud # global
|
| 401 |
+
- query_points: list of indices in pc1, representing the query points to compare.
|
| 402 |
+
- similarity_threshold: float, optional, threshold to cap the similarity distance.
|
| 403 |
+
"""
|
| 404 |
+
|
| 405 |
+
|
| 406 |
+
pc1_f = pc1_f / np.linalg.norm(pc1_f, axis=1)[:, None] # Normalize the features
|
| 407 |
+
pc2_f = pc2_f / np.linalg.norm(pc2_f, axis=1)[:, None] # Normalize the features
|
| 408 |
+
# Create a figure with subplots
|
| 409 |
+
fig = plt.figure(figsize=(12, 10))
|
| 410 |
+
num_query_points = len(query_points)
|
| 411 |
+
# Set limits and labels
|
| 412 |
+
size = pc2.max() - pc2.min()
|
| 413 |
+
# Plot the first point cloud in the first subplot
|
| 414 |
+
ax1 = fig.add_subplot(1, num_query_points + 1, 1, projection='3d')
|
| 415 |
+
ax1.scatter(pc2[:, 0], pc2[:, 1], pc2[:, 2], color='grey', label='Point Cloud 1 (Left)', alpha=0.1,s=10)
|
| 416 |
+
|
| 417 |
+
# Define a color list for each query point
|
| 418 |
+
query_colors = cm.tab10(np.linspace(0, 1, num_query_points)) # Use tab10 colormap for distinct colors
|
| 419 |
+
|
| 420 |
+
# Highlight query points in pc1 with different colors
|
| 421 |
+
for i, idx in enumerate(query_points):
|
| 422 |
+
ax1.scatter(pc1[idx, 0], pc1[idx, 1], pc1[idx, 2],
|
| 423 |
+
color=query_colors[i], s=100, edgecolor='k', label=f'Query Point {idx}')
|
| 424 |
+
|
| 425 |
+
ax1.set_title('Point Cloud 1 with Query Points')
|
| 426 |
+
ax1.set_xlabel('X')
|
| 427 |
+
ax1.set_ylabel('Y')
|
| 428 |
+
ax1.set_zlabel('Z')
|
| 429 |
+
ax1.set_xlim(-size / 1.4, size / 1.4)
|
| 430 |
+
ax1.set_ylim(-size / 1.4, size / 1.4)
|
| 431 |
+
ax1.set_zlim(-size / 1.4, size / 1.4)
|
| 432 |
+
ax1.view_init(elev=45, azim=-45)
|
| 433 |
+
ax1.grid(True)
|
| 434 |
+
ax1.legend()
|
| 435 |
+
|
| 436 |
+
# Plot the second point cloud in the subsequent subplots
|
| 437 |
+
for k in range(num_query_points):
|
| 438 |
+
|
| 439 |
+
ax = fig.add_subplot(1, num_query_points + 1, k + 2, projection='3d')
|
| 440 |
+
|
| 441 |
+
# Calculate distances between query points in pc1 and all points in pc2
|
| 442 |
+
similarity =(pc1_f[query_points[k]][None]@ pc2_f.T).reshape(-1) # (1, 3) x (M, 3) = (1, M)
|
| 443 |
+
# For each point in pc2, take the minimum distance to any query point
|
| 444 |
+
min_similarity = np.min(similarity, axis=0)
|
| 445 |
+
# Optionally cap the similarity distances to a threshold (to avoid extreme values)
|
| 446 |
+
similarity_threshold= 0.3
|
| 447 |
+
if similarity_threshold is not None:
|
| 448 |
+
similarity = np.clip(similarity, similarity_threshold,1)
|
| 449 |
+
# Normalize the distances to a range of 0 to 1 for colormap mapping
|
| 450 |
+
similarity = (similarity - np.min(similarity)) / (np.max(similarity) - np.min(similarity))
|
| 451 |
+
colors = cm.plasma(similarity)
|
| 452 |
+
|
| 453 |
+
# Plot the second point cloud with color mapping based on similarity
|
| 454 |
+
ax.scatter(pc2[:, 0], pc2[:, 1], pc2[:, 2], color=colors, s=15, alpha=1.0, label='Point Cloud 2 (Right)', edgecolor='k')
|
| 455 |
+
|
| 456 |
+
ax.set_xlim(-size / 1.4, size / 1.4)
|
| 457 |
+
ax.set_ylim(-size / 1.4, size / 1.4)
|
| 458 |
+
ax.set_zlim(-size / 1.4, size / 1.4)
|
| 459 |
+
ax.set_title(f'QP_{query_points[k]}')
|
| 460 |
+
ax.set_xlabel('X')
|
| 461 |
+
ax.set_ylabel('Y')
|
| 462 |
+
ax.set_zlabel('Z')
|
| 463 |
+
ax.view_init(elev=45, azim=-45)
|
| 464 |
+
ax.grid(True)
|
| 465 |
+
ax.legend()
|
| 466 |
+
|
| 467 |
+
# Show the plot
|
| 468 |
+
plt.tight_layout()
|
| 469 |
+
plt.show()
|
| 470 |
+
|
| 471 |
+
|
| 472 |
+
def plot_pointclouds_3d_with_copca_old(global_sem_pcd, partial_sem_pcd, global_pcd, partial_pcd):
|
| 473 |
+
"""
|
| 474 |
+
Visualizes two point clouds in 3D, coloring them based on their PCA components.
|
| 475 |
+
|
| 476 |
+
Parameters:
|
| 477 |
+
- global_pointcloud: numpy array of shape (N, D) for global point cloud.
|
| 478 |
+
- partial_pointcloud: numpy array of shape (M, D) for partial point cloud.
|
| 479 |
+
"""
|
| 480 |
+
|
| 481 |
+
|
| 482 |
+
n_components = 3
|
| 483 |
+
# Step 1: Perform PCA on both global and partial point clouds
|
| 484 |
+
sem_pca = PCA(n_components=n_components)
|
| 485 |
+
sem_pca = sem_pca.fit(global_sem_pcd) # shape (N+M, 3)
|
| 486 |
+
|
| 487 |
+
transformed_sem_pcd_list = [sem_pca.transform(pcd) for pcd in [global_sem_pcd,partial_sem_pcd]]
|
| 488 |
+
sem_pcd_pca = np.concatenate(transformed_sem_pcd_list,axis=0)
|
| 489 |
+
for show_channel in range(n_components):
|
| 490 |
+
sem_pcd_pca[:, show_channel] = (sem_pcd_pca[:, show_channel] - sem_pcd_pca[:, show_channel].mean()) / \
|
| 491 |
+
(sem_pcd_pca[:, show_channel].std()*5 + 1e-8) # Small epsilon to avoid division by zero
|
| 492 |
+
|
| 493 |
+
# sem_pcd_pca_min = sem_pcd_pca.min()
|
| 494 |
+
# sem_pcd_pca_max = sem_pcd_pca.max()
|
| 495 |
+
# sem_pcd_pca = (sem_pcd_pca- sem_pcd_pca_min) / (sem_pcd_pca_max - sem_pcd_pca_min) # Normalize to [0, 1]
|
| 496 |
+
|
| 497 |
+
sem_pcd_pca = np.clip(sem_pcd_pca[:,:]+0.5, 0, 1)
|
| 498 |
+
global_pca = sem_pcd_pca[:global_sem_pcd.shape[0]] # shape (N, 3)
|
| 499 |
+
partial_pca = sem_pcd_pca[-partial_sem_pcd.shape[0]:] # shape (M, 3)
|
| 500 |
+
|
| 501 |
+
# Step 2: Create a 3D scatter plot
|
| 502 |
+
fig = plt.figure(figsize=(12, 6))
|
| 503 |
+
ax = fig.add_subplot(121, projection='3d')
|
| 504 |
+
|
| 505 |
+
|
| 506 |
+
# Global point cloud
|
| 507 |
+
ax.scatter(global_pcd[:, 0], global_pcd[:, 1], global_pcd[:, 2],
|
| 508 |
+
c=global_pca, marker='o', s=100, alpha=1.0, label='Global Point Cloud')
|
| 509 |
+
|
| 510 |
+
# Set labels for each axis
|
| 511 |
+
# ax.set_xlabel('X axis')
|
| 512 |
+
# ax.set_ylabel('Y axis')
|
| 513 |
+
# ax.set_zlabel('Z axis')
|
| 514 |
+
ax.set_xlim(-0.5, 0.5)
|
| 515 |
+
ax.set_ylim(-0.5, 0.5)
|
| 516 |
+
ax.set_zlim(-0.5, 0.5)
|
| 517 |
+
|
| 518 |
+
ax1 = fig.add_subplot(122, projection='3d')
|
| 519 |
+
|
| 520 |
+
# Partial point cloud
|
| 521 |
+
ax1.scatter(partial_pcd[:, 0], partial_pcd[:, 1], partial_pcd[:, 2],
|
| 522 |
+
c=partial_pca, marker='o', s=100, alpha=1.0, label='Partial Point Cloud')
|
| 523 |
+
|
| 524 |
+
# ax1.scatter(global_pcd[:, 0], global_pcd[:, 1], global_pcd[:, 2],
|
| 525 |
+
# marker='o', s=10, alpha=0.1)
|
| 526 |
+
# Set labels for each axis
|
| 527 |
+
# ax1.set_xlabel('X axis')
|
| 528 |
+
# ax1.set_ylabel('Y axis')
|
| 529 |
+
# ax1.set_zlabel('Z axis')
|
| 530 |
+
|
| 531 |
+
|
| 532 |
+
ax1.set_xlim(-0.5, 0.5)
|
| 533 |
+
ax1.set_ylim(-0.5, 0.5)
|
| 534 |
+
ax1.set_zlim(-0.5, 0.5)
|
| 535 |
+
plt.tight_layout()
|
| 536 |
+
|
| 537 |
+
ax.view_init(120,-95)
|
| 538 |
+
ax1.view_init(120,-95)
|
| 539 |
+
|
| 540 |
+
|
| 541 |
+
ax.set_axis_off()
|
| 542 |
+
ax.set_facecolor((0, 0, 0, 0))
|
| 543 |
+
ax1.set_axis_off()
|
| 544 |
+
ax1.set_facecolor((0, 0, 0, 0))
|
| 545 |
+
|
| 546 |
+
plt.show()
|
| 547 |
+
|
| 548 |
+
|
| 549 |
+
def plot_pointclouds_3d_with_pca(global_sem_pcd, global_pcd):
|
| 550 |
+
"""
|
| 551 |
+
Visualizes two point clouds in 3D, coloring them based on their PCA components.
|
| 552 |
+
|
| 553 |
+
Parameters:
|
| 554 |
+
- global_pointcloud: numpy array of shape (N, D) for global point cloud.
|
| 555 |
+
- partial_pointcloud: numpy array of shape (M, D) for partial point cloud.
|
| 556 |
+
"""
|
| 557 |
+
#sem_pcd = np.concatenate((global_sem_pcd,partial_sem_pcd), axis=0) # shape (N+M, D)
|
| 558 |
+
|
| 559 |
+
# Step 1: Perform PCA on both global and partial point clouds
|
| 560 |
+
sem_pca = PCA(n_components=3)
|
| 561 |
+
sem_pcd_pca = sem_pca.fit_transform(global_sem_pcd) # shape (N+M, 3)
|
| 562 |
+
|
| 563 |
+
for i in range(3): # Iterate over each component (3 in total for RGB)
|
| 564 |
+
sem_pcd_pca_mean = sem_pcd_pca[:, i].mean()
|
| 565 |
+
sem_pcd_pca_std = sem_pcd_pca[:, i].std()
|
| 566 |
+
sem_pcd_pca[:, i] = (sem_pcd_pca[:, i] - sem_pcd_pca_mean) / (sem_pcd_pca_std*5+1e-8) # Normalize to [0, 1]
|
| 567 |
+
|
| 568 |
+
|
| 569 |
+
global_pca = np.clip(sem_pcd_pca+0.5,0,1)
|
| 570 |
+
# scatter plot
|
| 571 |
+
fig = plt.figure(figsize=(6, 6))
|
| 572 |
+
ax = fig.add_subplot(111, projection='3d')
|
| 573 |
+
|
| 574 |
+
# Global point cloud
|
| 575 |
+
ax.scatter(global_pcd[:, 0], global_pcd[:, 1], global_pcd[:, 2],
|
| 576 |
+
c=global_pca, marker='o', s=50, alpha=1.0, label='Global Point Cloud')
|
| 577 |
+
|
| 578 |
+
# Remove axes and background
|
| 579 |
+
ax.set_axis_off()
|
| 580 |
+
|
| 581 |
+
# Set background color to none
|
| 582 |
+
ax.set_facecolor((0, 0, 0, 0))
|
| 583 |
+
# # Set labels for each axis
|
| 584 |
+
# ax.set_xlabel('X axis')
|
| 585 |
+
# ax.set_ylabel('Y axis')
|
| 586 |
+
# ax.set_zlabel('Z axis')
|
| 587 |
+
ax.set_xlim(-0.5, 0.5)
|
| 588 |
+
ax.set_ylim(-0.5, 0.5)
|
| 589 |
+
ax.set_zlim(-0.5, 0.5)
|
| 590 |
+
|
| 591 |
+
ax.view_init(-73,102)
|
| 592 |
+
|
| 593 |
+
return fig
|
| 594 |
+
|
| 595 |
+
|
| 596 |
+
def plot_pointclouds_3d_with_copca(global_sem_pcd_list, global_pcd_list,co_pca=True):
|
| 597 |
+
"""
|
| 598 |
+
Visualizes multiple point clouds in 3D, each in a separate subplot, after applying CoPCA.
|
| 599 |
+
Coloring them based on their PCA components.
|
| 600 |
+
|
| 601 |
+
Parameters:
|
| 602 |
+
- global_sem_pcd_list: list of numpy arrays for semantic point clouds (one per object).
|
| 603 |
+
- global_pcd_list: list of numpy arrays for global point clouds (one per object).
|
| 604 |
+
"""
|
| 605 |
+
num_pcds = len(global_sem_pcd_list) # Number of point clouds
|
| 606 |
+
print("Number of point clouds to visualize:", num_pcds)
|
| 607 |
+
# Step 1: Perform CoPCA (Common PCA) on the semantic point clouds
|
| 608 |
+
# Concatenate all point clouds to perform common PCA
|
| 609 |
+
if co_pca:
|
| 610 |
+
concatenated_pcds = np.concatenate(global_sem_pcd_list, axis=0) # shape (N_total, D)
|
| 611 |
+
copca = PCA(n_components=3, random_state=0)
|
| 612 |
+
copca.fit(concatenated_pcds[:1024]) # Fit PCA on all point clouds together
|
| 613 |
+
transformed_sem_pcd_list = [copca.transform(pcd) for pcd in global_sem_pcd_list]
|
| 614 |
+
|
| 615 |
+
|
| 616 |
+
signs = np.sign(np.sum(transformed_sem_pcd_list[0], axis=0))
|
| 617 |
+
# Post-process to ensure consistent orientation of PCA components
|
| 618 |
+
for i, transformed_pcd in enumerate(transformed_sem_pcd_list):
|
| 619 |
+
# For each component (column), align sign based on the sum of values in the column
|
| 620 |
+
transformed_sem_pcd_list[i] = transformed_pcd * signs
|
| 621 |
+
else:
|
| 622 |
+
copca = PCA(n_components=3)
|
| 623 |
+
transformed_sem_pcd_list = [copca.fit_transform(pcd) for pcd in global_sem_pcd_list]
|
| 624 |
+
# Post-process to ensure consistent orientation of PCA components
|
| 625 |
+
for i, transformed_pcd in enumerate(transformed_sem_pcd_list):
|
| 626 |
+
signs = np.sign(np.sum(transformed_pcd, axis=0))
|
| 627 |
+
# For each component (column), align sign based on the sum of values in the column
|
| 628 |
+
transformed_sem_pcd_list[i] = transformed_pcd * signs
|
| 629 |
+
|
| 630 |
+
|
| 631 |
+
|
| 632 |
+
# Create a figure with subplots arranged in a grid (based on number of point clouds)
|
| 633 |
+
fig = plt.figure(figsize=(6 * num_pcds, 6)) # Adjust figure size based on the number of subplots
|
| 634 |
+
|
| 635 |
+
# Loop over the point clouds
|
| 636 |
+
for idx, (sem_pcd_pca, global_pcd) in enumerate(zip(transformed_sem_pcd_list, global_pcd_list)):
|
| 637 |
+
ax = fig.add_subplot(1, num_pcds, idx + 1, projection='3d')
|
| 638 |
+
|
| 639 |
+
# Step 2: Normalize the PCA-transformed data to use as colors
|
| 640 |
+
for i in range(3): # Iterate over each component (3 in total for RGB)
|
| 641 |
+
pca_mean = sem_pcd_pca[:, i].mean()
|
| 642 |
+
pca_std = sem_pcd_pca[:, i].std()
|
| 643 |
+
sem_pcd_pca[:, i] = (sem_pcd_pca[:, i] - pca_mean) / (pca_std * 5 + 1e-8) # Normalize
|
| 644 |
+
|
| 645 |
+
global_pca_colors = np.clip(sem_pcd_pca + 0.5, 0, 1) # Map to [0, 1] for RGB
|
| 646 |
+
|
| 647 |
+
# Scatter plot for this point cloud in the current subplot
|
| 648 |
+
ax.scatter(global_pcd[:, 0], global_pcd[:, 1], global_pcd[:, 2],
|
| 649 |
+
c=global_pca_colors, marker='o', s=50, alpha=1.0)
|
| 650 |
+
|
| 651 |
+
# Remove axes and background
|
| 652 |
+
ax.set_axis_off()
|
| 653 |
+
ax.set_facecolor((0, 0, 0, 0))
|
| 654 |
+
|
| 655 |
+
# Set axis limits for each subplot
|
| 656 |
+
ax.set_xlim(-0.5, 0.5)
|
| 657 |
+
ax.set_ylim(-0.5, 0.5)
|
| 658 |
+
ax.set_zlim(-0.5, 0.5)
|
| 659 |
+
|
| 660 |
+
# Set view angle
|
| 661 |
+
ax.view_init(-55, 102)
|
| 662 |
+
|
| 663 |
+
# Adjust spacing between subplots
|
| 664 |
+
plt.tight_layout()
|
| 665 |
+
|
| 666 |
+
return fig
|
| 667 |
+
|
| 668 |
+
|
| 669 |
+
|
| 670 |
+
def unnormalize(x):
|
| 671 |
+
# x.shape : [H,W,3]
|
| 672 |
+
mean = np.array([0.485, 0.456, 0.406])
|
| 673 |
+
std = np.array([0.229, 0.224, 0.225])
|
| 674 |
+
return x * std + mean
|
| 675 |
+
|
| 676 |
+
|
| 677 |
+
from custom_utils.housecat6d_dataset import HouseCat6DTrainingDataset
|
| 678 |
+
trainset = HouseCat6DTrainingDataset(image_size=420, sample_num=1024,data_dir='/media/xyz/data1/HouseCat6D')
|
| 679 |
+
|
| 680 |
+
vis = True
|
| 681 |
+
device = "cuda"
|
| 682 |
+
import matplotlib
|
| 683 |
+
import open3d as o3d
|
| 684 |
+
from pytorch3d.io import load_objs_as_meshes
|
| 685 |
+
import trimesh
|
| 686 |
+
matplotlib.use('TkAgg')
|
| 687 |
+
|
| 688 |
+
#cat_list = ['bottle','box','can','cup','cutlery','remote','shoe','tube','teapot']
|
| 689 |
+
cat_list = ['cup']
|
| 690 |
+
|
| 691 |
+
|
| 692 |
+
sem_global_list = []
|
| 693 |
+
sem_global_pcd_list = []
|
| 694 |
+
|
| 695 |
+
# # load semantc feature and show
|
| 696 |
+
# ########################################
|
| 697 |
+
save_dir = 'Yung/yung_large_files/semantic_feature/test_notebook/8v'
|
| 698 |
+
# #save_dir = './80views_textured_token'
|
| 699 |
+
# if True:
|
| 700 |
+
# for cat in cat_list:
|
| 701 |
+
# # # orriginal
|
| 702 |
+
# # with open(f'/mnt/4T/Yung/yung_large_files/semantic_feature/test_notebook/housecat_{cat}/raw/housecat1_train.txt', 'r') as f:
|
| 703 |
+
# # instances = [line.strip() for line in f.readlines()]
|
| 704 |
+
|
| 705 |
+
# # print(instances)
|
| 706 |
+
# # revised
|
| 707 |
+
# # instance try cup-grey_handle
|
| 708 |
+
# instances = ['cup-grey_handle']
|
| 709 |
+
# sem_global_list = []
|
| 710 |
+
# sem_global_pcd_list = []
|
| 711 |
+
|
| 712 |
+
# # Load the mean shape point cloud
|
| 713 |
+
# meanshape_path = f'Yung/yung_large_files/semantic_feature/test_notebook/saved_pcd/{cat}/mean_shape/mean_shape_pcd_1.txt'
|
| 714 |
+
# meanshape_pcd_np = np.loadtxt(meanshape_path)
|
| 715 |
+
|
| 716 |
+
# meanshape_pcd_tensor = torch.from_numpy(meanshape_pcd_np)
|
| 717 |
+
# M = meanshape_pcd_tensor.shape[0]
|
| 718 |
+
# meanshape_points = meanshape_pcd_tensor.view(1, M, 3).float()
|
| 719 |
+
# #make sure map to cuda0
|
| 720 |
+
# average_aggregated_features = torch.load(f'/mnt/4T/Yung/yung_large_files/semantic_feature/test_notebook/8v_key/sem_cat_pcd_untex/{cat}_dino_feature.pt', map_location={"cuda:1": "cuda:0"})
|
| 721 |
+
# sem_global_pcd_list.append(meanshape_points[0])
|
| 722 |
+
# sem_global_list.append(average_aggregated_features[0].detach().cpu())
|
| 723 |
+
# #fig =plot_pointclouds_3d_with_pca(average_aggregated_features[0].detach().cpu(),meanshape_points[0])
|
| 724 |
+
# #fig.savefig('test.png')
|
| 725 |
+
# for j,instance in enumerate(instances):
|
| 726 |
+
# #break
|
| 727 |
+
# print("Processing", instance)
|
| 728 |
+
# #obj_path = f'/media/xyz/data/HouseCat6D/obj_models_small_size_final/{cat}/{instance}.obj'
|
| 729 |
+
# #instance_pcd_tensor = torch.load(f'{save_dir}/saved_pcd_untex/{cat}/{instance}_pcd.pt')[0]
|
| 730 |
+
# #obj_path = f'/media/xyz/data1/HouseCat6D/obj_models_small_size_final/{cat}/{instance}.obj'
|
| 731 |
+
# # instance_pcd_path = f'Yung/yung_large_files/semantic_feature/test_notebook/saved_pcd/{cat}/test/{instance}.txt'
|
| 732 |
+
# # instance_pcd_np = np.loadtxt(instance_pcd_path)
|
| 733 |
+
# instance_pcd_path = f'Yung/yung_large_files/pose_can_results/housecat6d_sonata_feature/scene01/000000/cup-grey_handle/input_pca.ply'
|
| 734 |
+
# pcd = o3d.io.read_point_cloud(instance_pcd_path)
|
| 735 |
+
# instance_pcd_np = np.asarray(pcd.points)
|
| 736 |
+
|
| 737 |
+
# # Rotate 180 degrees around y axis
|
| 738 |
+
# rotation_matrix = np.array([
|
| 739 |
+
# [-1, 0, 0],
|
| 740 |
+
# [0, 1, 0],
|
| 741 |
+
# [0, 0, -1]
|
| 742 |
+
# ])
|
| 743 |
+
# instance_pcd_np = instance_pcd_np @ rotation_matrix.T
|
| 744 |
+
|
| 745 |
+
|
| 746 |
+
# # Load the instance point cloud
|
| 747 |
+
# instance_pcd_tensor = torch.from_numpy(instance_pcd_np)
|
| 748 |
+
# N = instance_pcd_tensor.shape[0]
|
| 749 |
+
# instance_points = instance_pcd_tensor.view(1, N, 3).float()
|
| 750 |
+
# try:
|
| 751 |
+
# # aggregated_features = torch.load(f'{save_dir}/saved_dino_pcd_untex/{cat}/{instance}_dino_feature.pt')
|
| 752 |
+
# aggregated_features = average_aggregated_features
|
| 753 |
+
# except:
|
| 754 |
+
# print(f"Warning: {instance} not found.")
|
| 755 |
+
# continue
|
| 756 |
+
# # plot_pointclouds_3d_with_pca(aggregated_features[0].detach().cpu(),
|
| 757 |
+
# # instance_points[0])
|
| 758 |
+
# sem_global_pcd_list.append(instance_points[0].detach().cpu())
|
| 759 |
+
# sem_global_list.append(aggregated_features[0].detach().cpu())
|
| 760 |
+
# if len(sem_global_list)>4:
|
| 761 |
+
# break
|
| 762 |
+
|
| 763 |
+
# fig = plot_pointclouds_3d_with_copca(sem_global_list,sem_global_pcd_list,co_pca=True)
|
| 764 |
+
# fig.savefig(f'./{save_dir}/{cat}_amodal.png')
|
| 765 |
+
# ###############################
|
| 766 |
+
|
| 767 |
+
|
| 768 |
+
model_dict={'small':'dinov2_vits14',
|
| 769 |
+
'base':'dinov2_vitb14',
|
| 770 |
+
'large':'dinov2_vitl14',
|
| 771 |
+
'giant':'dinov2_vitg14'}
|
| 772 |
+
extractor = ViTExtractor(model_dict['small'],14)
|
| 773 |
+
# use GPPU0
|
| 774 |
+
extractor.model = extractor.model.cuda(0) # the stride of first conv control outputs resolution
|
| 775 |
+
|
| 776 |
+
# extractor = torch.hub.load('facebookresearch/dinov2', model_dict['small'], pretrained=True).cuda()
|
| 777 |
+
|
| 778 |
+
|
| 779 |
+
# cat_list = ['bottle','box','can','cup','cutlery','glass','remote','shoe','tube','teapot']
|
| 780 |
+
cat_list = ['cup']
|
| 781 |
+
|
| 782 |
+
#cat_list = ['teapot']
|
| 783 |
+
#TODO: if condition for tex rendering
|
| 784 |
+
for cat in cat_list:
|
| 785 |
+
# # orriginal
|
| 786 |
+
# with open(f'/mnt/4T/Yung/yung_large_files/semantic_feature/test_notebook/housecat_{cat}/raw/housecat1_train.txt', 'r') as f:
|
| 787 |
+
# instances = [line.strip() for line in f.readlines()]
|
| 788 |
+
|
| 789 |
+
# print(instances)
|
| 790 |
+
#revised
|
| 791 |
+
# instance try cup-grey_handle
|
| 792 |
+
instances = ['cup-grey_handle']
|
| 793 |
+
|
| 794 |
+
aggregated_features_list = [] # N * [1, 1024, 384]
|
| 795 |
+
# Load the mean shape point cloud
|
| 796 |
+
meanshape_path = f'Yung/yung_large_files/semantic_feature/test_notebook/saved_pcd/{cat}/mean_shape/mean_shape_pcd_1.txt'
|
| 797 |
+
meanshape_pcd_np = np.loadtxt(meanshape_path)
|
| 798 |
+
meanshape_pcd_tensor = torch.from_numpy(meanshape_pcd_np)
|
| 799 |
+
M = meanshape_pcd_tensor.shape[0]
|
| 800 |
+
# modify for cuda0
|
| 801 |
+
meanshape_points = meanshape_pcd_tensor.view(1, M, 3).float().cuda(0)
|
| 802 |
+
|
| 803 |
+
|
| 804 |
+
for j,instance in enumerate(instances):
|
| 805 |
+
# #original
|
| 806 |
+
# # if instance != 'bottle-85_alcool':
|
| 807 |
+
# # continue
|
| 808 |
+
# print("Processing", instance)
|
| 809 |
+
# obj_path = f'pose_dataset/HouseCat6D/obj_models_small_size_final/{cat}/{instance}.obj'
|
| 810 |
+
# instance_pcd_path = f'Yung/yung_large_files/semantic_feature/test_notebook/saved_pcd/{cat}/test/{instance}.txt'
|
| 811 |
+
|
| 812 |
+
# # Load the instance point cloud
|
| 813 |
+
# instance_pcd_np = np.loadtxt(instance_pcd_path)
|
| 814 |
+
# try:
|
| 815 |
+
# verts, faces, aux = load_obj(obj_path)
|
| 816 |
+
# except ValueError as e:
|
| 817 |
+
# print(f"Warning: {e}, attempting to load without material.")
|
| 818 |
+
|
| 819 |
+
# try:
|
| 820 |
+
# verts, faces, aux = load_obj(obj_path, load_textures=True)
|
| 821 |
+
# except ValueError as e2:
|
| 822 |
+
# print(f"Failed to load {obj_path} without material: {e2}")
|
| 823 |
+
# continue
|
| 824 |
+
# meshes = Meshes(verts=[verts], faces=[faces.verts_idx], textures=None)
|
| 825 |
+
|
| 826 |
+
#modify for amodal
|
| 827 |
+
print("Processing", instance)
|
| 828 |
+
obj_path = f'/mnt/4T/Yung/yung_large_files/pose_can_results/output_orientation_Matters/Amodal3r_HouseCat6D_test/scene01/000000/cup-grey_handle/mesh.glb'
|
| 829 |
+
instance_pcd_path = f"/mnt/4T/Yung/yung_large_files/pose_can_results/output_orientation_Matters/Amodal3r_HouseCat6D_test/scene01/000000/cup-grey_handle/mesh_downsampled.npz"
|
| 830 |
+
instance_pcd_np = np.load(instance_pcd_path)['coord']
|
| 831 |
+
instance_pcd_tensor = torch.from_numpy(instance_pcd_np)
|
| 832 |
+
N = instance_pcd_tensor.shape[0]
|
| 833 |
+
# modify for cuda0
|
| 834 |
+
instance_points = instance_pcd_tensor.view(1, N, 3).float().cuda(0)
|
| 835 |
+
|
| 836 |
+
try:
|
| 837 |
+
verts, faces, aux = load_obj(obj_path)
|
| 838 |
+
except Exception as e:
|
| 839 |
+
print(f"Warning: Failed to load OBJ with load_obj: {e}")
|
| 840 |
+
try:
|
| 841 |
+
mesh = trimesh.load(obj_path, force='mesh')
|
| 842 |
+
verts = torch.from_numpy(mesh.vertices).float()
|
| 843 |
+
faces = torch.from_numpy(mesh.faces).long()
|
| 844 |
+
|
| 845 |
+
# Extract texture information from trimesh
|
| 846 |
+
tex = None
|
| 847 |
+
if isinstance(mesh, trimesh.Scene):
|
| 848 |
+
# Extract the first geometry from the scene
|
| 849 |
+
if len(mesh.geometry) == 0:
|
| 850 |
+
raise ValueError(f"No geometry found in scene for {obj_path}")
|
| 851 |
+
mesh = list(mesh.geometry.values())[0]
|
| 852 |
+
|
| 853 |
+
# Extract texture information from the mesh
|
| 854 |
+
color_visual = mesh.visual.to_color()
|
| 855 |
+
if hasattr(color_visual, "vertex_colors") and color_visual.vertex_colors is not None:
|
| 856 |
+
# Create vertex textures from vertex colors
|
| 857 |
+
print("Using vertex colors for texture.")
|
| 858 |
+
vertex_colors = torch.from_numpy(color_visual.vertex_colors[:, :3].astype(np.float32)) / 255.0
|
| 859 |
+
tex = TexturesVertex(verts_features=vertex_colors[None])
|
| 860 |
+
elif hasattr(color_visual, "face_colors") and color_visual.face_colors is not None:
|
| 861 |
+
# Average face colors to vertices
|
| 862 |
+
print("Using face colors to compute vertex colors for texture.")
|
| 863 |
+
vertex_colors = np.zeros((len(mesh.vertices), 3))
|
| 864 |
+
vertex_counts = np.zeros(len(mesh.vertices))
|
| 865 |
+
for face, color in zip(mesh.faces, color_visual.face_colors):
|
| 866 |
+
vertex_colors[face] += color[:3]
|
| 867 |
+
vertex_counts[face] += 1
|
| 868 |
+
vertex_colors = vertex_colors / (vertex_counts[:, None] + 1e-8)
|
| 869 |
+
vertex_colors = torch.from_numpy(vertex_colors.astype(np.float32)) / 255.0
|
| 870 |
+
tex = TexturesVertex(verts_features=vertex_colors[None])
|
| 871 |
+
else:
|
| 872 |
+
print("No vertex or face colors found; proceeding without texture.")
|
| 873 |
+
tex = None
|
| 874 |
+
|
| 875 |
+
|
| 876 |
+
except Exception as e2:
|
| 877 |
+
print(f"Warning: Failed to load GLB with trimesh: {e2}")
|
| 878 |
+
continue
|
| 879 |
+
|
| 880 |
+
|
| 881 |
+
# Initialise the mesh with textures
|
| 882 |
+
verts = normalize_mesh_verts(verts) # Housecat meshes are absolute scale
|
| 883 |
+
# original
|
| 884 |
+
# meshes = Meshes(verts=[verts], faces=[faces.verts_idx], textures=tex)
|
| 885 |
+
# revised for amodal
|
| 886 |
+
meshes = Meshes(verts=[verts], faces=[faces], textures=tex)
|
| 887 |
+
|
| 888 |
+
if meshes.textures is None:
|
| 889 |
+
meshes.textures = TexturesVertex(
|
| 890 |
+
verts_features=torch.ones_like(meshes.verts_padded(), device=device)
|
| 891 |
+
)
|
| 892 |
+
|
| 893 |
+
# render the mesh with 8 views, scale means the distance from the object to the camera
|
| 894 |
+
image_size=(420,420)
|
| 895 |
+
#images,fragments,cameras = render_batch(meshes,image_size=image_size,scale=1.0)
|
| 896 |
+
images,fragments,cameras = render(meshes,image_size=image_size,scale=2.0)
|
| 897 |
+
|
| 898 |
+
os.makedirs(f'{save_dir}/{cat}_rgb_dino_untex-try', exist_ok=True)
|
| 899 |
+
rgb = images.cpu().numpy()[:, :, :, :3]
|
| 900 |
+
image_grid(rgb, rows=1, cols=8, rgb=True)
|
| 901 |
+
plt.savefig(f'{save_dir}/{cat}_rgb_dino_untex-try/{instance}_rendering-texture_amodal.png')
|
| 902 |
+
plt.close()
|
| 903 |
+
|
| 904 |
+
# get the feature point cloud
|
| 905 |
+
feature_point_cloud, dino_feat_masked, feature_point_cloud_list = fuse_feature_rgbd(extractor,images,fragments,cameras)
|
| 906 |
+
|
| 907 |
+
# get the downsampled aggregated feature point cloud
|
| 908 |
+
num_pts= 1024
|
| 909 |
+
nn_num= 100 # larger nn_num will make the feature more smooth
|
| 910 |
+
sampled_points,aggregated_features = downsample_with_knn_feature_aggregation(feature_point_cloud,num_pts,nn_num)
|
| 911 |
+
|
| 912 |
+
# #Needed
|
| 913 |
+
# index = np.random.choice(partial_feature_point_cloud.shape[0], 1024, replace=False)
|
| 914 |
+
# plot_pointclouds_3d_with_copca(average_aggregated_features.squeeze(0).detach().cpu().numpy(),
|
| 915 |
+
# partial_feature_point_cloud[index,3:],
|
| 916 |
+
# sampled_points.squeeze(0).detach().cpu().numpy(),
|
| 917 |
+
# partial_feature_point_cloud[index,:3])
|
| 918 |
+
|
| 919 |
+
|
| 920 |
+
q=0
|
| 921 |
+
|
| 922 |
+
if False:
|
| 923 |
+
q+=1
|
| 924 |
+
inputs = trainset[q]
|
| 925 |
+
rgb = inputs['rgb'][None].cuda()
|
| 926 |
+
pts = inputs['pts'][None]
|
| 927 |
+
choose = inputs['choose'][None]
|
| 928 |
+
model = inputs['model'][None].cuda()
|
| 929 |
+
rgb = inputs['rgb'][None].cuda()
|
| 930 |
+
|
| 931 |
+
_desc_q = extractor.forward_features(rgb)["x_prenorm"][:, :]
|
| 932 |
+
#_desc_q = extractor.extract_descriptors(rgb,layer=11,facet='token',include_cls=True).squeeze(1) # B,L,C
|
| 933 |
+
# _norm_q = torch.linalg.norm(_desc_q, dim=-1)[:, :, None]
|
| 934 |
+
# _desc_q = _desc_q / (_norm_q)
|
| 935 |
+
|
| 936 |
+
dino_feature = _desc_q[:,1:,:]
|
| 937 |
+
|
| 938 |
+
|
| 939 |
+
#dino_feature = self.rgb_extractor.forward_features(rgb)["x_prenorm"][:, 1:]
|
| 940 |
+
#rgb=self.rgb_extractor.preprocess_pil(rgb)
|
| 941 |
+
#dino_feature = self.rgb_extractor.extract_descriptors(rgb,layer=11,facet='key') # (1,900,384)
|
| 942 |
+
f_dim = dino_feature.shape[-1]
|
| 943 |
+
num_patches =int(dino_feature.shape[1]**0.5) # 1
|
| 944 |
+
b=1
|
| 945 |
+
dino_feature = dino_feature.reshape(b, num_patches, num_patches, f_dim).permute(0,3,1,2)
|
| 946 |
+
|
| 947 |
+
dino_feature = F.interpolate(dino_feature, size=(num_patches * 14, num_patches * 14), mode='nearest')
|
| 948 |
+
dino_feature_2d_vis = dino_feature.detach().cpu()[0] #384, 224,224
|
| 949 |
+
|
| 950 |
+
b, d = dino_feature.shape[0:2]
|
| 951 |
+
dino_feature = dino_feature.reshape(b,d,-1)
|
| 952 |
+
choose_2 = choose.unsqueeze(1).repeat(1, d, 1).cuda()
|
| 953 |
+
dino_feature = torch.gather(dino_feature,2,choose_2).contiguous() # b,d,n
|
| 954 |
+
|
| 955 |
+
#dino_feature = dino_feature / torch.std(dino_feature, dim=1, keepdim=True)
|
| 956 |
+
#dino_feature = torch.norm(dino_feature, dim=1, keepdim=True)
|
| 957 |
+
#choose_dino = choose.unsqueeze(1).repeat(1, d, 1Z
|
| 958 |
+
#sem_model = sem_model / torch.std(sem_model, dim=-1, keepdim=True)
|
| 959 |
+
#visual_global_sem_high = sem_model.detach().cpu().numpy()[0] #1024,384
|
| 960 |
+
visual_partial_sem_high = dino_feature.permute(0,2,1).detach().cpu().numpy()[0] #1024,128
|
| 961 |
+
|
| 962 |
+
#visual_global_sem_low = self.feature_mlp(sem_model.permute(0,2,1)).permute(0,2,1).detach().cpu().numpy()[0]
|
| 963 |
+
#visual_partial_sem_low = rgb_local.permute(0,2,1).detach().cpu().numpy()[0]
|
| 964 |
+
# transform the pts with GT 9D Pose into object coordinate
|
| 965 |
+
translation_gt = inputs['translation_label'][None]
|
| 966 |
+
rotation_gt = inputs['rotation_label'][None]
|
| 967 |
+
size_gt = inputs['size_label'][None]
|
| 968 |
+
pts_obj_frame = (inputs['pts'] - translation_gt.unsqueeze(1)) / (torch.norm(size_gt, dim=1).view(b, 1, 1) + 1e-8) @ rotation_gt
|
| 969 |
+
#kpt_obj_frame = (kpt_3d - translation_gt.unsqueeze(1)) / (torch.norm(size_gt, dim=1).view(b, 1, 1) + 1e-8) @ rotation_gt
|
| 970 |
+
|
| 971 |
+
# dino_feature_2d_vis_pca = vis_pca_pixelwise(dino_feature_2d_vis[None])[0]
|
| 972 |
+
# plt.imshow(dino_feature_2d_vis_pca[:,:,:3])
|
| 973 |
+
# plt.show()
|
| 974 |
+
# fig =plt.figure()
|
| 975 |
+
# rgb_unnorm = unnormalize(rgb[0].permute(1,2,0).detach().cpu())
|
| 976 |
+
# plt.imshow(rgb_unnorm)
|
| 977 |
+
# plt.show()
|
| 978 |
+
# image_mask = ((rgb_unnorm.clone().sum(axis=2) >0.1)*1.0)[None,None] # 224,224
|
| 979 |
+
|
| 980 |
+
# rgb_mask = np.array(image_mask[0,0,:,:,None]).repeat(384, axis=2).transpose(2,0,1)
|
| 981 |
+
|
| 982 |
+
# dino_feature_2d_vis[rgb_mask==0] = 0
|
| 983 |
+
# masked_dino_feature_2d_vis_pca = vis_pca_pixelwise(dino_feature_2d_vis[None])[0]
|
| 984 |
+
# plt.imshow(masked_dino_feature_2d_vis_pca[:,:,:])
|
| 985 |
+
# plt.show()
|
| 986 |
+
|
| 987 |
+
|
| 988 |
+
# print('self.pca.cateagg-partial')
|
| 989 |
+
# index = np.random.choice(partial_feature_point_cloud.shape[0], 1024, replace=False)
|
| 990 |
+
# #average_aggregated_features = torch.load(f'sem_cat_pcd/{cat}_dino_feature.pt')
|
| 991 |
+
|
| 992 |
+
average_aggregated_features = torch.load(f'/home/xyz/anything6d_project/Sem-GCE-AG-Pose/sem_cat_pcd/{cat}_dino_feature.pt')
|
| 993 |
+
# #plot_pointclouds_3d_with_copca(aggregated_features.squeeze(0).detach().cpu().numpy(), partial_feature_point_cloud[index,3:], sampled_points.squeeze(0).detach().cpu().numpy(), pts_obj_frame)
|
| 994 |
+
|
| 995 |
+
plot_pointclouds_3d_with_copca_old(average_aggregated_features.squeeze(0).detach().cpu().numpy(),
|
| 996 |
+
visual_partial_sem_high,
|
| 997 |
+
sampled_points.squeeze(0).detach().cpu().numpy(),
|
| 998 |
+
pts_obj_frame[0].detach().cpu().numpy())
|
| 999 |
+
plt.show()
|
| 1000 |
+
|
| 1001 |
+
|
| 1002 |
+
# plot_pointclouds_3d_with_copca(average_aggregated_features.squeeze(0).detach().cpu().numpy(),
|
| 1003 |
+
# visual_partial_sem_high,
|
| 1004 |
+
# sampled_points.squeeze(0).detach().cpu().numpy(),
|
| 1005 |
+
# pts_obj_frame[0].detach().cpu().numpy())
|
| 1006 |
+
|
| 1007 |
+
|
| 1008 |
+
# #query_points =np.random.choice(1024, 3)
|
| 1009 |
+
# query_points, sampled_indices = sample_farthest_points(pts_obj_frame, K=4) # Shape: (1, 1024, 3), (1, 1024)
|
| 1010 |
+
# plot_pointclouds_with_color_mapping(visual_partial_sem_high,
|
| 1011 |
+
# aggregated_features.squeeze(0).detach().cpu().numpy(),
|
| 1012 |
+
# pts_obj_frame[0].detach().cpu().numpy(),
|
| 1013 |
+
# model[0].detach().cpu().numpy(),
|
| 1014 |
+
# sampled_indices[0], similarity_threshold=None)
|
| 1015 |
+
|
| 1016 |
+
|
| 1017 |
+
# # plot_pointclouds_3d_with_copca(average_aggregated_features.squeeze(0).detach().cpu().numpy(), partial_feature_point_cloud[index,3:], sampled_points.squeeze(0).detach().cpu().numpy(), partial_feature_point_cloud[index,:3])
|
| 1018 |
+
# # plot_pointclouds_3d_with_pca(average_aggregated_features.squeeze(0).detach().cpu().numpy(), partial_feature_point_cloud[index,3:], sampled_points.squeeze(0).detach().cpu().numpy(), partial_feature_point_cloud[index,:3])
|
| 1019 |
+
# partial_feature_point_cloud = feature_point_cloud_list[5]
|
| 1020 |
+
# plot_pointclouds_3d_with_copca(visual_partial_sem_high,
|
| 1021 |
+
# partial_feature_point_cloud[index,3:],
|
| 1022 |
+
# pts_obj_frame[0].detach().cpu().numpy(),
|
| 1023 |
+
# partial_feature_point_cloud[index,:3])
|
| 1024 |
+
|
| 1025 |
+
# plot_pointclouds_3d_with_copca(average_aggregated_features.squeeze(0).detach().cpu().numpy(), aggregated_features.squeeze(0).detach().cpu().numpy(), sampled_points.squeeze(0).detach().cpu().numpy(), sampled_points.squeeze(0).detach().cpu().numpy())
|
| 1026 |
+
|
| 1027 |
+
|
| 1028 |
+
|
| 1029 |
+
os.makedirs(f'{save_dir}/saved_dino_pcd_untex-try/{cat}', exist_ok=True)
|
| 1030 |
+
torch.save(aggregated_features, f'{save_dir}/saved_dino_pcd_untex-try/{cat}/{instance}_dino_feature-texture_amodal.pt')
|
| 1031 |
+
|
| 1032 |
+
os.makedirs(f'{save_dir}/saved_pcd_untex-try/{cat}', exist_ok=True)
|
| 1033 |
+
torch.save(sampled_points, f'{save_dir}/saved_pcd_untex-try/{cat}/{instance}_pcd-texture_amodal.pt')
|
| 1034 |
+
|
| 1035 |
+
aggregated_features_list.append(aggregated_features)
|
| 1036 |
+
# #break
|
| 1037 |
+
vis_dino = vis_pca_pixelwise(np.array(dino_feat_masked))
|
| 1038 |
+
vis_img = np.clip(vis_dino[:,:,:,:],a_min=0,a_max=1)
|
| 1039 |
+
image_grid(vis_img, rows=1, cols=8, rgb=True)
|
| 1040 |
+
|
| 1041 |
+
os.makedirs(f'{save_dir}/{cat}_rgb_dino_untex-try', exist_ok=True)
|
| 1042 |
+
plt.savefig(f'{save_dir}/{cat}_rgb_dino_untex-try/{instance}_dino-texture_amodal.png')
|
| 1043 |
+
plt.close()
|
| 1044 |
+
if False:
|
| 1045 |
+
|
| 1046 |
+
rgb = images.cpu().numpy()[:, :, :, :3]
|
| 1047 |
+
mask = images[:, ..., 3].cpu().numpy()!=0
|
| 1048 |
+
depth_image = fragments[:, ..., 0].cpu().numpy()*mask
|
| 1049 |
+
image_grid(rgb, rows=1, cols=8, rgb=True)
|
| 1050 |
+
# os.makedirs(f'/home/tulrfpf/code/PointFlowRenderer/{cat}_rgb_dino', exist_ok=True)
|
| 1051 |
+
# plt.savefig(f'/home/tulrfpf/code/PointFlowRenderer/{cat}_rgb_dino/{instance}_rgb.png')
|
| 1052 |
+
# image_grid(depth_image[...,None], rows=2, cols=4, rgb=True)
|
| 1053 |
+
# image_grid(mask[...,None], rows=2, cols=4, rgb=True)
|
| 1054 |
+
|
| 1055 |
+
|
| 1056 |
+
|
| 1057 |
+
fig = plt.figure(figsize=(10, 10))
|
| 1058 |
+
ax = fig.add_subplot(111, projection="3d")
|
| 1059 |
+
#ax.scatter(sampled_points[:, 2], sampled_points[:,0], sampled_points[:, 1], c="b")
|
| 1060 |
+
pca_color =vis_pca(feature_point_cloud[:, 3:])
|
| 1061 |
+
ax.scatter(feature_point_cloud[:, 2], feature_point_cloud[:, 0], feature_point_cloud[:, 1], c=pca_color,s=0.1)
|
| 1062 |
+
#create_camera_geometry_batch(ax=ax,R_batch=R,T_batch=T,order=(2,0,1))
|
| 1063 |
+
ax.set_xlabel("z")
|
| 1064 |
+
ax.set_ylabel("x")
|
| 1065 |
+
ax.set_zlabel("y")
|
| 1066 |
+
ax.set_xlim(-2, 2)
|
| 1067 |
+
ax.set_ylim(-2, 2)
|
| 1068 |
+
ax.set_zlim(-2, 2)
|
| 1069 |
+
plt.title("Sampled Dense Points from Mesh")
|
| 1070 |
+
plt.show()
|
| 1071 |
+
|
| 1072 |
+
fig = plt.figure(figsize=(10, 10))
|
| 1073 |
+
ax = fig.add_subplot(111, projection="3d")
|
| 1074 |
+
pca_color =vis_pca(aggregated_features.squeeze(0))
|
| 1075 |
+
sampled_points= sampled_points.squeeze(0).cpu().detach().numpy()
|
| 1076 |
+
ax.scatter(sampled_points[:, 2], sampled_points[:, 0], sampled_points[:, 1], c=pca_color,s=50)
|
| 1077 |
+
#create_camera_geometry_batch(ax=ax,R_batch=R,T_batch=T,order=(2,0,1))
|
| 1078 |
+
ax.set_xlabel("z")
|
| 1079 |
+
ax.set_ylabel("x")
|
| 1080 |
+
ax.set_zlabel("y")
|
| 1081 |
+
ax.set_xlim(-2, 2)
|
| 1082 |
+
ax.set_ylim(-2, 2)
|
| 1083 |
+
ax.set_zlim(-2, 2)
|
| 1084 |
+
plt.title("Sampled Sparse Points from Mesh")
|
| 1085 |
+
plt.show()
|
| 1086 |
+
#break
|
| 1087 |
+
# Assign the aggregated features to the mean shape point cloud
|
| 1088 |
+
aggregated_features_tensor = torch.cat(aggregated_features_list, dim=0) #[N, 1024, 384]
|
| 1089 |
+
average_aggregated_features = aggregated_features_tensor.mean(dim=0, keepdim=True)
|
| 1090 |
+
print("Average Aggregated Features Shape:", average_aggregated_features.shape) # Should be (1, 1024, 384)
|
| 1091 |
+
|
| 1092 |
+
os.makedirs(f'{save_dir}/sem_cat_pcd_untex-try', exist_ok=True)
|
| 1093 |
+
torch.save(average_aggregated_features, f'{save_dir}/sem_cat_pcd_untex-try/{cat}_dino_feature.pt')
|
| 1094 |
+
|
| 1095 |
+
# fig = plt.figure(figsize=(10, 10))
|
| 1096 |
+
# ax = fig.add_subplot(111, projection="3d")
|
| 1097 |
+
# pca_color =vis_pca(average_aggregated_features.squeeze(0))
|
| 1098 |
+
# # sampled_points= sampled_points.squeeze(0).cpu().detach().numpy()
|
| 1099 |
+
# meanshape_points = meanshape_points.squeeze(0).cpu().detach().numpy()
|
| 1100 |
+
# ax.scatter(meanshape_points[:, 2], meanshape_points[:, 0], meanshape_points[:, 1], c=pca_color,s=10.0, marker='o')
|
| 1101 |
+
# ax.set_xlabel("z")
|
| 1102 |
+
# ax.set_ylabel("x")
|
| 1103 |
+
# ax.set_zlabel("y")
|
| 1104 |
+
# ax.set_xlim(-2, 2)
|
| 1105 |
+
# ax.set_ylim(-2, 2)
|
| 1106 |
+
# ax.set_zlim(-2, 2)
|
| 1107 |
+
# plt.title("Shape Prior Dino")
|
| 1108 |
+
# plt.show()
|
| 1109 |
+
|
RGBD_DIN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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from custom_utils import ShapeNetCore
|
| 3 |
+
from custom_utils import _compute_fov,_sample_points_from_faces
|
| 4 |
+
from custom_utils import image_grid
|
| 5 |
+
from custom_utils.shapenet_base import HouseCatDataset
|
| 6 |
+
import matplotlib.pyplot as plt
|
| 7 |
+
import numpy as np
|
| 8 |
+
import k3d
|
| 9 |
+
import os
|
| 10 |
+
import json
|
| 11 |
+
import torch
|
| 12 |
+
from PIL import Image
|
| 13 |
+
|
| 14 |
+
import cv2
|
| 15 |
+
import imageio
|
| 16 |
+
import numpy as np
|
| 17 |
+
from PIL import Image
|
| 18 |
+
import matplotlib.pyplot as plt
|
| 19 |
+
from torchvision import transforms
|
| 20 |
+
from custom_utils.extractor import ViTExtractor
|
| 21 |
+
import torch.nn.functional as F
|
| 22 |
+
from sklearn.decomposition import PCA as sklearnPCA
|
| 23 |
+
import math
|
| 24 |
+
from custom_utils.utils_general import center_crop
|
| 25 |
+
|
| 26 |
+
from pytorch3d.io import load_objs_as_meshes, load_obj
|
| 27 |
+
from pytorch3d.implicitron.tools.point_cloud_utils import get_rgbd_point_cloud
|
| 28 |
+
from pytorch3d.structures import Meshes
|
| 29 |
+
from pytorch3d.renderer import (
|
| 30 |
+
PerspectiveCameras,
|
| 31 |
+
FoVPerspectiveCameras,
|
| 32 |
+
PointLights,
|
| 33 |
+
MeshRasterizer,
|
| 34 |
+
MeshRenderer,
|
| 35 |
+
RasterizationSettings,
|
| 36 |
+
HardPhongShader,
|
| 37 |
+
TexturesVertex,
|
| 38 |
+
look_at_view_transform,
|
| 39 |
+
ray_bundle_to_ray_points,
|
| 40 |
+
NDCMultinomialRaysampler,
|
| 41 |
+
TexturesUV,
|
| 42 |
+
BlendParams,
|
| 43 |
+
|
| 44 |
+
TexturesVertex
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
from pytorch3d.implicitron.tools.point_cloud_utils import get_rgbd_point_cloud
|
| 48 |
+
from pytorch3d.structures import Pointclouds
|
| 49 |
+
import torch
|
| 50 |
+
from pytorch3d.ops import sample_farthest_points, knn_points, knn_gather
|
| 51 |
+
|
| 52 |
+
from matplotlib import cm
|
| 53 |
+
import numpy as np
|
| 54 |
+
import matplotlib.pyplot as plt
|
| 55 |
+
from sklearn.decomposition import PCA
|
| 56 |
+
from mpl_toolkits.mplot3d import Axes3D
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def sample_points_on_sphere(num_points=80):
|
| 60 |
+
points = []
|
| 61 |
+
phi = (1 + math.sqrt(5)) / 2 # golden ratio
|
| 62 |
+
|
| 63 |
+
for i in range(num_points):
|
| 64 |
+
theta = 2 * math.pi * i / phi # azimuthal angle
|
| 65 |
+
z = 1 - (2 * i + 1) / num_points # z-coordinate, uniform from -1 to 1
|
| 66 |
+
radius = math.sqrt(1 - z * z) # radius for the xy-plane
|
| 67 |
+
x = radius * math.cos(theta)
|
| 68 |
+
y = radius * math.sin(theta)
|
| 69 |
+
points.append([x, y, z])
|
| 70 |
+
|
| 71 |
+
return torch.tensor(points, dtype=torch.float32)
|
| 72 |
+
|
| 73 |
+
def get_cube_vertices():
|
| 74 |
+
# Cube vertices (8 vertices)
|
| 75 |
+
return torch.tensor([[1, 1, 1],
|
| 76 |
+
[1, 1, -1],
|
| 77 |
+
[1, -1, 1],
|
| 78 |
+
[1, -1, -1],
|
| 79 |
+
[-1, 1, 1],
|
| 80 |
+
[-1, 1, -1],
|
| 81 |
+
[-1, -1, 1],
|
| 82 |
+
[-1, -1, -1]], dtype=torch.float32) # Ensure float type
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def render(meshes,scale=3.0,image_size=(420,420),light=(0.3,0.3,0.3)):
|
| 86 |
+
# prepare the camera
|
| 87 |
+
num_views = 8
|
| 88 |
+
# Get the cube vertices
|
| 89 |
+
#cube_vertices = get_cube_vertices()*scale
|
| 90 |
+
cube_vertices = sample_points_on_sphere(num_views)*scale
|
| 91 |
+
#up = torch.randn(1, 3)
|
| 92 |
+
up=torch.tensor([[0.0, 0.0, 1.0]], dtype=torch.float32)
|
| 93 |
+
up = up / torch.norm(up, dim=1)[:, None]
|
| 94 |
+
R, T = look_at_view_transform(eye=cube_vertices, at=torch.tensor([[0.0, 0.0, 0.0]], dtype=torch.float32), up=up)
|
| 95 |
+
cam_K= np.array([[572, 0.0, image_size[0]//2], [0.0, 572, image_size[1]//2], [0.0, 0.0, 1.0]])
|
| 96 |
+
fx,_,cx,_,fy,cy,_,_,_=cam_K.reshape(9)
|
| 97 |
+
fov_x, fov_y = _compute_fov(cam_K, 420, 420)
|
| 98 |
+
|
| 99 |
+
cameras = PerspectiveCameras(device=device, R=R, T=T, image_size=((420,420),),
|
| 100 |
+
focal_length=torch.tensor([[fx, fy]], dtype=torch.float32),
|
| 101 |
+
principal_point=torch.tensor([[cx, cy]], dtype=torch.float32),
|
| 102 |
+
in_ndc=False)
|
| 103 |
+
|
| 104 |
+
# prepare the lights
|
| 105 |
+
raster_settings = RasterizationSettings(image_size=image_size)
|
| 106 |
+
lights = PointLights(location=torch.tensor([0.0, 1.0, -2.0], device=device)[None], ambient_color=(light,),diffuse_color=(light,),device=device)
|
| 107 |
+
|
| 108 |
+
# move the data to the device
|
| 109 |
+
meshes = meshes.to(device)
|
| 110 |
+
cameras = cameras.to(device)
|
| 111 |
+
if len(cameras) != 1 and len(cameras) % len(meshes) != 0:
|
| 112 |
+
raise ValueError("Mismatch between batch dims of cameras and meshes.")
|
| 113 |
+
if len(cameras) > 1:
|
| 114 |
+
meshes = meshes.extend(len(cameras) // len(meshes))
|
| 115 |
+
|
| 116 |
+
# prepare the renderer
|
| 117 |
+
class MeshRendererWithDepth(torch.nn.Module):
|
| 118 |
+
def __init__(self, rasterizer, shader):
|
| 119 |
+
super().__init__()
|
| 120 |
+
self.rasterizer = rasterizer
|
| 121 |
+
self.shader = shader
|
| 122 |
+
|
| 123 |
+
def forward(self, meshes_world, **kwargs) -> torch.Tensor:
|
| 124 |
+
fragments = self.rasterizer(meshes_world, **kwargs)
|
| 125 |
+
images = self.shader(fragments, meshes_world, **kwargs)
|
| 126 |
+
return images, fragments.zbuf
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
blend_params = BlendParams(background_color=(0.0, 0.0, 0.0)) # Blue background
|
| 130 |
+
renderer = MeshRendererWithDepth(
|
| 131 |
+
rasterizer=MeshRasterizer(
|
| 132 |
+
cameras=cameras,
|
| 133 |
+
raster_settings=raster_settings,
|
| 134 |
+
),
|
| 135 |
+
# Set background color to blue [R, G, B]
|
| 136 |
+
|
| 137 |
+
shader=HardPhongShader(
|
| 138 |
+
device=device,
|
| 139 |
+
cameras=cameras,
|
| 140 |
+
lights=lights,
|
| 141 |
+
blend_params=blend_params
|
| 142 |
+
)
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
images,fragments = renderer(meshes)
|
| 146 |
+
return images,fragments,cameras
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def render_batch(meshes,scale=3.0,image_size=(420,420),light=(0.3,0.3,0.3)):
|
| 150 |
+
# prepare the camera
|
| 151 |
+
num_views = 8
|
| 152 |
+
# Get the cube vertices
|
| 153 |
+
cube_vertices = get_cube_vertices()*scale
|
| 154 |
+
#cube_vertices = sample_points_on_sphere(num_views)*scale
|
| 155 |
+
up = torch.randn(1, 3)
|
| 156 |
+
# up=torch.tensor([[0.0, 0.0, 1.0]], dtype=torch.float32)
|
| 157 |
+
up = up / torch.norm(up, dim=1)[:, None]
|
| 158 |
+
R, T = look_at_view_transform(eye=cube_vertices, at=torch.tensor([[0.0, 0.0, 0.0]], dtype=torch.float32), up=up)
|
| 159 |
+
|
| 160 |
+
cam_K= np.array([[572, 0.0, image_size[0]//2], [0.0, 572, image_size[1]//2], [0.0, 0.0, 1.0]])
|
| 161 |
+
fx,_,cx,_,fy,cy,_,_,_=cam_K.reshape(9)
|
| 162 |
+
fov_x, fov_y = _compute_fov(cam_K, 420, 420)
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
# prepare the renderer
|
| 166 |
+
class MeshRendererWithDepth(torch.nn.Module):
|
| 167 |
+
def __init__(self, rasterizer, shader):
|
| 168 |
+
super().__init__()
|
| 169 |
+
self.rasterizer = rasterizer
|
| 170 |
+
self.shader = shader
|
| 171 |
+
|
| 172 |
+
def forward(self, meshes_world, **kwargs) -> torch.Tensor:
|
| 173 |
+
fragments = self.rasterizer(meshes_world, **kwargs)
|
| 174 |
+
images = self.shader(fragments, meshes_world, **kwargs)
|
| 175 |
+
return images, fragments.zbuf
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
blend_params = BlendParams(background_color=(0.0, 0.0, 0.0)) # Blue background
|
| 179 |
+
|
| 180 |
+
batch_size = 10
|
| 181 |
+
all_images=[]
|
| 182 |
+
all_fragments=[]
|
| 183 |
+
|
| 184 |
+
# move the data to the device
|
| 185 |
+
meshes = meshes.extend(batch_size).to(device)
|
| 186 |
+
for i in range(0,R.shape[0],batch_size):
|
| 187 |
+
R_batch = R[i:i+batch_size]
|
| 188 |
+
T_batch = T[i:i+batch_size]
|
| 189 |
+
cameras_batch = PerspectiveCameras(device=device, R=R_batch, T=T_batch, image_size=((420,420),),
|
| 190 |
+
focal_length=torch.tensor([[fx, fy]], dtype=torch.float32),
|
| 191 |
+
principal_point=torch.tensor([[cx, cy]], dtype=torch.float32),
|
| 192 |
+
in_ndc=False).to(device)
|
| 193 |
+
|
| 194 |
+
# prepare the lights
|
| 195 |
+
raster_settings = RasterizationSettings(image_size=image_size)
|
| 196 |
+
lights = PointLights(location=torch.tensor([0.0, 1.0, -2.0], device=device)[None],
|
| 197 |
+
ambient_color=(light,),diffuse_color=(light,),device=device)
|
| 198 |
+
|
| 199 |
+
renderer = MeshRendererWithDepth(
|
| 200 |
+
rasterizer=MeshRasterizer(
|
| 201 |
+
cameras=cameras_batch,
|
| 202 |
+
raster_settings=raster_settings,
|
| 203 |
+
),
|
| 204 |
+
# Set background color to blue [R, G, B]
|
| 205 |
+
shader=HardPhongShader(
|
| 206 |
+
device=device,
|
| 207 |
+
cameras=cameras_batch,
|
| 208 |
+
lights=lights,
|
| 209 |
+
blend_params=blend_params
|
| 210 |
+
)
|
| 211 |
+
)
|
| 212 |
+
images,fragments = renderer(meshes)
|
| 213 |
+
all_images.append(images)
|
| 214 |
+
all_fragments.append(fragments)
|
| 215 |
+
all_images = torch.cat(all_images,dim=0)
|
| 216 |
+
all_fragments = torch.cat(all_fragments,dim=0)
|
| 217 |
+
cameras = PerspectiveCameras(device=device, R=R, T=T, image_size=((420,420),),
|
| 218 |
+
focal_length=torch.tensor([[fx, fy]], dtype=torch.float32),
|
| 219 |
+
principal_point=torch.tensor([[cx, cy]], dtype=torch.float32),
|
| 220 |
+
in_ndc=False).to(device)
|
| 221 |
+
return all_images,all_fragments,cameras
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def fuse_feature_rgbd(extractor,images,fragments,cameras):
|
| 225 |
+
dino_feat_masked_list = []
|
| 226 |
+
feature_point_cloud_list = []
|
| 227 |
+
for i in range(images.shape[0]):
|
| 228 |
+
image = images.cpu().numpy()[i, :, :, :3]
|
| 229 |
+
image_mask = images[i, ..., 3].cpu().numpy()!=0
|
| 230 |
+
crop_size = (420, 420)
|
| 231 |
+
crop_image, crop_mask, bbox = center_crop(image, image_mask, crop_size)
|
| 232 |
+
cropped_image_np = cv2.resize(crop_image, crop_size, interpolation=cv2.INTER_AREA)
|
| 233 |
+
#cropped_mask = cv2.resize(crop_mask*1.0, crop_size, interpolation=cv2.INTER_NEAREST)!=0 # Use nearest neighbor interpolation for masks
|
| 234 |
+
orignal_size = (int(bbox[2]-bbox[0]), int(bbox[3]-bbox[1])) #K,K
|
| 235 |
+
|
| 236 |
+
to_tensor = transforms.ToTensor()
|
| 237 |
+
input_image = to_tensor(cropped_image_np).cuda()
|
| 238 |
+
input_image = input_image.unsqueeze(0)
|
| 239 |
+
#input_image=extractor.preprocess_pil(input_image)
|
| 240 |
+
mean = torch.tensor([0.485, 0.456, 0.406]).cuda()
|
| 241 |
+
std = torch.tensor([0.229, 0.224, 0.225]).cuda()
|
| 242 |
+
input_image = (input_image - mean[None, :, None, None]) / std[None, :, None, None]
|
| 243 |
+
|
| 244 |
+
_desc_q = extractor.extract_descriptors(input_image,layer=11,include_cls=True).squeeze(1) # (1,900,384)
|
| 245 |
+
#_desc_q = extractor.forward_features(input_image)["x_prenorm"][:, :] # (1,900,384)
|
| 246 |
+
#_desc_q = extractor.extract_descriptors(input_image,layer=11,facet='token',include_cls=True).squeeze(1) # B,L,C
|
| 247 |
+
# _norm_q = torch.linalg.norm(_desc_q, dim=-1)[:, :, None]
|
| 248 |
+
# _desc_q = _desc_q / (_norm_q)
|
| 249 |
+
|
| 250 |
+
desc = _desc_q[:,1:,:][None]
|
| 251 |
+
#cls_token_q = _desc_q[:,0,:] #B,C`
|
| 252 |
+
|
| 253 |
+
input_mask = to_tensor(crop_mask).cuda()
|
| 254 |
+
input_mask = input_mask.unsqueeze(0)
|
| 255 |
+
|
| 256 |
+
img_mask = to_tensor(image_mask)
|
| 257 |
+
|
| 258 |
+
img_mask = img_mask.permute(1,2,0)
|
| 259 |
+
|
| 260 |
+
dino_feat = patch2pixel_feats(desc, original_size=orignal_size) #reize back to K,K =>( K, K, 384)
|
| 261 |
+
# create dino-feat with orignal size
|
| 262 |
+
dino_height, dino_width, feat_dim = (image_size[0],image_size[1], desc.shape[-1])
|
| 263 |
+
dino_feat_orig = torch.zeros(dino_height,dino_width,feat_dim)
|
| 264 |
+
# Fill the dino features into the original tensor at the specified bounding box
|
| 265 |
+
dino_feat_orig[bbox[1]:bbox[3], bbox[0]:bbox[2],:] = dino_feat #reize back to K,K =>(420, 420, 384) #gradint is not supported for this operation
|
| 266 |
+
# Apply the mask
|
| 267 |
+
dino_feat_masked = dino_feat_orig * img_mask
|
| 268 |
+
dino_feat_masked = dino_feat_masked.permute(2,0,1).unsqueeze(0)
|
| 269 |
+
dino_feat_masked_low = F.interpolate(dino_feat_masked, size=(30, 30), mode='bilinear')
|
| 270 |
+
|
| 271 |
+
image_mask = images[i, ..., 3][None,None]
|
| 272 |
+
depth_image = fragments[i, ..., 0][None]*image_mask
|
| 273 |
+
|
| 274 |
+
# # Define the kernel for erosion (3x3 ones kernel)
|
| 275 |
+
# kernel = torch.ones((1, 1, 5, 5), dtype=torch.float).cuda()
|
| 276 |
+
# # Number of erosion iterations
|
| 277 |
+
# iterations = 5
|
| 278 |
+
|
| 279 |
+
# # Perform iterative erosion
|
| 280 |
+
# for i in range(iterations):
|
| 281 |
+
# # Apply erosion using 2D convolution
|
| 282 |
+
# eroded_mask = F.conv2d(image_mask, kernel, padding=2)
|
| 283 |
+
# image_mask = (eroded_mask == kernel.sum()).float() # Update mask to eroded version
|
| 284 |
+
|
| 285 |
+
feature_point_cloud = get_rgbd_point_cloud(cameras[i], dino_feat_masked.to(device), depth_map=depth_image,mask=image_mask)#everthing on GPU
|
| 286 |
+
|
| 287 |
+
index = np.random.choice(feature_point_cloud.points_list()[0].shape[0], 4096, replace=True)
|
| 288 |
+
points = feature_point_cloud.points_list()[0].detach().cpu()[index,:]
|
| 289 |
+
colors = feature_point_cloud.features_list()[0].detach().cpu()[index,:]
|
| 290 |
+
# points = feature_point_cloud.points_list()[0].detach().cpu()[:,:]
|
| 291 |
+
# colors = feature_point_cloud.features_list()[0].detach().cpu()[:,:]
|
| 292 |
+
feature_point_cloud = torch.cat((points, colors), dim=1)
|
| 293 |
+
|
| 294 |
+
dino_feat_masked_list.append(dino_feat_masked_low.detach().cpu())
|
| 295 |
+
feature_point_cloud_list.append(feature_point_cloud)
|
| 296 |
+
feature_point_cloud = torch.cat(feature_point_cloud_list, dim=0)
|
| 297 |
+
dino_feat_masked = torch.cat(dino_feat_masked_list, dim=0)
|
| 298 |
+
return feature_point_cloud,dino_feat_masked, feature_point_cloud_list
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
def downsample_with_knn_feature_aggregation(feature_point_cloud,num_pts=1024,k_nearest_neighbors=100, instance_points=None):
|
| 302 |
+
#N_1, C_1 = 2048, 384 # Example number of points and features
|
| 303 |
+
num_points_to_sample = num_pts
|
| 304 |
+
k_nearest_neighbors = k_nearest_neighbors
|
| 305 |
+
|
| 306 |
+
# Example input pointcloud and features (N_1, C_1), where N_1 is the number of points and C_1 is the feature dimension
|
| 307 |
+
pointcloud = feature_point_cloud[None,:,:3].cuda() # Shape (1, N_1, 3) for 3D coordinates
|
| 308 |
+
features = feature_point_cloud[None,:,3:].cuda() # Shape (1, N_1, C_1) for features
|
| 309 |
+
|
| 310 |
+
# Step 1: FPS to downsample the points
|
| 311 |
+
# We use sample_farthest_points to select num_points_to_sample points
|
| 312 |
+
sampled_points, sampled_indices = sample_farthest_points(pointcloud, K=num_points_to_sample) # Shape: (1, 1024, 3), (1, 1024)
|
| 313 |
+
if instance_points is not None:
|
| 314 |
+
sampled_points = instance_points
|
| 315 |
+
|
| 316 |
+
# Step 2: KNN to find nearest neighbors
|
| 317 |
+
# Find the k nearest neighbors for each sampled point in the original pointcloud
|
| 318 |
+
dists, knn_indices, _ = knn_points(sampled_points, pointcloud, K=k_nearest_neighbors, return_nn=False)
|
| 319 |
+
|
| 320 |
+
# Step 3: Gather the features of the k-nearest neighbors using the knn indices
|
| 321 |
+
# Use knn_gather to get neighbor features for each sampled point
|
| 322 |
+
neighbor_features = knn_gather(features, knn_indices) # Shape: (1, 1024, k, C_1)
|
| 323 |
+
|
| 324 |
+
# Step 4: Aggregate features from the neighbors (e.g., by averaging)
|
| 325 |
+
#aggregated_features,_ = torch.max(neighbor_features,dim=-2) # Shape: (1, 1024, C_1)
|
| 326 |
+
aggregated_features = torch.mean(neighbor_features,dim=-2) # Shape: (1, 1024, C_1)
|
| 327 |
+
return sampled_points, aggregated_features
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
def vis_pca(feature):
|
| 331 |
+
n_components=3 # the first component is to seperate the object from the background
|
| 332 |
+
|
| 333 |
+
pca = sklearnPCA(n_components=n_components)
|
| 334 |
+
feature = pca.fit_transform(feature.detach().cpu().numpy())
|
| 335 |
+
for show_channel in range(n_components):
|
| 336 |
+
# min max normalize the feature map
|
| 337 |
+
feature[:, show_channel] = (feature[:, show_channel] - feature[:, show_channel].mean()) / (feature[:, show_channel].std()*10)
|
| 338 |
+
feature_resized = np.clip(feature[:,:]+0.5,0,1)
|
| 339 |
+
return feature_resized
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
def patch2pixel_feats(patch_features, original_size):
|
| 343 |
+
# Calculate the number of patches along each dimension
|
| 344 |
+
num_patches = int(math.sqrt(patch_features.shape[2]))
|
| 345 |
+
|
| 346 |
+
batch_num = patch_features.shape[0]
|
| 347 |
+
feat_dim = patch_features.shape[3]
|
| 348 |
+
patch_features = patch_features.reshape(batch_num, num_patches, num_patches, feat_dim)
|
| 349 |
+
patch_features = patch_features.permute(0,3,1,2)
|
| 350 |
+
|
| 351 |
+
pixel_features = F.interpolate(patch_features, size=(original_size[0], original_size[1]), mode='bilinear')
|
| 352 |
+
pixel_features = pixel_features.squeeze().permute(1,2,0)
|
| 353 |
+
|
| 354 |
+
return pixel_features
|
| 355 |
+
|
| 356 |
+
def vis_pca_pixelwise(feature):
|
| 357 |
+
n_components = 4 # The number of PCA components to use
|
| 358 |
+
batch, feat_dim, height,width = feature.shape
|
| 359 |
+
|
| 360 |
+
# Reshape the feature to (num_pixels, feat_dim)
|
| 361 |
+
num_pixels = height * width
|
| 362 |
+
feature_reshaped = np.array(feature).transpose(0,2,3,1).reshape(-1, feat_dim)
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
# Apply PCA
|
| 366 |
+
pca = sklearnPCA(n_components=n_components)
|
| 367 |
+
feature_pca = pca.fit_transform(feature_reshaped)
|
| 368 |
+
|
| 369 |
+
# Min-max normalization for each component
|
| 370 |
+
# for show_channel in range(n_components):
|
| 371 |
+
# feature_pca[:, show_channel] = (feature_pca[:, show_channel] - feature_pca[:, show_channel].min()) / \
|
| 372 |
+
# (feature_pca[:, show_channel].max() - feature_pca[:, show_channel].min() + 1e-8) # Small epsilon to avoid division by zero
|
| 373 |
+
for show_channel in range(n_components):
|
| 374 |
+
feature_pca[:, show_channel] = (feature_pca[:, show_channel] - feature_pca[:, show_channel].mean()) / \
|
| 375 |
+
(feature_pca[:, show_channel].std()*10 + 1e-8) # Small epsilon to avoid division by zero
|
| 376 |
+
|
| 377 |
+
feature_pca = np.clip(feature_pca+0.5, 0, 1)
|
| 378 |
+
# Reshape the PCA result back to (height, width, n_components)
|
| 379 |
+
feature_resized = feature_pca.reshape(batch,height,width,n_components)[...,1:4]
|
| 380 |
+
return feature_resized
|
| 381 |
+
|
| 382 |
+
def normalize_mesh_verts(data):
|
| 383 |
+
# data [N, 3]
|
| 384 |
+
min_vals, _ = torch.min(data, dim=0)
|
| 385 |
+
max_vals, _ = torch.max(data, dim=0)
|
| 386 |
+
bbox_sizes = max_vals - min_vals
|
| 387 |
+
scale = torch.norm(bbox_sizes)
|
| 388 |
+
print("Scale:", scale)
|
| 389 |
+
normalized_verts = verts / scale
|
| 390 |
+
return normalized_verts
|
| 391 |
+
|
| 392 |
+
def plot_pointclouds_with_color_mapping(pc1_f, pc2_f,pc1,pc2, query_points, similarity_threshold=None):
|
| 393 |
+
"""
|
| 394 |
+
Visualizes two 3D point clouds. The second point cloud (pc2) is color-mapped
|
| 395 |
+
using the 'viridis' colormap based on its similarity (proximity) to the sampled
|
| 396 |
+
query points in the first point cloud (pc1).
|
| 397 |
+
|
| 398 |
+
Parameters:
|
| 399 |
+
- pc1: np.ndarray of shape (N, 3), first point cloud #partial
|
| 400 |
+
- pc2: np.ndarray of shape (M, 3), second point cloud # global
|
| 401 |
+
- query_points: list of indices in pc1, representing the query points to compare.
|
| 402 |
+
- similarity_threshold: float, optional, threshold to cap the similarity distance.
|
| 403 |
+
"""
|
| 404 |
+
|
| 405 |
+
|
| 406 |
+
pc1_f = pc1_f / np.linalg.norm(pc1_f, axis=1)[:, None] # Normalize the features
|
| 407 |
+
pc2_f = pc2_f / np.linalg.norm(pc2_f, axis=1)[:, None] # Normalize the features
|
| 408 |
+
# Create a figure with subplots
|
| 409 |
+
fig = plt.figure(figsize=(12, 10))
|
| 410 |
+
num_query_points = len(query_points)
|
| 411 |
+
# Set limits and labels
|
| 412 |
+
size = pc2.max() - pc2.min()
|
| 413 |
+
# Plot the first point cloud in the first subplot
|
| 414 |
+
ax1 = fig.add_subplot(1, num_query_points + 1, 1, projection='3d')
|
| 415 |
+
ax1.scatter(pc2[:, 0], pc2[:, 1], pc2[:, 2], color='grey', label='Point Cloud 1 (Left)', alpha=0.1,s=10)
|
| 416 |
+
|
| 417 |
+
# Define a color list for each query point
|
| 418 |
+
query_colors = cm.tab10(np.linspace(0, 1, num_query_points)) # Use tab10 colormap for distinct colors
|
| 419 |
+
|
| 420 |
+
# Highlight query points in pc1 with different colors
|
| 421 |
+
for i, idx in enumerate(query_points):
|
| 422 |
+
ax1.scatter(pc1[idx, 0], pc1[idx, 1], pc1[idx, 2],
|
| 423 |
+
color=query_colors[i], s=100, edgecolor='k', label=f'Query Point {idx}')
|
| 424 |
+
|
| 425 |
+
ax1.set_title('Point Cloud 1 with Query Points')
|
| 426 |
+
ax1.set_xlabel('X')
|
| 427 |
+
ax1.set_ylabel('Y')
|
| 428 |
+
ax1.set_zlabel('Z')
|
| 429 |
+
ax1.set_xlim(-size / 1.4, size / 1.4)
|
| 430 |
+
ax1.set_ylim(-size / 1.4, size / 1.4)
|
| 431 |
+
ax1.set_zlim(-size / 1.4, size / 1.4)
|
| 432 |
+
ax1.view_init(elev=45, azim=-45)
|
| 433 |
+
ax1.grid(True)
|
| 434 |
+
ax1.legend()
|
| 435 |
+
|
| 436 |
+
# Plot the second point cloud in the subsequent subplots
|
| 437 |
+
for k in range(num_query_points):
|
| 438 |
+
|
| 439 |
+
ax = fig.add_subplot(1, num_query_points + 1, k + 2, projection='3d')
|
| 440 |
+
|
| 441 |
+
# Calculate distances between query points in pc1 and all points in pc2
|
| 442 |
+
similarity =(pc1_f[query_points[k]][None]@ pc2_f.T).reshape(-1) # (1, 3) x (M, 3) = (1, M)
|
| 443 |
+
# For each point in pc2, take the minimum distance to any query point
|
| 444 |
+
min_similarity = np.min(similarity, axis=0)
|
| 445 |
+
# Optionally cap the similarity distances to a threshold (to avoid extreme values)
|
| 446 |
+
similarity_threshold= 0.3
|
| 447 |
+
if similarity_threshold is not None:
|
| 448 |
+
similarity = np.clip(similarity, similarity_threshold,1)
|
| 449 |
+
# Normalize the distances to a range of 0 to 1 for colormap mapping
|
| 450 |
+
similarity = (similarity - np.min(similarity)) / (np.max(similarity) - np.min(similarity))
|
| 451 |
+
colors = cm.plasma(similarity)
|
| 452 |
+
|
| 453 |
+
# Plot the second point cloud with color mapping based on similarity
|
| 454 |
+
ax.scatter(pc2[:, 0], pc2[:, 1], pc2[:, 2], color=colors, s=15, alpha=1.0, label='Point Cloud 2 (Right)', edgecolor='k')
|
| 455 |
+
|
| 456 |
+
ax.set_xlim(-size / 1.4, size / 1.4)
|
| 457 |
+
ax.set_ylim(-size / 1.4, size / 1.4)
|
| 458 |
+
ax.set_zlim(-size / 1.4, size / 1.4)
|
| 459 |
+
ax.set_title(f'QP_{query_points[k]}')
|
| 460 |
+
ax.set_xlabel('X')
|
| 461 |
+
ax.set_ylabel('Y')
|
| 462 |
+
ax.set_zlabel('Z')
|
| 463 |
+
ax.view_init(elev=45, azim=-45)
|
| 464 |
+
ax.grid(True)
|
| 465 |
+
ax.legend()
|
| 466 |
+
|
| 467 |
+
# Show the plot
|
| 468 |
+
plt.tight_layout()
|
| 469 |
+
plt.show()
|
| 470 |
+
|
| 471 |
+
|
| 472 |
+
def plot_pointclouds_3d_with_copca_old(global_sem_pcd, partial_sem_pcd, global_pcd, partial_pcd):
|
| 473 |
+
"""
|
| 474 |
+
Visualizes two point clouds in 3D, coloring them based on their PCA components.
|
| 475 |
+
|
| 476 |
+
Parameters:
|
| 477 |
+
- global_pointcloud: numpy array of shape (N, D) for global point cloud.
|
| 478 |
+
- partial_pointcloud: numpy array of shape (M, D) for partial point cloud.
|
| 479 |
+
"""
|
| 480 |
+
|
| 481 |
+
|
| 482 |
+
n_components = 3
|
| 483 |
+
# Step 1: Perform PCA on both global and partial point clouds
|
| 484 |
+
sem_pca = PCA(n_components=n_components)
|
| 485 |
+
sem_pca = sem_pca.fit(global_sem_pcd) # shape (N+M, 3)
|
| 486 |
+
|
| 487 |
+
transformed_sem_pcd_list = [sem_pca.transform(pcd) for pcd in [global_sem_pcd,partial_sem_pcd]]
|
| 488 |
+
sem_pcd_pca = np.concatenate(transformed_sem_pcd_list,axis=0)
|
| 489 |
+
for show_channel in range(n_components):
|
| 490 |
+
sem_pcd_pca[:, show_channel] = (sem_pcd_pca[:, show_channel] - sem_pcd_pca[:, show_channel].mean()) / \
|
| 491 |
+
(sem_pcd_pca[:, show_channel].std()*5 + 1e-8) # Small epsilon to avoid division by zero
|
| 492 |
+
|
| 493 |
+
# sem_pcd_pca_min = sem_pcd_pca.min()
|
| 494 |
+
# sem_pcd_pca_max = sem_pcd_pca.max()
|
| 495 |
+
# sem_pcd_pca = (sem_pcd_pca- sem_pcd_pca_min) / (sem_pcd_pca_max - sem_pcd_pca_min) # Normalize to [0, 1]
|
| 496 |
+
|
| 497 |
+
sem_pcd_pca = np.clip(sem_pcd_pca[:,:]+0.5, 0, 1)
|
| 498 |
+
global_pca = sem_pcd_pca[:global_sem_pcd.shape[0]] # shape (N, 3)
|
| 499 |
+
partial_pca = sem_pcd_pca[-partial_sem_pcd.shape[0]:] # shape (M, 3)
|
| 500 |
+
|
| 501 |
+
# Step 2: Create a 3D scatter plot
|
| 502 |
+
fig = plt.figure(figsize=(12, 6))
|
| 503 |
+
ax = fig.add_subplot(121, projection='3d')
|
| 504 |
+
|
| 505 |
+
|
| 506 |
+
# Global point cloud
|
| 507 |
+
ax.scatter(global_pcd[:, 0], global_pcd[:, 1], global_pcd[:, 2],
|
| 508 |
+
c=global_pca, marker='o', s=100, alpha=1.0, label='Global Point Cloud')
|
| 509 |
+
|
| 510 |
+
# Set labels for each axis
|
| 511 |
+
# ax.set_xlabel('X axis')
|
| 512 |
+
# ax.set_ylabel('Y axis')
|
| 513 |
+
# ax.set_zlabel('Z axis')
|
| 514 |
+
ax.set_xlim(-0.5, 0.5)
|
| 515 |
+
ax.set_ylim(-0.5, 0.5)
|
| 516 |
+
ax.set_zlim(-0.5, 0.5)
|
| 517 |
+
|
| 518 |
+
ax1 = fig.add_subplot(122, projection='3d')
|
| 519 |
+
|
| 520 |
+
# Partial point cloud
|
| 521 |
+
ax1.scatter(partial_pcd[:, 0], partial_pcd[:, 1], partial_pcd[:, 2],
|
| 522 |
+
c=partial_pca, marker='o', s=100, alpha=1.0, label='Partial Point Cloud')
|
| 523 |
+
|
| 524 |
+
# ax1.scatter(global_pcd[:, 0], global_pcd[:, 1], global_pcd[:, 2],
|
| 525 |
+
# marker='o', s=10, alpha=0.1)
|
| 526 |
+
# Set labels for each axis
|
| 527 |
+
# ax1.set_xlabel('X axis')
|
| 528 |
+
# ax1.set_ylabel('Y axis')
|
| 529 |
+
# ax1.set_zlabel('Z axis')
|
| 530 |
+
|
| 531 |
+
|
| 532 |
+
ax1.set_xlim(-0.5, 0.5)
|
| 533 |
+
ax1.set_ylim(-0.5, 0.5)
|
| 534 |
+
ax1.set_zlim(-0.5, 0.5)
|
| 535 |
+
plt.tight_layout()
|
| 536 |
+
|
| 537 |
+
ax.view_init(120,-95)
|
| 538 |
+
ax1.view_init(120,-95)
|
| 539 |
+
|
| 540 |
+
|
| 541 |
+
ax.set_axis_off()
|
| 542 |
+
ax.set_facecolor((0, 0, 0, 0))
|
| 543 |
+
ax1.set_axis_off()
|
| 544 |
+
ax1.set_facecolor((0, 0, 0, 0))
|
| 545 |
+
|
| 546 |
+
plt.show()
|
| 547 |
+
|
| 548 |
+
|
| 549 |
+
def plot_pointclouds_3d_with_pca(global_sem_pcd, global_pcd):
|
| 550 |
+
"""
|
| 551 |
+
Visualizes two point clouds in 3D, coloring them based on their PCA components.
|
| 552 |
+
|
| 553 |
+
Parameters:
|
| 554 |
+
- global_pointcloud: numpy array of shape (N, D) for global point cloud.
|
| 555 |
+
- partial_pointcloud: numpy array of shape (M, D) for partial point cloud.
|
| 556 |
+
"""
|
| 557 |
+
#sem_pcd = np.concatenate((global_sem_pcd,partial_sem_pcd), axis=0) # shape (N+M, D)
|
| 558 |
+
|
| 559 |
+
# Step 1: Perform PCA on both global and partial point clouds
|
| 560 |
+
sem_pca = PCA(n_components=3)
|
| 561 |
+
sem_pcd_pca = sem_pca.fit_transform(global_sem_pcd) # shape (N+M, 3)
|
| 562 |
+
|
| 563 |
+
for i in range(3): # Iterate over each component (3 in total for RGB)
|
| 564 |
+
sem_pcd_pca_mean = sem_pcd_pca[:, i].mean()
|
| 565 |
+
sem_pcd_pca_std = sem_pcd_pca[:, i].std()
|
| 566 |
+
sem_pcd_pca[:, i] = (sem_pcd_pca[:, i] - sem_pcd_pca_mean) / (sem_pcd_pca_std*5+1e-8) # Normalize to [0, 1]
|
| 567 |
+
|
| 568 |
+
|
| 569 |
+
global_pca = np.clip(sem_pcd_pca+0.5,0,1)
|
| 570 |
+
# scatter plot
|
| 571 |
+
fig = plt.figure(figsize=(6, 6))
|
| 572 |
+
ax = fig.add_subplot(111, projection='3d')
|
| 573 |
+
|
| 574 |
+
# Global point cloud
|
| 575 |
+
ax.scatter(global_pcd[:, 0], global_pcd[:, 1], global_pcd[:, 2],
|
| 576 |
+
c=global_pca, marker='o', s=50, alpha=1.0, label='Global Point Cloud')
|
| 577 |
+
|
| 578 |
+
# Remove axes and background
|
| 579 |
+
ax.set_axis_off()
|
| 580 |
+
|
| 581 |
+
# Set background color to none
|
| 582 |
+
ax.set_facecolor((0, 0, 0, 0))
|
| 583 |
+
# # Set labels for each axis
|
| 584 |
+
# ax.set_xlabel('X axis')
|
| 585 |
+
# ax.set_ylabel('Y axis')
|
| 586 |
+
# ax.set_zlabel('Z axis')
|
| 587 |
+
ax.set_xlim(-0.5, 0.5)
|
| 588 |
+
ax.set_ylim(-0.5, 0.5)
|
| 589 |
+
ax.set_zlim(-0.5, 0.5)
|
| 590 |
+
|
| 591 |
+
ax.view_init(-73,102)
|
| 592 |
+
|
| 593 |
+
return fig
|
| 594 |
+
|
| 595 |
+
|
| 596 |
+
def plot_pointclouds_3d_with_copca(global_sem_pcd_list, global_pcd_list,co_pca=True):
|
| 597 |
+
"""
|
| 598 |
+
Visualizes multiple point clouds in 3D, each in a separate subplot, after applying CoPCA.
|
| 599 |
+
Coloring them based on their PCA components.
|
| 600 |
+
|
| 601 |
+
Parameters:
|
| 602 |
+
- global_sem_pcd_list: list of numpy arrays for semantic point clouds (one per object).
|
| 603 |
+
- global_pcd_list: list of numpy arrays for global point clouds (one per object).
|
| 604 |
+
"""
|
| 605 |
+
num_pcds = len(global_sem_pcd_list) # Number of point clouds
|
| 606 |
+
print("Number of point clouds to visualize:", num_pcds)
|
| 607 |
+
# Step 1: Perform CoPCA (Common PCA) on the semantic point clouds
|
| 608 |
+
# Concatenate all point clouds to perform common PCA
|
| 609 |
+
if co_pca:
|
| 610 |
+
concatenated_pcds = np.concatenate(global_sem_pcd_list, axis=0) # shape (N_total, D)
|
| 611 |
+
copca = PCA(n_components=3, random_state=0)
|
| 612 |
+
copca.fit(concatenated_pcds[:1024]) # Fit PCA on all point clouds together
|
| 613 |
+
transformed_sem_pcd_list = [copca.transform(pcd) for pcd in global_sem_pcd_list]
|
| 614 |
+
|
| 615 |
+
|
| 616 |
+
signs = np.sign(np.sum(transformed_sem_pcd_list[0], axis=0))
|
| 617 |
+
# Post-process to ensure consistent orientation of PCA components
|
| 618 |
+
for i, transformed_pcd in enumerate(transformed_sem_pcd_list):
|
| 619 |
+
# For each component (column), align sign based on the sum of values in the column
|
| 620 |
+
transformed_sem_pcd_list[i] = transformed_pcd * signs
|
| 621 |
+
else:
|
| 622 |
+
copca = PCA(n_components=3)
|
| 623 |
+
transformed_sem_pcd_list = [copca.fit_transform(pcd) for pcd in global_sem_pcd_list]
|
| 624 |
+
# Post-process to ensure consistent orientation of PCA components
|
| 625 |
+
for i, transformed_pcd in enumerate(transformed_sem_pcd_list):
|
| 626 |
+
signs = np.sign(np.sum(transformed_pcd, axis=0))
|
| 627 |
+
# For each component (column), align sign based on the sum of values in the column
|
| 628 |
+
transformed_sem_pcd_list[i] = transformed_pcd * signs
|
| 629 |
+
|
| 630 |
+
|
| 631 |
+
|
| 632 |
+
# Create a figure with subplots arranged in a grid (based on number of point clouds)
|
| 633 |
+
fig = plt.figure(figsize=(6 * num_pcds, 6)) # Adjust figure size based on the number of subplots
|
| 634 |
+
|
| 635 |
+
# Loop over the point clouds
|
| 636 |
+
for idx, (sem_pcd_pca, global_pcd) in enumerate(zip(transformed_sem_pcd_list, global_pcd_list)):
|
| 637 |
+
ax = fig.add_subplot(1, num_pcds, idx + 1, projection='3d')
|
| 638 |
+
|
| 639 |
+
# Step 2: Normalize the PCA-transformed data to use as colors
|
| 640 |
+
for i in range(3): # Iterate over each component (3 in total for RGB)
|
| 641 |
+
pca_mean = sem_pcd_pca[:, i].mean()
|
| 642 |
+
pca_std = sem_pcd_pca[:, i].std()
|
| 643 |
+
sem_pcd_pca[:, i] = (sem_pcd_pca[:, i] - pca_mean) / (pca_std * 5 + 1e-8) # Normalize
|
| 644 |
+
|
| 645 |
+
global_pca_colors = np.clip(sem_pcd_pca + 0.5, 0, 1) # Map to [0, 1] for RGB
|
| 646 |
+
|
| 647 |
+
# Scatter plot for this point cloud in the current subplot
|
| 648 |
+
ax.scatter(global_pcd[:, 0], global_pcd[:, 1], global_pcd[:, 2],
|
| 649 |
+
c=global_pca_colors, marker='o', s=50, alpha=1.0)
|
| 650 |
+
|
| 651 |
+
# Remove axes and background
|
| 652 |
+
ax.set_axis_off()
|
| 653 |
+
ax.set_facecolor((0, 0, 0, 0))
|
| 654 |
+
|
| 655 |
+
# Set axis limits for each subplot
|
| 656 |
+
ax.set_xlim(-0.5, 0.5)
|
| 657 |
+
ax.set_ylim(-0.5, 0.5)
|
| 658 |
+
ax.set_zlim(-0.5, 0.5)
|
| 659 |
+
|
| 660 |
+
# Set view angle
|
| 661 |
+
ax.view_init(-55, 102)
|
| 662 |
+
|
| 663 |
+
# Adjust spacing between subplots
|
| 664 |
+
plt.tight_layout()
|
| 665 |
+
|
| 666 |
+
return fig
|
| 667 |
+
|
| 668 |
+
|
| 669 |
+
|
| 670 |
+
def unnormalize(x):
|
| 671 |
+
# x.shape : [H,W,3]
|
| 672 |
+
mean = np.array([0.485, 0.456, 0.406])
|
| 673 |
+
std = np.array([0.229, 0.224, 0.225])
|
| 674 |
+
return x * std + mean
|
| 675 |
+
|
| 676 |
+
|
| 677 |
+
from custom_utils.housecat6d_dataset import HouseCat6DTrainingDataset
|
| 678 |
+
trainset = HouseCat6DTrainingDataset(image_size=420, sample_num=1024,data_dir='/media/xyz/data1/HouseCat6D')
|
| 679 |
+
|
| 680 |
+
vis = True
|
| 681 |
+
device = "cuda"
|
| 682 |
+
import matplotlib
|
| 683 |
+
import open3d as o3d
|
| 684 |
+
from pytorch3d.io import load_objs_as_meshes
|
| 685 |
+
import trimesh
|
| 686 |
+
matplotlib.use('TkAgg')
|
| 687 |
+
|
| 688 |
+
#cat_list = ['bottle','box','can','cup','cutlery','remote','shoe','tube','teapot']
|
| 689 |
+
cat_list = ['cup']
|
| 690 |
+
|
| 691 |
+
|
| 692 |
+
sem_global_list = []
|
| 693 |
+
sem_global_pcd_list = []
|
| 694 |
+
|
| 695 |
+
# # load semantc feature and show
|
| 696 |
+
# ########################################
|
| 697 |
+
save_dir = 'Yung/yung_large_files/semantic_feature/test_notebook/8v'
|
| 698 |
+
# #save_dir = './80views_textured_token'
|
| 699 |
+
# if True:
|
| 700 |
+
# for cat in cat_list:
|
| 701 |
+
# # # orriginal
|
| 702 |
+
# # with open(f'/mnt/4T/Yung/yung_large_files/semantic_feature/test_notebook/housecat_{cat}/raw/housecat1_train.txt', 'r') as f:
|
| 703 |
+
# # instances = [line.strip() for line in f.readlines()]
|
| 704 |
+
|
| 705 |
+
# # print(instances)
|
| 706 |
+
# # revised
|
| 707 |
+
# # instance try cup-grey_handle
|
| 708 |
+
# instances = ['cup-grey_handle']
|
| 709 |
+
# sem_global_list = []
|
| 710 |
+
# sem_global_pcd_list = []
|
| 711 |
+
|
| 712 |
+
# # Load the mean shape point cloud
|
| 713 |
+
# meanshape_path = f'Yung/yung_large_files/semantic_feature/test_notebook/saved_pcd/{cat}/mean_shape/mean_shape_pcd_1.txt'
|
| 714 |
+
# meanshape_pcd_np = np.loadtxt(meanshape_path)
|
| 715 |
+
|
| 716 |
+
# meanshape_pcd_tensor = torch.from_numpy(meanshape_pcd_np)
|
| 717 |
+
# M = meanshape_pcd_tensor.shape[0]
|
| 718 |
+
# meanshape_points = meanshape_pcd_tensor.view(1, M, 3).float()
|
| 719 |
+
# #make sure map to cuda0
|
| 720 |
+
# average_aggregated_features = torch.load(f'/mnt/4T/Yung/yung_large_files/semantic_feature/test_notebook/8v_key/sem_cat_pcd_untex/{cat}_dino_feature.pt', map_location={"cuda:1": "cuda:0"})
|
| 721 |
+
# sem_global_pcd_list.append(meanshape_points[0])
|
| 722 |
+
# sem_global_list.append(average_aggregated_features[0].detach().cpu())
|
| 723 |
+
# #fig =plot_pointclouds_3d_with_pca(average_aggregated_features[0].detach().cpu(),meanshape_points[0])
|
| 724 |
+
# #fig.savefig('test.png')
|
| 725 |
+
# for j,instance in enumerate(instances):
|
| 726 |
+
# #break
|
| 727 |
+
# print("Processing", instance)
|
| 728 |
+
# #obj_path = f'/media/xyz/data/HouseCat6D/obj_models_small_size_final/{cat}/{instance}.obj'
|
| 729 |
+
# #instance_pcd_tensor = torch.load(f'{save_dir}/saved_pcd_untex/{cat}/{instance}_pcd.pt')[0]
|
| 730 |
+
# #obj_path = f'/media/xyz/data1/HouseCat6D/obj_models_small_size_final/{cat}/{instance}.obj'
|
| 731 |
+
# # instance_pcd_path = f'Yung/yung_large_files/semantic_feature/test_notebook/saved_pcd/{cat}/test/{instance}.txt'
|
| 732 |
+
# # instance_pcd_np = np.loadtxt(instance_pcd_path)
|
| 733 |
+
# instance_pcd_path = f'Yung/yung_large_files/pose_can_results/housecat6d_sonata_feature/scene01/000000/cup-grey_handle/input_pca.ply'
|
| 734 |
+
# pcd = o3d.io.read_point_cloud(instance_pcd_path)
|
| 735 |
+
# instance_pcd_np = np.asarray(pcd.points)
|
| 736 |
+
|
| 737 |
+
# # Rotate 180 degrees around y axis
|
| 738 |
+
# rotation_matrix = np.array([
|
| 739 |
+
# [-1, 0, 0],
|
| 740 |
+
# [0, 1, 0],
|
| 741 |
+
# [0, 0, -1]
|
| 742 |
+
# ])
|
| 743 |
+
# instance_pcd_np = instance_pcd_np @ rotation_matrix.T
|
| 744 |
+
|
| 745 |
+
|
| 746 |
+
# # Load the instance point cloud
|
| 747 |
+
# instance_pcd_tensor = torch.from_numpy(instance_pcd_np)
|
| 748 |
+
# N = instance_pcd_tensor.shape[0]
|
| 749 |
+
# instance_points = instance_pcd_tensor.view(1, N, 3).float()
|
| 750 |
+
# try:
|
| 751 |
+
# # aggregated_features = torch.load(f'{save_dir}/saved_dino_pcd_untex/{cat}/{instance}_dino_feature.pt')
|
| 752 |
+
# aggregated_features = average_aggregated_features
|
| 753 |
+
# except:
|
| 754 |
+
# print(f"Warning: {instance} not found.")
|
| 755 |
+
# continue
|
| 756 |
+
# # plot_pointclouds_3d_with_pca(aggregated_features[0].detach().cpu(),
|
| 757 |
+
# # instance_points[0])
|
| 758 |
+
# sem_global_pcd_list.append(instance_points[0].detach().cpu())
|
| 759 |
+
# sem_global_list.append(aggregated_features[0].detach().cpu())
|
| 760 |
+
# if len(sem_global_list)>4:
|
| 761 |
+
# break
|
| 762 |
+
|
| 763 |
+
# fig = plot_pointclouds_3d_with_copca(sem_global_list,sem_global_pcd_list,co_pca=True)
|
| 764 |
+
# fig.savefig(f'./{save_dir}/{cat}_sam3d.png')
|
| 765 |
+
# ###############################
|
| 766 |
+
|
| 767 |
+
|
| 768 |
+
model_dict={'small':'dinov2_vits14',
|
| 769 |
+
'base':'dinov2_vitb14',
|
| 770 |
+
'large':'dinov2_vitl14',
|
| 771 |
+
'giant':'dinov2_vitg14'}
|
| 772 |
+
extractor = ViTExtractor(model_dict['small'],14)
|
| 773 |
+
# use GPPU0
|
| 774 |
+
extractor.model = extractor.model.cuda(0) # the stride of first conv control outputs resolution
|
| 775 |
+
|
| 776 |
+
# extractor = torch.hub.load('facebookresearch/dinov2', model_dict['small'], pretrained=True).cuda()
|
| 777 |
+
|
| 778 |
+
|
| 779 |
+
# cat_list = ['bottle','box','can','cup','cutlery','glass','remote','shoe','tube','teapot']
|
| 780 |
+
cat_list = ['cup']
|
| 781 |
+
|
| 782 |
+
#cat_list = ['teapot']
|
| 783 |
+
#TODO: if condition for tex rendering
|
| 784 |
+
for cat in cat_list:
|
| 785 |
+
# # orriginal
|
| 786 |
+
# with open(f'/mnt/4T/Yung/yung_large_files/semantic_feature/test_notebook/housecat_{cat}/raw/housecat1_train.txt', 'r') as f:
|
| 787 |
+
# instances = [line.strip() for line in f.readlines()]
|
| 788 |
+
|
| 789 |
+
# print(instances)
|
| 790 |
+
#revised
|
| 791 |
+
# # instance try cup-grey_handle
|
| 792 |
+
# instances = ['cup-grey_handle']
|
| 793 |
+
|
| 794 |
+
# instance try cup-grey_handle
|
| 795 |
+
instances = ['cup-grey_handle']
|
| 796 |
+
|
| 797 |
+
|
| 798 |
+
aggregated_features_list = [] # N * [1, 1024, 384]
|
| 799 |
+
# Load the mean shape point cloud
|
| 800 |
+
meanshape_path = f'Yung/yung_large_files/semantic_feature/test_notebook/saved_pcd/{cat}/mean_shape/mean_shape_pcd_1.txt'
|
| 801 |
+
meanshape_pcd_np = np.loadtxt(meanshape_path)
|
| 802 |
+
meanshape_pcd_tensor = torch.from_numpy(meanshape_pcd_np)
|
| 803 |
+
M = meanshape_pcd_tensor.shape[0]
|
| 804 |
+
# modify for cuda0
|
| 805 |
+
meanshape_points = meanshape_pcd_tensor.view(1, M, 3).float().cuda(0)
|
| 806 |
+
|
| 807 |
+
|
| 808 |
+
for j,instance in enumerate(instances):
|
| 809 |
+
# #original
|
| 810 |
+
# # if instance != 'bottle-85_alcool':
|
| 811 |
+
# # continue
|
| 812 |
+
# print("Processing", instance)
|
| 813 |
+
# obj_path = f'pose_dataset/HouseCat6D/obj_models_small_size_final/{cat}/{instance}.obj'
|
| 814 |
+
# instance_pcd_path = f'Yung/yung_large_files/semantic_feature/test_notebook/saved_pcd/{cat}/test/{instance}.txt'
|
| 815 |
+
|
| 816 |
+
# # Load the instance point cloud
|
| 817 |
+
# instance_pcd_np = np.loadtxt(instance_pcd_path)
|
| 818 |
+
# try:
|
| 819 |
+
# verts, faces, aux = load_obj(obj_path)
|
| 820 |
+
# except ValueError as e:
|
| 821 |
+
# print(f"Warning: {e}, attempting to load without material.")
|
| 822 |
+
|
| 823 |
+
# try:
|
| 824 |
+
# verts, faces, aux = load_obj(obj_path, load_textures=True)
|
| 825 |
+
# except ValueError as e2:
|
| 826 |
+
# print(f"Failed to load {obj_path} without material: {e2}")
|
| 827 |
+
# continue
|
| 828 |
+
# meshes = Meshes(verts=[verts], faces=[faces.verts_idx], textures=None)
|
| 829 |
+
|
| 830 |
+
#modify for sam3d
|
| 831 |
+
print("Processing", instance)
|
| 832 |
+
obj_path = f'/mnt/4T/Yung/pose_repo_temp/sam-3d-objects/notebook/gaussians/single/housecat6d_relight/000000_relight_msr_000000_cup-grey_handle.ply'
|
| 833 |
+
instance_pcd_path = obj_path
|
| 834 |
+
pcd = o3d.io.read_point_cloud(instance_pcd_path)
|
| 835 |
+
instance_pcd_np = np.asarray(pcd.points)
|
| 836 |
+
instance_pcd_tensor = torch.from_numpy(instance_pcd_np)
|
| 837 |
+
N = instance_pcd_tensor.shape[0]
|
| 838 |
+
# modify for cuda0
|
| 839 |
+
instance_points = instance_pcd_tensor.view(1, N, 3).float().cuda(0)
|
| 840 |
+
|
| 841 |
+
try:
|
| 842 |
+
pcd = o3d.io.read_point_cloud(obj_path)
|
| 843 |
+
pcd.estimate_normals(
|
| 844 |
+
search_param=o3d.geometry.KDTreeSearchParamHybrid(
|
| 845 |
+
radius=0.02,
|
| 846 |
+
max_nn=30
|
| 847 |
+
)
|
| 848 |
+
)
|
| 849 |
+
|
| 850 |
+
# Poisson
|
| 851 |
+
mesh, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
|
| 852 |
+
pcd, depth=8
|
| 853 |
+
)
|
| 854 |
+
|
| 855 |
+
# Density trimming
|
| 856 |
+
densities = np.asarray(densities)
|
| 857 |
+
mesh = mesh.select_by_index(
|
| 858 |
+
np.where(densities > np.quantile(densities, 0.05))[0]
|
| 859 |
+
)
|
| 860 |
+
|
| 861 |
+
# Keep largest component
|
| 862 |
+
clusters, counts, _ = mesh.cluster_connected_triangles()
|
| 863 |
+
clusters = np.asarray(clusters)
|
| 864 |
+
counts = np.asarray(counts)
|
| 865 |
+
mesh.remove_triangles_by_mask(clusters != counts.argmax())
|
| 866 |
+
mesh.remove_unreferenced_vertices()
|
| 867 |
+
|
| 868 |
+
verts = np.asarray(mesh.vertices)
|
| 869 |
+
faces = np.asarray(mesh.triangles)
|
| 870 |
+
print(f"Loaded PLY with {verts.shape[0]} vertices and {faces.shape[0]} faces.")
|
| 871 |
+
|
| 872 |
+
# Extract texture colors from point cloud
|
| 873 |
+
tex = None
|
| 874 |
+
if pcd.has_colors():
|
| 875 |
+
print("Point cloud has colors, extracting texture.")
|
| 876 |
+
colors = np.asarray(pcd.colors)
|
| 877 |
+
# Map point cloud colors to mesh vertices using nearest neighbor
|
| 878 |
+
pcd_tree = o3d.geometry.KDTreeFlann(pcd)
|
| 879 |
+
vertex_colors = np.zeros((verts.shape[0], 3))
|
| 880 |
+
for i, vert in enumerate(verts):
|
| 881 |
+
_, idx, _ = pcd_tree.search_knn_vector_3d(vert, 1)
|
| 882 |
+
vertex_colors[i] = colors[idx[0]]
|
| 883 |
+
tex = torch.from_numpy(vertex_colors).float().to(device=device)
|
| 884 |
+
|
| 885 |
+
except Exception as e:
|
| 886 |
+
print(f"Warning: Failed to load PLY: {e}")
|
| 887 |
+
continue
|
| 888 |
+
|
| 889 |
+
# Initialise the mesh with textures
|
| 890 |
+
verts = torch.from_numpy(verts).float()
|
| 891 |
+
verts = normalize_mesh_verts(verts)
|
| 892 |
+
|
| 893 |
+
if isinstance(faces, np.ndarray):
|
| 894 |
+
faces = torch.from_numpy(faces)
|
| 895 |
+
|
| 896 |
+
faces = faces.to(device=device, dtype=torch.int64)
|
| 897 |
+
verts = verts.to(device=device, dtype=torch.float32)
|
| 898 |
+
# Ensure shape is (1, V, 3)
|
| 899 |
+
if tex.dim() == 2:
|
| 900 |
+
tex = tex.unsqueeze(0)
|
| 901 |
+
|
| 902 |
+
tex = TexturesVertex(verts_features=tex)
|
| 903 |
+
|
| 904 |
+
meshes = Meshes(verts=[verts], faces=[faces], textures=None)
|
| 905 |
+
|
| 906 |
+
|
| 907 |
+
if meshes.textures is None:
|
| 908 |
+
meshes.textures = TexturesVertex(
|
| 909 |
+
verts_features=torch.ones_like(meshes.verts_padded(), device=device)
|
| 910 |
+
)
|
| 911 |
+
|
| 912 |
+
# Also save as OBJ format to preserve texture information
|
| 913 |
+
o3d.io.write_triangle_mesh(f'{save_dir}/mesh_{instance}.obj', mesh)
|
| 914 |
+
|
| 915 |
+
# render the mesh with 8 views, scale means the distance from the object to the camera
|
| 916 |
+
image_size=(420,420)
|
| 917 |
+
#images,fragments,cameras = render_batch(meshes,image_size=image_size,scale=1.0)
|
| 918 |
+
images,fragments,cameras = render(meshes,image_size=image_size,scale=2.0)
|
| 919 |
+
|
| 920 |
+
os.makedirs(f'{save_dir}/{cat}_rgb_dino_untex-try', exist_ok=True)
|
| 921 |
+
rgb = images.cpu().numpy()[:, :, :, :3]
|
| 922 |
+
image_grid(rgb, rows=1, cols=8, rgb=True)
|
| 923 |
+
plt.savefig(f'{save_dir}/{cat}_rgb_dino_untex-try/{instance}_rendering-sam3d.png')
|
| 924 |
+
plt.close()
|
| 925 |
+
|
| 926 |
+
# get the feature point cloud
|
| 927 |
+
feature_point_cloud, dino_feat_masked, feature_point_cloud_list = fuse_feature_rgbd(extractor,images,fragments,cameras)
|
| 928 |
+
|
| 929 |
+
# get the downsampled aggregated feature point cloud
|
| 930 |
+
num_pts= 1024
|
| 931 |
+
nn_num= 100 # larger nn_num will make the feature more smooth
|
| 932 |
+
sampled_points,aggregated_features = downsample_with_knn_feature_aggregation(feature_point_cloud,num_pts,nn_num)
|
| 933 |
+
|
| 934 |
+
# #Needed
|
| 935 |
+
# index = np.random.choice(partial_feature_point_cloud.shape[0], 1024, replace=False)
|
| 936 |
+
# plot_pointclouds_3d_with_copca(average_aggregated_features.squeeze(0).detach().cpu().numpy(),
|
| 937 |
+
# partial_feature_point_cloud[index,3:],
|
| 938 |
+
# sampled_points.squeeze(0).detach().cpu().numpy(),
|
| 939 |
+
# partial_feature_point_cloud[index,:3])
|
| 940 |
+
|
| 941 |
+
|
| 942 |
+
q=0
|
| 943 |
+
|
| 944 |
+
if False:
|
| 945 |
+
q+=1
|
| 946 |
+
inputs = trainset[q]
|
| 947 |
+
rgb = inputs['rgb'][None].cuda()
|
| 948 |
+
pts = inputs['pts'][None]
|
| 949 |
+
choose = inputs['choose'][None]
|
| 950 |
+
model = inputs['model'][None].cuda()
|
| 951 |
+
rgb = inputs['rgb'][None].cuda()
|
| 952 |
+
|
| 953 |
+
_desc_q = extractor.forward_features(rgb)["x_prenorm"][:, :]
|
| 954 |
+
#_desc_q = extractor.extract_descriptors(rgb,layer=11,facet='token',include_cls=True).squeeze(1) # B,L,C
|
| 955 |
+
# _norm_q = torch.linalg.norm(_desc_q, dim=-1)[:, :, None]
|
| 956 |
+
# _desc_q = _desc_q / (_norm_q)
|
| 957 |
+
|
| 958 |
+
dino_feature = _desc_q[:,1:,:]
|
| 959 |
+
|
| 960 |
+
|
| 961 |
+
#dino_feature = self.rgb_extractor.forward_features(rgb)["x_prenorm"][:, 1:]
|
| 962 |
+
#rgb=self.rgb_extractor.preprocess_pil(rgb)
|
| 963 |
+
#dino_feature = self.rgb_extractor.extract_descriptors(rgb,layer=11,facet='key') # (1,900,384)
|
| 964 |
+
f_dim = dino_feature.shape[-1]
|
| 965 |
+
num_patches =int(dino_feature.shape[1]**0.5) # 1
|
| 966 |
+
b=1
|
| 967 |
+
dino_feature = dino_feature.reshape(b, num_patches, num_patches, f_dim).permute(0,3,1,2)
|
| 968 |
+
|
| 969 |
+
dino_feature = F.interpolate(dino_feature, size=(num_patches * 14, num_patches * 14), mode='nearest')
|
| 970 |
+
dino_feature_2d_vis = dino_feature.detach().cpu()[0] #384, 224,224
|
| 971 |
+
|
| 972 |
+
b, d = dino_feature.shape[0:2]
|
| 973 |
+
dino_feature = dino_feature.reshape(b,d,-1)
|
| 974 |
+
choose_2 = choose.unsqueeze(1).repeat(1, d, 1).cuda()
|
| 975 |
+
dino_feature = torch.gather(dino_feature,2,choose_2).contiguous() # b,d,n
|
| 976 |
+
|
| 977 |
+
#dino_feature = dino_feature / torch.std(dino_feature, dim=1, keepdim=True)
|
| 978 |
+
#dino_feature = torch.norm(dino_feature, dim=1, keepdim=True)
|
| 979 |
+
#choose_dino = choose.unsqueeze(1).repeat(1, d, 1Z
|
| 980 |
+
#sem_model = sem_model / torch.std(sem_model, dim=-1, keepdim=True)
|
| 981 |
+
#visual_global_sem_high = sem_model.detach().cpu().numpy()[0] #1024,384
|
| 982 |
+
visual_partial_sem_high = dino_feature.permute(0,2,1).detach().cpu().numpy()[0] #1024,128
|
| 983 |
+
|
| 984 |
+
#visual_global_sem_low = self.feature_mlp(sem_model.permute(0,2,1)).permute(0,2,1).detach().cpu().numpy()[0]
|
| 985 |
+
#visual_partial_sem_low = rgb_local.permute(0,2,1).detach().cpu().numpy()[0]
|
| 986 |
+
# transform the pts with GT 9D Pose into object coordinate
|
| 987 |
+
translation_gt = inputs['translation_label'][None]
|
| 988 |
+
rotation_gt = inputs['rotation_label'][None]
|
| 989 |
+
size_gt = inputs['size_label'][None]
|
| 990 |
+
pts_obj_frame = (inputs['pts'] - translation_gt.unsqueeze(1)) / (torch.norm(size_gt, dim=1).view(b, 1, 1) + 1e-8) @ rotation_gt
|
| 991 |
+
#kpt_obj_frame = (kpt_3d - translation_gt.unsqueeze(1)) / (torch.norm(size_gt, dim=1).view(b, 1, 1) + 1e-8) @ rotation_gt
|
| 992 |
+
|
| 993 |
+
# dino_feature_2d_vis_pca = vis_pca_pixelwise(dino_feature_2d_vis[None])[0]
|
| 994 |
+
# plt.imshow(dino_feature_2d_vis_pca[:,:,:3])
|
| 995 |
+
# plt.show()
|
| 996 |
+
# fig =plt.figure()
|
| 997 |
+
# rgb_unnorm = unnormalize(rgb[0].permute(1,2,0).detach().cpu())
|
| 998 |
+
# plt.imshow(rgb_unnorm)
|
| 999 |
+
# plt.show()
|
| 1000 |
+
# image_mask = ((rgb_unnorm.clone().sum(axis=2) >0.1)*1.0)[None,None] # 224,224
|
| 1001 |
+
|
| 1002 |
+
# rgb_mask = np.array(image_mask[0,0,:,:,None]).repeat(384, axis=2).transpose(2,0,1)
|
| 1003 |
+
|
| 1004 |
+
# dino_feature_2d_vis[rgb_mask==0] = 0
|
| 1005 |
+
# masked_dino_feature_2d_vis_pca = vis_pca_pixelwise(dino_feature_2d_vis[None])[0]
|
| 1006 |
+
# plt.imshow(masked_dino_feature_2d_vis_pca[:,:,:])
|
| 1007 |
+
# plt.show()
|
| 1008 |
+
|
| 1009 |
+
|
| 1010 |
+
# print('self.pca.cateagg-partial')
|
| 1011 |
+
# index = np.random.choice(partial_feature_point_cloud.shape[0], 1024, replace=False)
|
| 1012 |
+
# #average_aggregated_features = torch.load(f'sem_cat_pcd/{cat}_dino_feature.pt')
|
| 1013 |
+
|
| 1014 |
+
average_aggregated_features = torch.load(f'/home/xyz/anything6d_project/Sem-GCE-AG-Pose/sem_cat_pcd/{cat}_dino_feature.pt')
|
| 1015 |
+
# #plot_pointclouds_3d_with_copca(aggregated_features.squeeze(0).detach().cpu().numpy(), partial_feature_point_cloud[index,3:], sampled_points.squeeze(0).detach().cpu().numpy(), pts_obj_frame)
|
| 1016 |
+
|
| 1017 |
+
plot_pointclouds_3d_with_copca_old(average_aggregated_features.squeeze(0).detach().cpu().numpy(),
|
| 1018 |
+
visual_partial_sem_high,
|
| 1019 |
+
sampled_points.squeeze(0).detach().cpu().numpy(),
|
| 1020 |
+
pts_obj_frame[0].detach().cpu().numpy())
|
| 1021 |
+
plt.show()
|
| 1022 |
+
|
| 1023 |
+
|
| 1024 |
+
# plot_pointclouds_3d_with_copca(average_aggregated_features.squeeze(0).detach().cpu().numpy(),
|
| 1025 |
+
# visual_partial_sem_high,
|
| 1026 |
+
# sampled_points.squeeze(0).detach().cpu().numpy(),
|
| 1027 |
+
# pts_obj_frame[0].detach().cpu().numpy())
|
| 1028 |
+
|
| 1029 |
+
|
| 1030 |
+
# #query_points =np.random.choice(1024, 3)
|
| 1031 |
+
# query_points, sampled_indices = sample_farthest_points(pts_obj_frame, K=4) # Shape: (1, 1024, 3), (1, 1024)
|
| 1032 |
+
# plot_pointclouds_with_color_mapping(visual_partial_sem_high,
|
| 1033 |
+
# aggregated_features.squeeze(0).detach().cpu().numpy(),
|
| 1034 |
+
# pts_obj_frame[0].detach().cpu().numpy(),
|
| 1035 |
+
# model[0].detach().cpu().numpy(),
|
| 1036 |
+
# sampled_indices[0], similarity_threshold=None)
|
| 1037 |
+
|
| 1038 |
+
|
| 1039 |
+
# # plot_pointclouds_3d_with_copca(average_aggregated_features.squeeze(0).detach().cpu().numpy(), partial_feature_point_cloud[index,3:], sampled_points.squeeze(0).detach().cpu().numpy(), partial_feature_point_cloud[index,:3])
|
| 1040 |
+
# # plot_pointclouds_3d_with_pca(average_aggregated_features.squeeze(0).detach().cpu().numpy(), partial_feature_point_cloud[index,3:], sampled_points.squeeze(0).detach().cpu().numpy(), partial_feature_point_cloud[index,:3])
|
| 1041 |
+
# partial_feature_point_cloud = feature_point_cloud_list[5]
|
| 1042 |
+
# plot_pointclouds_3d_with_copca(visual_partial_sem_high,
|
| 1043 |
+
# partial_feature_point_cloud[index,3:],
|
| 1044 |
+
# pts_obj_frame[0].detach().cpu().numpy(),
|
| 1045 |
+
# partial_feature_point_cloud[index,:3])
|
| 1046 |
+
|
| 1047 |
+
# plot_pointclouds_3d_with_copca(average_aggregated_features.squeeze(0).detach().cpu().numpy(), aggregated_features.squeeze(0).detach().cpu().numpy(), sampled_points.squeeze(0).detach().cpu().numpy(), sampled_points.squeeze(0).detach().cpu().numpy())
|
| 1048 |
+
|
| 1049 |
+
|
| 1050 |
+
|
| 1051 |
+
os.makedirs(f'{save_dir}/saved_dino_pcd_untex-try/{cat}', exist_ok=True)
|
| 1052 |
+
torch.save(aggregated_features, f'{save_dir}/saved_dino_pcd_untex-try/{cat}/{instance}_dino_feature-notexture_sam3d.pt')
|
| 1053 |
+
|
| 1054 |
+
os.makedirs(f'{save_dir}/saved_pcd_untex-try/{cat}', exist_ok=True)
|
| 1055 |
+
torch.save(sampled_points, f'{save_dir}/saved_pcd_untex-try/{cat}/{instance}_pcd-notexture_sam3d.pt')
|
| 1056 |
+
|
| 1057 |
+
aggregated_features_list.append(aggregated_features)
|
| 1058 |
+
# #break
|
| 1059 |
+
vis_dino = vis_pca_pixelwise(np.array(dino_feat_masked))
|
| 1060 |
+
vis_img = np.clip(vis_dino[:,:,:,:],a_min=0,a_max=1)
|
| 1061 |
+
image_grid(vis_img, rows=1, cols=8, rgb=True)
|
| 1062 |
+
|
| 1063 |
+
os.makedirs(f'{save_dir}/{cat}_rgb_dino_untex-try', exist_ok=True)
|
| 1064 |
+
plt.savefig(f'{save_dir}/{cat}_rgb_dino_untex-try/{instance}_dino-notexture_sam3d.png')
|
| 1065 |
+
plt.close()
|
| 1066 |
+
if False:
|
| 1067 |
+
|
| 1068 |
+
rgb = images.cpu().numpy()[:, :, :, :3]
|
| 1069 |
+
mask = images[:, ..., 3].cpu().numpy()!=0
|
| 1070 |
+
depth_image = fragments[:, ..., 0].cpu().numpy()*mask
|
| 1071 |
+
image_grid(rgb, rows=1, cols=8, rgb=True)
|
| 1072 |
+
# os.makedirs(f'/home/tulrfpf/code/PointFlowRenderer/{cat}_rgb_dino', exist_ok=True)
|
| 1073 |
+
# plt.savefig(f'/home/tulrfpf/code/PointFlowRenderer/{cat}_rgb_dino/{instance}_rgb.png')
|
| 1074 |
+
# image_grid(depth_image[...,None], rows=2, cols=4, rgb=True)
|
| 1075 |
+
# image_grid(mask[...,None], rows=2, cols=4, rgb=True)
|
| 1076 |
+
|
| 1077 |
+
|
| 1078 |
+
|
| 1079 |
+
fig = plt.figure(figsize=(10, 10))
|
| 1080 |
+
ax = fig.add_subplot(111, projection="3d")
|
| 1081 |
+
#ax.scatter(sampled_points[:, 2], sampled_points[:,0], sampled_points[:, 1], c="b")
|
| 1082 |
+
pca_color =vis_pca(feature_point_cloud[:, 3:])
|
| 1083 |
+
ax.scatter(feature_point_cloud[:, 2], feature_point_cloud[:, 0], feature_point_cloud[:, 1], c=pca_color,s=0.1)
|
| 1084 |
+
#create_camera_geometry_batch(ax=ax,R_batch=R,T_batch=T,order=(2,0,1))
|
| 1085 |
+
ax.set_xlabel("z")
|
| 1086 |
+
ax.set_ylabel("x")
|
| 1087 |
+
ax.set_zlabel("y")
|
| 1088 |
+
ax.set_xlim(-2, 2)
|
| 1089 |
+
ax.set_ylim(-2, 2)
|
| 1090 |
+
ax.set_zlim(-2, 2)
|
| 1091 |
+
plt.title("Sampled Dense Points from Mesh")
|
| 1092 |
+
plt.show()
|
| 1093 |
+
|
| 1094 |
+
fig = plt.figure(figsize=(10, 10))
|
| 1095 |
+
ax = fig.add_subplot(111, projection="3d")
|
| 1096 |
+
pca_color =vis_pca(aggregated_features.squeeze(0))
|
| 1097 |
+
sampled_points= sampled_points.squeeze(0).cpu().detach().numpy()
|
| 1098 |
+
ax.scatter(sampled_points[:, 2], sampled_points[:, 0], sampled_points[:, 1], c=pca_color,s=50)
|
| 1099 |
+
#create_camera_geometry_batch(ax=ax,R_batch=R,T_batch=T,order=(2,0,1))
|
| 1100 |
+
ax.set_xlabel("z")
|
| 1101 |
+
ax.set_ylabel("x")
|
| 1102 |
+
ax.set_zlabel("y")
|
| 1103 |
+
ax.set_xlim(-2, 2)
|
| 1104 |
+
ax.set_ylim(-2, 2)
|
| 1105 |
+
ax.set_zlim(-2, 2)
|
| 1106 |
+
plt.title("Sampled Sparse Points from Mesh")
|
| 1107 |
+
plt.show()
|
| 1108 |
+
#break
|
| 1109 |
+
# Assign the aggregated features to the mean shape point cloud
|
| 1110 |
+
aggregated_features_tensor = torch.cat(aggregated_features_list, dim=0) #[N, 1024, 384]
|
| 1111 |
+
average_aggregated_features = aggregated_features_tensor.mean(dim=0, keepdim=True)
|
| 1112 |
+
print("Average Aggregated Features Shape:", average_aggregated_features.shape) # Should be (1, 1024, 384)
|
| 1113 |
+
|
| 1114 |
+
os.makedirs(f'{save_dir}/sem_cat_pcd_untex-try', exist_ok=True)
|
| 1115 |
+
torch.save(average_aggregated_features, f'{save_dir}/sem_cat_pcd_untex-try/{cat}_dino_feature.pt')
|
| 1116 |
+
|
| 1117 |
+
# fig = plt.figure(figsize=(10, 10))
|
| 1118 |
+
# ax = fig.add_subplot(111, projection="3d")
|
| 1119 |
+
# pca_color =vis_pca(average_aggregated_features.squeeze(0))
|
| 1120 |
+
# # sampled_points= sampled_points.squeeze(0).cpu().detach().numpy()
|
| 1121 |
+
# meanshape_points = meanshape_points.squeeze(0).cpu().detach().numpy()
|
| 1122 |
+
# ax.scatter(meanshape_points[:, 2], meanshape_points[:, 0], meanshape_points[:, 1], c=pca_color,s=10.0, marker='o')
|
| 1123 |
+
# ax.set_xlabel("z")
|
| 1124 |
+
# ax.set_ylabel("x")
|
| 1125 |
+
# ax.set_zlabel("y")
|
| 1126 |
+
# ax.set_xlim(-2, 2)
|
| 1127 |
+
# ax.set_ylim(-2, 2)
|
| 1128 |
+
# ax.set_zlim(-2, 2)
|
| 1129 |
+
# plt.title("Shape Prior Dino")
|
| 1130 |
+
# plt.show()
|
| 1131 |
+
|
feature_alignment.py
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import open3d as o3d
|
| 3 |
+
import os
|
| 4 |
+
import copy
|
| 5 |
+
import trimesh
|
| 6 |
+
import torch
|
| 7 |
+
from sklearn.decomposition import PCA
|
| 8 |
+
|
| 9 |
+
def align_point_clouds(pcd1_path, pcd2_path, geometric_features1_path, geometric_features2_path,
|
| 10 |
+
semantic_features1_path, semantic_features2_path, distance_threshold=0.05, output_path="aligned_combined.ply"):
|
| 11 |
+
# # Load point clouds
|
| 12 |
+
# pcd1 = o3d.io.read_point_cloud(pcd1_path)
|
| 13 |
+
# pcd2 = o3d.io.read_point_cloud(pcd2_path)
|
| 14 |
+
|
| 15 |
+
# Load point clouds
|
| 16 |
+
pcd1 = torch.load(pcd1_path, map_location="cpu")
|
| 17 |
+
|
| 18 |
+
# Rotate pcd1 90 degrees along x axis
|
| 19 |
+
rotation_x = torch.tensor([
|
| 20 |
+
[1, 0, 0],
|
| 21 |
+
[0, 0, -1],
|
| 22 |
+
[0, 1, 0]
|
| 23 |
+
], dtype=pcd1.dtype)
|
| 24 |
+
|
| 25 |
+
rotation_z = torch.tensor([
|
| 26 |
+
[0, -1, 0],
|
| 27 |
+
[1, 0, 0],
|
| 28 |
+
[0, 0, 1]
|
| 29 |
+
], dtype=pcd1.dtype)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
pcd1 = torch.matmul(pcd1, rotation_x.T)
|
| 33 |
+
pcd1 = torch.matmul(pcd1, rotation_z.T)
|
| 34 |
+
pcd2 = torch.load(pcd2_path, map_location="cpu")
|
| 35 |
+
|
| 36 |
+
# Convert to Open3D point clouds
|
| 37 |
+
# pcd is a torch.Tensor
|
| 38 |
+
pcd_np1 = pcd1.detach().cpu().numpy().astype(np.float64)
|
| 39 |
+
pcd1 = o3d.geometry.PointCloud()
|
| 40 |
+
pcd1.points = o3d.utility.Vector3dVector(pcd_np1.reshape(-1, 3))
|
| 41 |
+
pcd_np2 = pcd2.detach().cpu().numpy().astype(np.float64)
|
| 42 |
+
pcd2 = o3d.geometry.PointCloud()
|
| 43 |
+
pcd2.points = o3d.utility.Vector3dVector(pcd_np2.reshape(-1, 3))
|
| 44 |
+
|
| 45 |
+
# Load geometric features
|
| 46 |
+
geometric_features1 = np.load(geometric_features1_path)
|
| 47 |
+
geometric_features2 = np.load(geometric_features2_path)
|
| 48 |
+
|
| 49 |
+
# Load semantic features
|
| 50 |
+
semantic_features1 = torch.load(semantic_features1_path, map_location="cpu").numpy().reshape(1024, 384)
|
| 51 |
+
semantic_features2 = torch.load(semantic_features2_path, map_location="cpu").numpy().reshape(1024, 384)
|
| 52 |
+
|
| 53 |
+
# Concatenate geometric and semantic features
|
| 54 |
+
print(f"geometric_features1 shape: {geometric_features1.shape}")
|
| 55 |
+
print(f"semantic_features1 shape: {semantic_features1.shape}")
|
| 56 |
+
|
| 57 |
+
# combined_features1 = np.concatenate([geometric_features1, semantic_features1], axis=1)
|
| 58 |
+
# combined_features2 = np.concatenate([geometric_features2, semantic_features2], axis=1)
|
| 59 |
+
combined_features1 = semantic_features1
|
| 60 |
+
combined_features2 = semantic_features2
|
| 61 |
+
|
| 62 |
+
# save original combined
|
| 63 |
+
original_pcd = pcd1 + pcd2
|
| 64 |
+
os.makedirs(output_path, exist_ok=True)
|
| 65 |
+
o3d.io.write_point_cloud(f"{output_path}/original.ply", original_pcd)
|
| 66 |
+
|
| 67 |
+
# save a separated view so pcd1 and pcd2 are in the same file but easily distinguishable
|
| 68 |
+
bbox1 = np.asarray(pcd1.get_max_bound()) - np.asarray(pcd1.get_min_bound())
|
| 69 |
+
bbox2 = np.asarray(pcd2.get_max_bound()) - np.asarray(pcd2.get_min_bound())
|
| 70 |
+
max_extent = max(np.max(bbox1), np.max(bbox2), 1e-6)
|
| 71 |
+
offset = max_extent * 1.5
|
| 72 |
+
p1 = copy.deepcopy(pcd1)
|
| 73 |
+
p2 = copy.deepcopy(pcd2)
|
| 74 |
+
p1.translate([-offset / 2, 0, 0])
|
| 75 |
+
p2.translate([ offset / 2, 0, 0])
|
| 76 |
+
separated_pcd = p1 + p2
|
| 77 |
+
o3d.io.write_point_cloud(f"{output_path}/original_separate.ply", separated_pcd)
|
| 78 |
+
|
| 79 |
+
print(f"pcd1 points shape: {np.asarray(pcd1.points).shape}")
|
| 80 |
+
print(f"pcd2 points shape: {np.asarray(pcd2.points).shape}")
|
| 81 |
+
print(f"combined_features1 shape: {combined_features1.shape}")
|
| 82 |
+
print(f"combined_features2 shape: {combined_features2.shape}")
|
| 83 |
+
|
| 84 |
+
# Convert combined features to Open3D format
|
| 85 |
+
f1 = o3d.pipelines.registration.Feature()
|
| 86 |
+
f1.data = combined_features1.T
|
| 87 |
+
f2 = o3d.pipelines.registration.Feature()
|
| 88 |
+
f2.data = combined_features2.T
|
| 89 |
+
|
| 90 |
+
# RANSAC-based initial alignment
|
| 91 |
+
result_ransac = o3d.pipelines.registration.registration_ransac_based_on_feature_matching(
|
| 92 |
+
pcd1, pcd2, f1, f2, True, distance_threshold,
|
| 93 |
+
o3d.pipelines.registration.TransformationEstimationPointToPoint(False), 4,
|
| 94 |
+
[o3d.pipelines.registration.CorrespondenceCheckerBasedOnEdgeLength(0.9),
|
| 95 |
+
o3d.pipelines.registration.CorrespondenceCheckerBasedOnDistance(distance_threshold)],
|
| 96 |
+
o3d.pipelines.registration.RANSACConvergenceCriteria(4000000, 500)
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
# ICP refinement
|
| 100 |
+
result_icp = o3d.pipelines.registration.registration_icp(
|
| 101 |
+
pcd1, pcd2, distance_threshold, result_ransac.transformation,
|
| 102 |
+
o3d.pipelines.registration.TransformationEstimationPointToPoint()
|
| 103 |
+
)
|
| 104 |
+
# Transform and visualize
|
| 105 |
+
pcd1.transform(result_icp.transformation)
|
| 106 |
+
|
| 107 |
+
# Save aligned point clouds separated for easy comparison
|
| 108 |
+
bbox1 = np.asarray(pcd1.get_max_bound()) - np.asarray(pcd1.get_min_bound())
|
| 109 |
+
bbox2 = np.asarray(pcd2.get_max_bound()) - np.asarray(pcd2.get_min_bound())
|
| 110 |
+
max_extent = max(np.max(bbox1), np.max(bbox2), 1e-6)
|
| 111 |
+
offset = max_extent * 1.5
|
| 112 |
+
p1 = copy.deepcopy(pcd1)
|
| 113 |
+
p2 = copy.deepcopy(pcd2)
|
| 114 |
+
p1.translate([-offset / 2, 0, 0])
|
| 115 |
+
p2.translate([ offset / 2, 0, 0])
|
| 116 |
+
|
| 117 |
+
# Apply PCA to combined features separately for RGB coloring
|
| 118 |
+
pca1 = PCA(n_components=3)
|
| 119 |
+
pca_features1 = pca1.fit_transform(combined_features1)
|
| 120 |
+
|
| 121 |
+
pca2 = PCA(n_components=3)
|
| 122 |
+
pca_features2 = pca2.fit_transform(combined_features2)
|
| 123 |
+
|
| 124 |
+
# Normalize to [0, 1] range for RGB
|
| 125 |
+
pca_features1_normalized = (pca_features1 - pca_features1.min(axis=0)) / (pca_features1.max(axis=0) - pca_features1.min(axis=0) + 1e-6)
|
| 126 |
+
pca_features2_normalized = (pca_features2 - pca_features2.min(axis=0)) / (pca_features2.max(axis=0) - pca_features2.min(axis=0) + 1e-6)
|
| 127 |
+
|
| 128 |
+
p1.colors = o3d.utility.Vector3dVector(pca_features1_normalized)
|
| 129 |
+
p2.colors = o3d.utility.Vector3dVector(pca_features2_normalized)
|
| 130 |
+
|
| 131 |
+
transformed_separate = p1 + p2
|
| 132 |
+
o3d.io.write_point_cloud(f"{output_path}/transformed_separate.ply", transformed_separate)
|
| 133 |
+
|
| 134 |
+
return result_icp.transformation
|
| 135 |
+
|
| 136 |
+
# Example usage:
|
| 137 |
+
# align_point_clouds("path_to_pcd1.ply", "path_to_pcd2.ply", "path_to_features1.npy", "path_to_features2.npy", output_path="aligned_combined.ply")
|
| 138 |
+
transformation = align_point_clouds(
|
| 139 |
+
f"/mnt/4T/Yung/yung_large_files/semantic_feature/test_notebook/8v/saved_pcd_untex-try/cup/cup-grey_handle_pcd-texture_amodal.pt",
|
| 140 |
+
f"/mnt/4T/Yung/yung_large_files/semantic_feature/test_notebook/8v/saved_pcd_untex-try/cup/cup-grey_handle_pcd-texture.pt",
|
| 141 |
+
f"yung_large_files/pose_can_results/housecat6d_sonata_feature/scene01/000000/cup-grey_handle/input_features.npy",
|
| 142 |
+
f"yung_large_files/pose_can_results/housecat6d_sonata_feature/scene01/000000/cup-grey_handle/normalized_groundtruth_features.npy",
|
| 143 |
+
f"/mnt/4T/Yung/yung_large_files/semantic_feature/test_notebook/8v/saved_dino_pcd_untex-try/cup/cup-grey_handle_dino_feature-texture_amodal.pt",
|
| 144 |
+
f"/mnt/4T/Yung/yung_large_files/semantic_feature/test_notebook/8v/saved_dino_pcd_untex-try/cup/cup-grey_handle_dino_feature-texture.pt",
|
| 145 |
+
output_path=f"yung_large_files/pose_can_results/housecat6d_sonata_feature/scene01/000000/cup-grey_handle/semantic_feature-texture"
|
| 146 |
+
)
|
| 147 |
+
# meshfile_name = f"yung_large_files/pose_can_results/output_orientation_Matters/Amodal3r_HouseCat6D_test/scene01/000000/cup-grey_handle/mesh.glb"
|
| 148 |
+
# mesh = trimesh.load(meshfile_name, force='mesh')
|
| 149 |
+
# mesh.apply_transform(transformation)
|
| 150 |
+
# # Save the transformed mesh as GLB
|
| 151 |
+
# transformed_mesh_path = os.path.join(os.path.dirname(meshfile_name), "mesh_transformed_w_semanticand_geometric_feature.glb")
|
| 152 |
+
# # trimesh.export will include vertex colors if present
|
| 153 |
+
# mesh.export(transformed_mesh_path)
|
| 154 |
+
|
| 155 |
+
# # Visualization of features using PCA for color mapping
|
| 156 |
+
# import matplotlib.pyplot as plt
|
| 157 |
+
|
| 158 |
+
# # Load the feature file and point cloud
|
| 159 |
+
# features = torch.load("/mnt/4T/Yung/yung_large_files/semantic_feature/test_notebook/8v/saved_dino_pcd_untex-try/cup/cup-grey_handle_dinov3_feature-texture.pt", map_location="cpu")
|
| 160 |
+
# # pcd = o3d.io.read_point_cloud("/mnt/4T/Yung/yung_large_files/pose_can_results/output_orientation_Matters/Amodal3r_HouseCat6D_test/scene01/000000/cup-grey_handle/mesh_downsampled.ply")
|
| 161 |
+
# pcd = torch.load("/mnt/4T/Yung/yung_large_files/semantic_feature/test_notebook/8v/saved_pcd_untex-try/cup/cup-grey_handle_pcd-texture.pt", map_location="cpu")
|
| 162 |
+
|
| 163 |
+
# # pcd is a torch.Tensor
|
| 164 |
+
# pcd_np = pcd.detach().cpu().numpy().astype(np.float64)
|
| 165 |
+
# # pcd_np = np.asarray(pcd.points).astype(np.float64)
|
| 166 |
+
|
| 167 |
+
# # Ensure shape is (N,3)
|
| 168 |
+
# pcd_np = pcd_np.reshape(-1, 3)
|
| 169 |
+
|
| 170 |
+
# print(features.shape)
|
| 171 |
+
# # Convert features to numpy and reshape to 2D
|
| 172 |
+
# features_np = features.detach().cpu().numpy().squeeze(0)
|
| 173 |
+
# print(features_np.shape)
|
| 174 |
+
|
| 175 |
+
# # Apply PCA to reduce features to 3 components for RGB coloring
|
| 176 |
+
# pca = PCA(n_components=3)
|
| 177 |
+
# pca_features = pca.fit_transform(features_np)
|
| 178 |
+
|
| 179 |
+
# # Normalize to [0, 1] range for RGB
|
| 180 |
+
# pca_features_normalized = (pca_features - pca_features.min(axis=0)) / (pca_features.max(axis=0) - pca_features.min(axis=0) + 1e-6)
|
| 181 |
+
|
| 182 |
+
# # Create point cloud and apply PCA colors
|
| 183 |
+
# pcd_o3d = o3d.geometry.PointCloud()
|
| 184 |
+
# pcd_o3d.points = o3d.utility.Vector3dVector(pcd_np)
|
| 185 |
+
# pcd_o3d.colors = o3d.utility.Vector3dVector(pca_features_normalized)
|
| 186 |
+
# o3d.io.write_point_cloud("pcd_colored_new.ply", pcd_o3d)
|
| 187 |
+
|