Elffuss BraidHub

kikocis/SpatialLM public

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