| 1 | import os |
| 2 | import argparse |
| 3 | import math |
| 4 | import csv |
| 5 | import itertools |
| 6 | import logging |
| 7 | from typing import Dict, List |
| 8 | from collections import defaultdict |
| 9 | from dataclasses import dataclass |
| 10 | |
| 11 | import torch |
| 12 | import pandas as pd |
| 13 | import numpy as np |
| 14 | from scipy.optimize import linear_sum_assignment |
| 15 | from shapely import Polygon, LineString, polygonize, polygonize_full, make_valid |
| 16 | from bbox import BBox3D |
| 17 | from bbox.metrics import iou_3d |
| 18 | from terminaltables import AsciiTable |
| 19 | |
| 20 | from spatiallm import Layout |
| 21 | from spatiallm.layout.entity import Wall, Door, Window, Bbox |
| 22 | |
| 23 | log = logging.getLogger(__name__) |
| 24 | |
| 25 | ZERO_TOLERANCE = 1e-6 |
| 26 | LARGE_COST_VALUE = 1e6 |
| 27 | OBJECTS = [ |
| 28 | "curtain", |
| 29 | "nightstand", |
| 30 | "chandelier", |
| 31 | "wardrobe", |
| 32 | "bed", |
| 33 | "sofa", |
| 34 | "chair", |
| 35 | "cabinet", |
| 36 | "dining table", |
| 37 | "plants", |
| 38 | "tv cabinet", |
| 39 | "coffee table", |
| 40 | "side table", |
| 41 | "air conditioner", |
| 42 | "dresser", |
| 43 | ] |
| 44 | THIN_OBJECTS = [ |
| 45 | "painting", |
| 46 | "carpet", |
| 47 | "tv", |
| 48 | "door", |
| 49 | "window", |
| 50 | ] |
| 51 | |
| 52 | |
| 53 | @dataclass |
| 54 | class EvalTuple: |
| 55 | tp: int |
| 56 | num_pred: int |
| 57 | num_gt: int |
| 58 | |
| 59 | @property |
| 60 | def precision(self): |
| 61 | return self.tp / self.num_pred if self.num_pred > 0 else 0 |
| 62 | |
| 63 | @property |
| 64 | def recall(self): |
| 65 | return self.tp / self.num_gt if self.num_gt > 0 else 0 |
| 66 | |
| 67 | @property |
| 68 | def f1(self): |
| 69 | return ( |
| 70 | (2 * self.precision * self.recall) / (self.precision + self.recall) |
| 71 | if (self.precision + self.recall) > 0 |
| 72 | else 0 |
| 73 | ) |
| 74 | |
| 75 | @property |
| 76 | def masked(self): |
| 77 | return self.num_pred == 0 and self.num_gt == 0 |
| 78 | |
| 79 | |
| 80 | def calc_poly_iou(poly1, poly2): |
| 81 | if poly1.intersects(poly2): |
| 82 | inter_area = poly1.intersection(poly2).area |
| 83 | union_area = poly1.union(poly2).area |
| 84 | poly_iou = inter_area / union_area if union_area > 0 else 0 |
| 85 | else: |
| 86 | poly_iou = 0 |
| 87 | return poly_iou |
| 88 | |
| 89 | |
| 90 | def construct_polygon(lines: List[LineString]): |
| 91 | try: |
| 92 | poly = polygonize(lines) |
| 93 | if poly.is_empty: |
| 94 | candidates = [] |
| 95 | for p in polygonize_full(lines): |
| 96 | if p.is_empty: |
| 97 | continue |
| 98 | |
| 99 | candidate = p.geoms[0] |
| 100 | if isinstance(candidate, Polygon): |
| 101 | candidates.append(candidate) |
| 102 | elif isinstance(candidate, LineString): |
| 103 | candidates.append(Polygon(candidate)) |
| 104 | else: |
| 105 | log.warning( |
| 106 | f"Unsupported geom_type {candidate.geom_type} to construct polygon." |
| 107 | ) |
| 108 | |
| 109 | candidates.sort(key=lambda x: x.area, reverse=True) |
| 110 | poly = candidates[0] |
| 111 | if not poly.is_valid: |
| 112 | poly = make_valid(poly) |
| 113 | return poly |
| 114 | except Exception as e: |
| 115 | log.error(f"Fail to construct polygon by lines {lines}", e) |
| 116 | return Polygon() |
| 117 | |
| 118 | |
| 119 | def read_label_mapping( |
| 120 | label_path: str, label_from="spatiallm59", label_to="spatiallm18" |
| 121 | ): |
| 122 | assert os.path.isfile(label_path), f"Label mapping file {label_path} does not exist" |
| 123 | mapping = dict() |
| 124 | with open(label_path) as csvfile: |
| 125 | reader = csv.DictReader(csvfile, delimiter="\t") |
| 126 | for row in reader: |
| 127 | label_from_value = row[label_from] |
| 128 | label_to_value = row[label_to] |
| 129 | if label_from_value == "" or label_to_value == "": |
| 130 | continue |
| 131 | mapping[label_from_value] = label_to_value |
| 132 | return mapping |
| 133 | |
| 134 | |
| 135 | def assign_class_map(entities: List[Bbox], class_map=Dict[str, str]): |
| 136 | res_entities = list() |
| 137 | for entity in entities: |
| 138 | mapping_to_class = class_map.get(entity.class_name.replace("_", " ")) |
| 139 | if mapping_to_class: |
| 140 | entity.class_name = mapping_to_class |
| 141 | res_entities.append(entity) |
| 142 | return res_entities |
| 143 | |
| 144 | |
| 145 | def get_entity_class(entity): |
| 146 | try: |
| 147 | return entity.class_name |
| 148 | except: |
| 149 | return entity.entity_label |
| 150 | |
| 151 | |
| 152 | def get_BBox3D(entity: Bbox): |
| 153 | return BBox3D( |
| 154 | entity.position_x, |
| 155 | entity.position_y, |
| 156 | entity.position_z, |
| 157 | entity.scale_x, |
| 158 | entity.scale_y, |
| 159 | entity.scale_z, |
| 160 | euler_angles=[0, 0, entity.angle_z], |
| 161 | is_center=True, |
| 162 | ) |
| 163 | |
| 164 | |
| 165 | def calc_bbox_tp( |
| 166 | pred_entities: List[Bbox], gt_entities: List[Bbox], iou_threshold: float = 0.25 |
| 167 | ): |
| 168 | num_pred = len(pred_entities) |
| 169 | num_gt = len(gt_entities) |
| 170 | if num_pred == 0 or num_gt == 0: |
| 171 | return EvalTuple(0, num_pred, num_gt) |
| 172 | |
| 173 | iou_matrix = torch.as_tensor( |
| 174 | [ |
| 175 | iou_3d(bbox_1, bbox_2) |
| 176 | for bbox_1, bbox_2 in itertools.product( |
| 177 | [get_BBox3D(entity) for entity in pred_entities], |
| 178 | [get_BBox3D(entity) for entity in gt_entities], |
| 179 | ) |
| 180 | ] |
| 181 | ).resize(num_pred, num_gt) |
| 182 | |
| 183 | cost_matrix = torch.full((num_pred, num_gt), LARGE_COST_VALUE) |
| 184 | cost_matrix[iou_matrix > iou_threshold] = -1 |
| 185 | |
| 186 | indices = linear_sum_assignment(cost_matrix.numpy()) |
| 187 | |
| 188 | tp_percent = iou_matrix[ |
| 189 | torch.as_tensor(indices[0], dtype=torch.int64), |
| 190 | torch.as_tensor(indices[1], dtype=torch.int64), |
| 191 | ] |
| 192 | tp = torch.sum(tp_percent >= iou_threshold).item() |
| 193 | |
| 194 | return EvalTuple(tp, num_pred, num_gt) |
| 195 | |
| 196 | |
| 197 | def is_valid_dw(entity: Door | Window, wall_id_lookup: Dict[int, Wall]): |
| 198 | attach_wall = wall_id_lookup.get(entity.id, None) |
| 199 | if attach_wall is None: |
| 200 | return False |
| 201 | |
| 202 | wall_extent_x = max( |
| 203 | max(attach_wall.ax, attach_wall.bx) - min(attach_wall.ax, attach_wall.bx), 0 |
| 204 | ) |
| 205 | wall_extent_y = max( |
| 206 | max(attach_wall.ay, attach_wall.by) - min(attach_wall.ay, attach_wall.by), 0 |
| 207 | ) |
| 208 | return wall_extent_x > ZERO_TOLERANCE or wall_extent_y > ZERO_TOLERANCE |
| 209 | |
| 210 | |
| 211 | def get_corners(entity: Door | Window | Bbox, wall_id_lookup: Dict[int, Wall]): |
| 212 | if isinstance(entity, (Door, Window)): |
| 213 | attach_wall = wall_id_lookup.get(entity.id, None) |
| 214 | if attach_wall is None: |
| 215 | log.error(f"{entity} attach wall is None") |
| 216 | return |
| 217 | |
| 218 | wall_start = np.array([attach_wall.ax, attach_wall.ay]) |
| 219 | wall_end = np.array([attach_wall.bx, attach_wall.by]) |
| 220 | wall_length = np.linalg.norm(wall_end - wall_start) |
| 221 | wall_xy_unit_vec = (wall_end - wall_start) / wall_length |
| 222 | wall_xy_unit_vec = np.nan_to_num(wall_xy_unit_vec, nan=0) |
| 223 | |
| 224 | door_center = np.array( |
| 225 | [entity.position_x, entity.position_y, entity.position_z] |
| 226 | ) |
| 227 | offset = 0.5 * np.concatenate( |
| 228 | [wall_xy_unit_vec * entity.width, np.array([entity.height])] |
| 229 | ) |
| 230 | door_start_xyz = door_center - offset |
| 231 | door_end_xyz = door_center + offset |
| 232 | |
| 233 | return np.array( |
| 234 | [ |
| 235 | [door_start_xyz[0], door_start_xyz[1], door_start_xyz[2]], |
| 236 | [door_end_xyz[0], door_end_xyz[1], door_start_xyz[2]], |
| 237 | [door_end_xyz[0], door_end_xyz[1], door_end_xyz[2]], |
| 238 | [door_start_xyz[0], door_start_xyz[1], door_end_xyz[2]], |
| 239 | ] |
| 240 | ) |
| 241 | elif isinstance(entity, Bbox): |
| 242 | bbox_points = get_BBox3D(entity).p |
| 243 | scale_key = ["scale_x", "scale_y", "scale_z"] |
| 244 | match min(scale_key, key=lambda k: abs(getattr(entity, k))): |
| 245 | case "scale_x": |
| 246 | return np.array( |
| 247 | [ |
| 248 | (bbox_points[0] + bbox_points[1]) / 2, |
| 249 | (bbox_points[2] + bbox_points[3]) / 2, |
| 250 | (bbox_points[6] + bbox_points[7]) / 2, |
| 251 | (bbox_points[4] + bbox_points[5]) / 2, |
| 252 | ] |
| 253 | ) |
| 254 | case "scale_y": |
| 255 | return np.array( |
| 256 | [ |
| 257 | (bbox_points[0] + bbox_points[3]) / 2, |
| 258 | (bbox_points[4] + bbox_points[7]) / 2, |
| 259 | (bbox_points[5] + bbox_points[6]) / 2, |
| 260 | (bbox_points[1] + bbox_points[2]) / 2, |
| 261 | ] |
| 262 | ) |
| 263 | case "scale_z": |
| 264 | return np.array( |
| 265 | [ |
| 266 | (bbox_points[0] + bbox_points[4]) / 2, |
| 267 | (bbox_points[1] + bbox_points[5]) / 2, |
| 268 | (bbox_points[2] + bbox_points[6]) / 2, |
| 269 | (bbox_points[3] + bbox_points[7]) / 2, |
| 270 | ] |
| 271 | ) |
| 272 | case _: |
| 273 | log.error(f"Unrecognized named attribute for {entity} in get_corners") |
| 274 | return |
| 275 | |
| 276 | |
| 277 | def are_planes_parallel_and_close( |
| 278 | corners_1: np.ndarray, |
| 279 | corners_2: np.ndarray, |
| 280 | parallel_tolerance: float, |
| 281 | dist_tolerance: float, |
| 282 | ): |
| 283 | p1, p2, p3, _ = corners_1 |
| 284 | q1, q2, q3, _ = corners_2 |
| 285 | n1 = np.cross(np.subtract(p2, p1), np.subtract(p3, p1)) |
| 286 | n2 = np.cross(np.subtract(q2, q1), np.subtract(q3, q1)) |
| 287 | n1_length = np.linalg.norm(n1) |
| 288 | n2_length = np.linalg.norm(n2) |
| 289 | assert ( |
| 290 | n1_length * n2_length > ZERO_TOLERANCE |
| 291 | ), f"Invalid plane corners, corners_1: {corners_1}, corners_2: {corners_2}" |
| 292 | |
| 293 | return ( |
| 294 | np.linalg.norm(np.cross(n1, n2)) / (n1_length * n2_length) < parallel_tolerance |
| 295 | and np.dot(np.subtract(q1, p1), n1) / n1_length < dist_tolerance |
| 296 | ) |
| 297 | |
| 298 | |
| 299 | def calc_thin_bbox_iou_2d( |
| 300 | corners_1: np.ndarray, |
| 301 | corners_2: np.ndarray, |
| 302 | parallel_tolerance: float, |
| 303 | dist_tolerance: float, |
| 304 | ): |
| 305 | if are_planes_parallel_and_close( |
| 306 | corners_1, corners_2, parallel_tolerance, dist_tolerance |
| 307 | ): |
| 308 | p1, p2, _, p4 = corners_1 |
| 309 | v1 = np.subtract(p2, p1) |
| 310 | v2 = np.subtract(p4, p1) |
| 311 | basis1 = v1 / np.linalg.norm(v1) |
| 312 | basis1_orth = v2 - np.dot(v2, basis1) * basis1 |
| 313 | basis2 = basis1_orth / np.linalg.norm(basis1_orth) |
| 314 | |
| 315 | projected_corners_1 = [ |
| 316 | [ |
| 317 | np.dot(np.subtract(point, p1), basis1), |
| 318 | np.dot(np.subtract(point, p1), basis2), |
| 319 | ] |
| 320 | for point in corners_1 |
| 321 | ] |
| 322 | projected_corners_2 = [ |
| 323 | [ |
| 324 | np.dot(np.subtract(point, p1), basis1), |
| 325 | np.dot(np.subtract(point, p1), basis2), |
| 326 | ] |
| 327 | for point in corners_2 |
| 328 | ] |
| 329 | box1 = Polygon(projected_corners_1) |
| 330 | box2 = Polygon(projected_corners_2) |
| 331 | |
| 332 | return calc_poly_iou(box1, box2) |
| 333 | else: |
| 334 | return 0 |
| 335 | |
| 336 | |
| 337 | def calc_thin_bbox_tp( |
| 338 | pred_entities: List[Door | Window | Bbox], |
| 339 | gt_entities: List[Door | Window | Bbox], |
| 340 | pred_wall_id_lookup: Dict[int, Wall], |
| 341 | gt_wall_id_lookup: Dict[int, Wall], |
| 342 | iou_threshold: float = 0.25, |
| 343 | parallel_tolerance: float = math.sin(math.radians(5)), |
| 344 | dist_tolerance: float = 0.2, |
| 345 | ): |
| 346 | num_pred = len(pred_entities) |
| 347 | num_gt = len(gt_entities) |
| 348 | if num_pred == 0 or num_gt == 0: |
| 349 | return EvalTuple(0, num_pred, num_gt) |
| 350 | |
| 351 | iou_matrix = torch.as_tensor( |
| 352 | [ |
| 353 | calc_thin_bbox_iou_2d( |
| 354 | corners_1, corners_2, parallel_tolerance, dist_tolerance |
| 355 | ) |
| 356 | for corners_1, corners_2 in itertools.product( |
| 357 | [get_corners(entity, pred_wall_id_lookup) for entity in pred_entities], |
| 358 | [get_corners(entity, gt_wall_id_lookup) for entity in gt_entities], |
| 359 | ) |
| 360 | ] |
| 361 | ).resize(num_pred, num_gt) |
| 362 | |
| 363 | cost_matrix = torch.full((num_pred, num_gt), LARGE_COST_VALUE) |
| 364 | cost_matrix[iou_matrix > iou_threshold] = -1 |
| 365 | |
| 366 | indices = linear_sum_assignment(cost_matrix.numpy()) |
| 367 | |
| 368 | tp_percent = iou_matrix[ |
| 369 | torch.as_tensor(indices[0], dtype=torch.int64), |
| 370 | torch.as_tensor(indices[1], dtype=torch.int64), |
| 371 | ] |
| 372 | tp = torch.sum(tp_percent >= iou_threshold).item() |
| 373 | |
| 374 | return EvalTuple(tp, num_pred, num_gt) |
| 375 | |
| 376 | |
| 377 | if __name__ == "__main__": |
| 378 | parser = argparse.ArgumentParser("SpatialLM evaluation script") |
| 379 | parser.add_argument( |
| 380 | "--metadata", |
| 381 | type=str, |
| 382 | required=True, |
| 383 | help="metadata CSV file with columns id, pcd, layout", |
| 384 | ) |
| 385 | parser.add_argument( |
| 386 | "--gt_dir", |
| 387 | type=str, |
| 388 | required=True, |
| 389 | help="Path to the gt layout txt directory", |
| 390 | ) |
| 391 | parser.add_argument( |
| 392 | "--pred_dir", |
| 393 | type=str, |
| 394 | required=True, |
| 395 | help="Path to the pred layout txt directory", |
| 396 | ) |
| 397 | parser.add_argument( |
| 398 | "--label_mapping", |
| 399 | type=str, |
| 400 | required=True, |
| 401 | help="Path to the label mapping file", |
| 402 | ) |
| 403 | args = parser.parse_args() |
| 404 | |
| 405 | df = pd.read_csv(args.metadata) |
| 406 | scene_id_list = df["id"].tolist() |
| 407 | class_map = read_label_mapping(args.label_mapping) |
| 408 | |
| 409 | floorplan_ious = list() |
| 410 | classwise_eval_tuples: Dict[str, List[EvalTuple]] = defaultdict(list) |
| 411 | for scene_id in scene_id_list: |
| 412 | log.info(f"Evaluating scene {scene_id}") |
| 413 | with open(os.path.join(args.pred_dir, f"{scene_id}.txt"), "r") as f: |
| 414 | pred_layout = Layout(f.read()) |
| 415 | with open(os.path.join(args.gt_dir, f"{scene_id}.txt"), "r") as f: |
| 416 | gt_layout = Layout(f.read()) |
| 417 | pred_layout.bboxes = assign_class_map(pred_layout.bboxes, class_map) |
| 418 | gt_layout.bboxes = assign_class_map(gt_layout.bboxes, class_map) |
| 419 | |
| 420 | # Floorplan, IoU |
| 421 | pred_poly = construct_polygon( |
| 422 | [LineString([(w.ax, w.ay), (w.bx, w.by)]) for w in pred_layout.walls] |
| 423 | ) |
| 424 | gt_poly = construct_polygon( |
| 425 | [LineString([(w.ax, w.ay), (w.bx, w.by)]) for w in gt_layout.walls] |
| 426 | ) |
| 427 | floorplan_ious.append(calc_poly_iou(pred_poly, gt_poly)) |
| 428 | |
| 429 | # Normal Objects, F1 |
| 430 | pred_normal_objects = [ |
| 431 | b for b in pred_layout.bboxes if b.class_name in OBJECTS |
| 432 | ] |
| 433 | gt_normal_objects = [ |
| 434 | b for b in gt_layout.bboxes if b.class_name in OBJECTS |
| 435 | ] |
| 436 | for class_name in OBJECTS: |
| 437 | classwise_eval_tuples[class_name].append( |
| 438 | calc_bbox_tp( |
| 439 | pred_entities=[ |
| 440 | b |
| 441 | for b in pred_normal_objects |
| 442 | if get_entity_class(b) == class_name |
| 443 | ], |
| 444 | gt_entities=[ |
| 445 | b |
| 446 | for b in gt_normal_objects |
| 447 | if get_entity_class(b) == class_name |
| 448 | ], |
| 449 | ) |
| 450 | ) |
| 451 | |
| 452 | # Thin Objects, F1 |
| 453 | pred_thin_objects = [ |
| 454 | b for b in pred_layout.bboxes if b.class_name in THIN_OBJECTS |
| 455 | ] |
| 456 | gt_thin_objects = [b for b in gt_layout.bboxes if b.class_name in THIN_OBJECTS] |
| 457 | pred_wall_id_lookup = {w.id: w for w in pred_layout.walls} |
| 458 | gt_wall_id_lookup = {w.id: w for w in gt_layout.walls} |
| 459 | pred_thin_objects += [ |
| 460 | e |
| 461 | for e in pred_layout.doors + pred_layout.windows |
| 462 | if is_valid_dw(e, pred_wall_id_lookup) |
| 463 | ] |
| 464 | gt_thin_objects += [ |
| 465 | e |
| 466 | for e in gt_layout.doors + gt_layout.windows |
| 467 | if is_valid_dw(e, gt_wall_id_lookup) |
| 468 | ] |
| 469 | |
| 470 | for class_name in THIN_OBJECTS: |
| 471 | classwise_eval_tuples[class_name].append( |
| 472 | calc_thin_bbox_tp( |
| 473 | pred_entities=[ |
| 474 | b |
| 475 | for b in pred_thin_objects |
| 476 | if get_entity_class(b) == class_name |
| 477 | ], |
| 478 | gt_entities=[ |
| 479 | b for b in gt_thin_objects if get_entity_class(b) == class_name |
| 480 | ], |
| 481 | pred_wall_id_lookup=pred_wall_id_lookup, |
| 482 | gt_wall_id_lookup=gt_wall_id_lookup, |
| 483 | ) |
| 484 | ) |
| 485 | |
| 486 | # table print |
| 487 | headers = ["Floorplan", "mean IoU"] |
| 488 | table_data = [headers] |
| 489 | table_data += [["wall", np.mean(floorplan_ious)]] |
| 490 | print("\n" + AsciiTable(table_data).table) |
| 491 | |
| 492 | headers = ["Objects", "F1 @.25 IoU"] |
| 493 | table_data = [headers] |
| 494 | for class_name in OBJECTS: |
| 495 | tuples = classwise_eval_tuples[class_name] |
| 496 | f1 = np.ma.masked_where( |
| 497 | [t.masked for t in tuples], [t.f1 for t in tuples] |
| 498 | ).mean() |
| 499 | table_data.append([class_name, f1]) |
| 500 | print("\n" + AsciiTable(table_data).table) |
| 501 | |
| 502 | headers = ["Thin Objects", "F1 @.25 IoU"] |
| 503 | table_data = [headers] |
| 504 | for class_name in THIN_OBJECTS: |
| 505 | tuples = classwise_eval_tuples[class_name] |
| 506 | f1 = np.ma.masked_where( |
| 507 | [t.masked for t in tuples], [t.f1 for t in tuples] |
| 508 | ).mean() |
| 509 | table_data.append([class_name, f1]) |
| 510 | print("\n" + AsciiTable(table_data).table) |