feature_match_code / feature_alignment.py
Jar-17's picture
Add files using upload-large-folder tool
3eeb500 verified
Raw History Blame Contribute Delete
8.94 kB
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)