import torch
import torch.nn as nn
import numpy as np
import os
import sys
import open3d as o3d
import argparse
import logging
from datetime import datetime
# Assuming the original PointNet model is in the 'models' directory
# You might need to adjust this path based on your project structure
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'models'))
from pointnet_sem_seg import PointNetDenseCls # Adjust the import based on your model's implementation
NUM_CLASSES = 13
BATCH_SIZE = 32
NUM_POINT = 2048 # Changed to 2048 to match original PointNet implementation
# Define color map
COLOR_MAP = {
'ceiling': [0, 255, 0],
'floor': [0, 0, 255],
'wall': [0, 255, 255],
'beam': [255, 255, 0],
'column': [255, 0, 255],
'window': [100, 100, 255],
'door': [200, 200, 100],
'table': [170, 120, 200],
'chair': [255, 0, 0],
'sofa': [200, 100, 100],
'bookcase': [10, 200, 100],
'board': [200, 200, 200],
'clutter': [50, 50, 50]
}
LABEL_TO_NAMES = {i: name for i, name in enumerate(COLOR_MAP.keys())}
def parse_args():
parser = argparse.ArgumentParser(description='Point Cloud Segmentation Inference')
parser.add_argument('--input_file', type=str, required=True, help='Path to the input point cloud file (TXT format)')
parser.add_argument('--output_folder', type=str, required=True, help='Path to the output folder')
parser.add_argument('--num_point', type=int, default=NUM_POINT, help='Number of points per sample')
parser.add_argument('--model_path', type=str, required=True, help='Path to the trained model checkpoint')
parser.add_argument('--use_full_cloud', action='store_true', help='Use full point cloud for segmentation')
parser.add_argument('--use_normals', action='store_true', help='Use normals as additional features')
parser.add_argument('--use_rgb', action='store_true', help='Use RGB colors as additional features')
parser.add_argument('--gpu', type=int, default=0, help='GPU index to use (default: 0)')
return parser.parse_args()
def setup_logger(log_file):
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
# File handler
file_handler = logging.FileHandler(log_file)
file_handler.setLevel(logging.INFO)
# Console handler
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
# Formatter
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
file_handler.setFormatter(formatter)
console_handler.setFormatter(formatter)
# Add handlers
logger.addHandler(file_handler)
logger.addHandler(console_handler)
return logger
def read_point_cloud(file_path, use_rgb=False):
"""
Read XYZ and optionally RGB data from a text file.
"""
data = np.loadtxt(file_path, delimiter=' ')
xyz = data[:, :3]
if use_rgb:
if data.shape[1] < 6:
raise ValueError("Input file does not contain RGB data, but --use_rgb was specified.")
rgb = data[:, 3:6] / 255.0 # Normalize RGB to [0,1]
return xyz, rgb
return xyz, None
def sample_point_cloud(xyz, rgb=None, num_points=NUM_POINT):
"""
Randomly sample a subset of points from the point cloud.
"""
if len(xyz) <= num_points:
if rgb is not None:
return xyz, rgb
return xyz, None
indices = np.random.choice(len(xyz), num_points, replace=False)
if rgb is not None:
return xyz[indices], rgb[indices]
return xyz[indices], None
def process_point_cloud(xyz, normals=None, rgb=None):
"""
Process XYZ and optionally normals and RGB data.
Normalize the point cloud to have zero mean and unit variance.
"""
xyz_mean = np.mean(xyz, axis=0)
xyz_centered = xyz - xyz_mean
scale = np.max(np.linalg.norm(xyz_centered, axis=1))
xyz_normalized = xyz_centered / scale
if normals is not None:
normals = normals / np.linalg.norm(normals, axis=1, keepdims=True)
points = np.hstack((xyz_normalized, normals))
else:
points = xyz_normalized
if rgb is not None:
points = np.hstack((points, rgb))
return points
def segment_point_cloud(classifier, points, device, num_point=NUM_POINT):
"""
Perform segmentation on input points using the classifier.
"""
classifier.eval()
points = points.astype(np.float32)
points = torch.from_numpy(points).to(device)
points = points.unsqueeze(0) # [B, num_channels, N]
# If the number of points is less than num_point, pad with zeros
if points.shape[2] < num_point:
pad_size = num_point - points.shape[2]
padding = torch.zeros(points.shape[0], points.shape[1], pad_size).to(device)
points = torch.cat([points, padding], dim=2)
with torch.no_grad():
seg_pred, _ = classifier(points)
seg_pred = seg_pred.squeeze(0) # [num_classes, N]
seg_pred = seg_pred.max(0)[1].cpu().numpy() # [N]
return seg_pred
def save_as_txt(xyz, labels, output_file):
"""
Save the point cloud with segmentation labels as a TXT file.
"""
with open(output_file, 'w') as f:
for i in range(xyz.shape[0]):
xyz_coords = xyz[i]
label_name = LABEL_TO_NAMES.get(labels[i], 'unknown')
label_color = COLOR_MAP.get(label_name, [0, 0, 0])
f.write(f"{xyz_coords[0]:.6f} {xyz_coords[1]:.6f} {xyz_coords[2]:.6f} {label_color[0]} {label_color[1]} {label_color[2]}\n")
def main(args):
# Set up logging
os.makedirs(args.output_folder, exist_ok=True)
log_file = os.path.join(args.output_folder, f"segmentation_log_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt")
logger = setup_logger(log_file)
# Log arguments
logger.info("Script arguments:")
for arg, value in vars(args).items():
logger.info(f"{arg}: {value}")
# Device configuration
device = torch.device(f"cuda:{args.gpu}" if torch.cuda.is_available() else "cpu")
logger.info(f"Using device: {device}")
# Load your model
logger.info("Loading model")
try:
classifier = PointNetDenseCls(k=NUM_CLASSES)
classifier.to(device)
except Exception as e:
logger.error(f"Failed to initialize the model: {str(e)}")
return
try:
state_dict = torch.load(args.model_path, map_location=device)
if 'model_state_dict' in state_dict:
state_dict = state_dict['model_state_dict']
classifier.load_state_dict(state_dict)
classifier.eval()
logger.info("Model loaded successfully")
except Exception as e:
logger.error(f"Failed to load model weights: {str(e)}")
return
# Read point cloud data
logger.info(f"Reading point cloud from {args.input_file}")
try:
xyz, rgb = read_point_cloud(args.input_file, use_rgb=args.use_rgb)
except Exception as e:
logger.error(f"Failed to read point cloud: {str(e)}")
return
if args.use_rgb and rgb is None:
logger.error("RGB data was not found in the input file, but --use_rgb was specified.")
return
# If normals are used, estimate them
if args.use_normals:
logger.info("Estimating normals")
pcd = o3d.geometry.PointCloud()
pcd.points = o3d.utility.Vector3dVector(xyz)
pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamKNN(knn=30))
normals = np.asarray(pcd.normals)
else:
normals = None
# Optionally use full cloud or sample
if args.use_full_cloud:
xyz_sampled = xyz
rgb_sampled = rgb if args.use_rgb else None
normals_sampled = normals if args.use_normals else None
else:
xyz_sampled, rgb_sampled = sample_point_cloud(xyz, rgb, num_points=args.num_point) if args.use_rgb else sample_point_cloud(xyz, None, num_points=args.num_point)
normals_sampled = normals # Sampling normals if used
if args.use_normals and normals_sampled is not None:
normals_sampled = normals_sampled[:args.num_point] # Adjust if sampled differently
# Process point cloud
logger.info("Processing point cloud")
processed_points = process_point_cloud(xyz_sampled, normals=normals_sampled, rgb=rgb_sampled)
# Ensure the number of points matches
if processed_points.shape[0] != args.num_point and not args.use_full_cloud:
logger.warning(f"Sampled points ({processed_points.shape[0]}) do not match num_point ({args.num_point})")
# Perform segmentation
logger.info("Starting segmentation")
try:
pred_labels = segment_point_cloud(classifier, processed_points, device, num_point=args.num_point)
except Exception as e:
logger.error(f"Segmentation failed: {str(e)}")
return
# Save results as TXT file
output_file_txt = os.path.join(args.output_folder, os.path.splitext(os.path.basename(args.input_file))[0] + "_segmented.txt")
logger.info(f"Saving results to {output_file_txt}")
try:
save_as_txt(xyz_sampled, pred_labels, output_file_txt)
except Exception as e:
logger.error(f"Failed to save segmented point cloud: {str(e)}")
return
# Log predicted labels
label_counts = {}
for label in pred_labels:
label_name = LABEL_TO_NAMES.get(label, 'unknown')
label_counts[label_name] = label_counts.get(label_name, 0) + 1
logger.info("Predicted label counts:")
for label_name, count in label_counts.items():
logger.info(f"{label_name}: {count}")
logger.info(f"Segmented {len(pred_labels)} points. Results saved to {output_file_txt}")
if __name__ == '__main__':
args = parse_args()
main(args)