File size: 8,935 Bytes
3eeb500 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 | import numpy as np
import open3d as o3d
import os
import copy
import trimesh
import torch
from sklearn.decomposition import PCA
def align_point_clouds(pcd1_path, pcd2_path, geometric_features1_path, geometric_features2_path,
semantic_features1_path, semantic_features2_path, distance_threshold=0.05, output_path="aligned_combined.ply"):
# # Load point clouds
# pcd1 = o3d.io.read_point_cloud(pcd1_path)
# pcd2 = o3d.io.read_point_cloud(pcd2_path)
# Load point clouds
pcd1 = torch.load(pcd1_path, map_location="cpu")
# Rotate pcd1 90 degrees along x axis
rotation_x = torch.tensor([
[1, 0, 0],
[0, 0, -1],
[0, 1, 0]
], dtype=pcd1.dtype)
rotation_z = torch.tensor([
[0, -1, 0],
[1, 0, 0],
[0, 0, 1]
], dtype=pcd1.dtype)
pcd1 = torch.matmul(pcd1, rotation_x.T)
pcd1 = torch.matmul(pcd1, rotation_z.T)
pcd2 = torch.load(pcd2_path, map_location="cpu")
# Convert to Open3D point clouds
# pcd is a torch.Tensor
pcd_np1 = pcd1.detach().cpu().numpy().astype(np.float64)
pcd1 = o3d.geometry.PointCloud()
pcd1.points = o3d.utility.Vector3dVector(pcd_np1.reshape(-1, 3))
pcd_np2 = pcd2.detach().cpu().numpy().astype(np.float64)
pcd2 = o3d.geometry.PointCloud()
pcd2.points = o3d.utility.Vector3dVector(pcd_np2.reshape(-1, 3))
# Load geometric features
geometric_features1 = np.load(geometric_features1_path)
geometric_features2 = np.load(geometric_features2_path)
# Load semantic features
semantic_features1 = torch.load(semantic_features1_path, map_location="cpu").numpy().reshape(1024, 384)
semantic_features2 = torch.load(semantic_features2_path, map_location="cpu").numpy().reshape(1024, 384)
# Concatenate geometric and semantic features
print(f"geometric_features1 shape: {geometric_features1.shape}")
print(f"semantic_features1 shape: {semantic_features1.shape}")
# combined_features1 = np.concatenate([geometric_features1, semantic_features1], axis=1)
# combined_features2 = np.concatenate([geometric_features2, semantic_features2], axis=1)
combined_features1 = semantic_features1
combined_features2 = semantic_features2
# save original combined
original_pcd = pcd1 + pcd2
os.makedirs(output_path, exist_ok=True)
o3d.io.write_point_cloud(f"{output_path}/original.ply", original_pcd)
# save a separated view so pcd1 and pcd2 are in the same file but easily distinguishable
bbox1 = np.asarray(pcd1.get_max_bound()) - np.asarray(pcd1.get_min_bound())
bbox2 = np.asarray(pcd2.get_max_bound()) - np.asarray(pcd2.get_min_bound())
max_extent = max(np.max(bbox1), np.max(bbox2), 1e-6)
offset = max_extent * 1.5
p1 = copy.deepcopy(pcd1)
p2 = copy.deepcopy(pcd2)
p1.translate([-offset / 2, 0, 0])
p2.translate([ offset / 2, 0, 0])
separated_pcd = p1 + p2
o3d.io.write_point_cloud(f"{output_path}/original_separate.ply", separated_pcd)
print(f"pcd1 points shape: {np.asarray(pcd1.points).shape}")
print(f"pcd2 points shape: {np.asarray(pcd2.points).shape}")
print(f"combined_features1 shape: {combined_features1.shape}")
print(f"combined_features2 shape: {combined_features2.shape}")
# Convert combined features to Open3D format
f1 = o3d.pipelines.registration.Feature()
f1.data = combined_features1.T
f2 = o3d.pipelines.registration.Feature()
f2.data = combined_features2.T
# RANSAC-based initial alignment
result_ransac = o3d.pipelines.registration.registration_ransac_based_on_feature_matching(
pcd1, pcd2, f1, f2, True, distance_threshold,
o3d.pipelines.registration.TransformationEstimationPointToPoint(False), 4,
[o3d.pipelines.registration.CorrespondenceCheckerBasedOnEdgeLength(0.9),
o3d.pipelines.registration.CorrespondenceCheckerBasedOnDistance(distance_threshold)],
o3d.pipelines.registration.RANSACConvergenceCriteria(4000000, 500)
)
# ICP refinement
result_icp = o3d.pipelines.registration.registration_icp(
pcd1, pcd2, distance_threshold, result_ransac.transformation,
o3d.pipelines.registration.TransformationEstimationPointToPoint()
)
# Transform and visualize
pcd1.transform(result_icp.transformation)
# Save aligned point clouds separated for easy comparison
bbox1 = np.asarray(pcd1.get_max_bound()) - np.asarray(pcd1.get_min_bound())
bbox2 = np.asarray(pcd2.get_max_bound()) - np.asarray(pcd2.get_min_bound())
max_extent = max(np.max(bbox1), np.max(bbox2), 1e-6)
offset = max_extent * 1.5
p1 = copy.deepcopy(pcd1)
p2 = copy.deepcopy(pcd2)
p1.translate([-offset / 2, 0, 0])
p2.translate([ offset / 2, 0, 0])
# Apply PCA to combined features separately for RGB coloring
pca1 = PCA(n_components=3)
pca_features1 = pca1.fit_transform(combined_features1)
pca2 = PCA(n_components=3)
pca_features2 = pca2.fit_transform(combined_features2)
# Normalize to [0, 1] range for RGB
pca_features1_normalized = (pca_features1 - pca_features1.min(axis=0)) / (pca_features1.max(axis=0) - pca_features1.min(axis=0) + 1e-6)
pca_features2_normalized = (pca_features2 - pca_features2.min(axis=0)) / (pca_features2.max(axis=0) - pca_features2.min(axis=0) + 1e-6)
p1.colors = o3d.utility.Vector3dVector(pca_features1_normalized)
p2.colors = o3d.utility.Vector3dVector(pca_features2_normalized)
transformed_separate = p1 + p2
o3d.io.write_point_cloud(f"{output_path}/transformed_separate.ply", transformed_separate)
return result_icp.transformation
# Example usage:
# align_point_clouds("path_to_pcd1.ply", "path_to_pcd2.ply", "path_to_features1.npy", "path_to_features2.npy", output_path="aligned_combined.ply")
transformation = align_point_clouds(
f"/mnt/4T/Yung/yung_large_files/semantic_feature/test_notebook/8v/saved_pcd_untex-try/cup/cup-grey_handle_pcd-texture_amodal.pt",
f"/mnt/4T/Yung/yung_large_files/semantic_feature/test_notebook/8v/saved_pcd_untex-try/cup/cup-grey_handle_pcd-texture.pt",
f"yung_large_files/pose_can_results/housecat6d_sonata_feature/scene01/000000/cup-grey_handle/input_features.npy",
f"yung_large_files/pose_can_results/housecat6d_sonata_feature/scene01/000000/cup-grey_handle/normalized_groundtruth_features.npy",
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",
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",
output_path=f"yung_large_files/pose_can_results/housecat6d_sonata_feature/scene01/000000/cup-grey_handle/semantic_feature-texture"
)
# meshfile_name = f"yung_large_files/pose_can_results/output_orientation_Matters/Amodal3r_HouseCat6D_test/scene01/000000/cup-grey_handle/mesh.glb"
# mesh = trimesh.load(meshfile_name, force='mesh')
# mesh.apply_transform(transformation)
# # Save the transformed mesh as GLB
# transformed_mesh_path = os.path.join(os.path.dirname(meshfile_name), "mesh_transformed_w_semanticand_geometric_feature.glb")
# # trimesh.export will include vertex colors if present
# mesh.export(transformed_mesh_path)
# # Visualization of features using PCA for color mapping
# import matplotlib.pyplot as plt
# # Load the feature file and point cloud
# 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")
# # 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")
# 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")
# # pcd is a torch.Tensor
# pcd_np = pcd.detach().cpu().numpy().astype(np.float64)
# # pcd_np = np.asarray(pcd.points).astype(np.float64)
# # Ensure shape is (N,3)
# pcd_np = pcd_np.reshape(-1, 3)
# print(features.shape)
# # Convert features to numpy and reshape to 2D
# features_np = features.detach().cpu().numpy().squeeze(0)
# print(features_np.shape)
# # Apply PCA to reduce features to 3 components for RGB coloring
# pca = PCA(n_components=3)
# pca_features = pca.fit_transform(features_np)
# # Normalize to [0, 1] range for RGB
# pca_features_normalized = (pca_features - pca_features.min(axis=0)) / (pca_features.max(axis=0) - pca_features.min(axis=0) + 1e-6)
# # Create point cloud and apply PCA colors
# pcd_o3d = o3d.geometry.PointCloud()
# pcd_o3d.points = o3d.utility.Vector3dVector(pcd_np)
# pcd_o3d.colors = o3d.utility.Vector3dVector(pca_features_normalized)
# o3d.io.write_point_cloud("pcd_colored_new.ply", pcd_o3d)
|