i-badas / scripts /plot_multiple_paper_graphs.py
JARAYAM
Accounting for symmetries in the dataset-wide computation
180b384
Raw History Blame Contribute Delete
109 kB
"""
I-BADAS Dataset Statistics and Visualization Script
====================================================
Generates a comprehensive suite of academic-quality figures describing the
I-BADAS (Intralogistics Bin Anomaly Detection And Segmentation) dataset.
All category names are discovered dynamically from every annotations.coco.json
found under the dataset root; the sample file is NOT treated as definitive.
Usage:
python ibadas_stats.py --root /path/to/test --out figures/
python ibadas_stats.py --root /path/to/test --train_root /path/to/train --out figures/
Dependencies:
pip install numpy matplotlib scipy pycocotools tqdm Pillow
"""
import argparse
import json
import os
import sys
from collections import defaultdict
from pathlib import Path
#matplotlib.use('Qt5Agg')
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
from mpl_toolkits.mplot3d import proj3d
from scipy.spatial import ConvexHull, QhullError
from matplotlib.patches import Patch
from scipy.spatial import ConvexHull
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
from matplotlib.lines import Line2D
from scipy.spatial.transform import Rotation
try:
from PIL import Image as PILImage
except ImportError:
PILImage = None
try:
from pycocotools import mask as coco_mask_utils
HAS_PYCOCOTOOLS = True
except ImportError:
HAS_PYCOCOTOOLS = False
# ---------------------------------------------------------------------------
# Style constants
# ---------------------------------------------------------------------------
VIRIDIS = plt.cm.viridis
VIRIDIS_R = plt.cm.viridis_r
CLASS_ORDER = ["empty_clean", "empty_dirty", "non_empty"]
FONT_TITLE = {"fontsize": 13, "fontweight": "bold", "color": "#1a1a2e"}
FONT_LABEL = {"fontsize": 11, "color": "#1a1a2e"}
FONT_TICK = {"fontsize": 9}
SPINE_COLOR = "#cccccc"
BG_AXES = "#f9f9f9"
def style_ax(ax, title="", xlabel="", ylabel=""):
ax.set_facecolor(BG_AXES)
for spine in ax.spines.values():
spine.set_edgecolor(SPINE_COLOR)
ax.tick_params(colors="#444444", labelsize=9)
ax.set_title(title, **FONT_TITLE, pad=10)
if xlabel:
ax.set_xlabel(xlabel, **FONT_LABEL)
if ylabel:
ax.set_ylabel(ylabel, **FONT_LABEL)
ax.grid(True, linestyle="--", linewidth=0.5, alpha=0.6, color="#cccccc")
ax.set_axisbelow(True)
def viridis_palette(n):
return [VIRIDIS(i / max(n - 1, 1)) for i in range(n)]
def save(fig, path, dpi=180):
fig.savefig(path, dpi=dpi, bbox_inches="tight",
facecolor=fig.get_facecolor())
plt.close(fig)
print(f" Saved: {path}")
# ---------------------------------------------------------------------------
# Data loading
# ---------------------------------------------------------------------------
def load_all_scenes(root: Path):
"""
Walk the dataset root and load every annotations.coco.json.
Returns a list of scene dicts:
{
'scene_id': str,
'coco': dict, # raw COCO JSON
'cat_map': {id: name},
'supercategory_map': {id: supercategory},
}
Also builds a global category registry across all files.
"""
scene_dirs = sorted(root.iterdir()) if root.is_dir() else []
scenes = []
global_cats = {} # name -> id (canonical, scene-independent)
for sd in scene_dirs:
ann_file = sd / "annotations.coco.json"
if not ann_file.exists():
continue
with open(ann_file) as f:
coco = json.load(f)
cat_map = {}
supercat_map = {}
for c in coco.get("categories", []):
cat_map[c["id"]] = c["name"]
supercat_map[c["id"]] = c.get("supercategory", "unknown")
global_cats[c["name"]] = c.get("supercategory", "unknown")
scenes.append({
"scene_id": sd.name,
"coco": coco,
"cat_map": cat_map,
"supercat_map": supercat_map,
"root": sd,
})
if not scenes:
sys.exit(f"[ERROR] No annotations.coco.json files found under {root}")
print(f"Loaded {len(scenes)} scenes.")
print(f"Global categories discovered: {sorted(global_cats.keys())}")
return scenes, global_cats
def aggregate(scenes):
"""
Build flat lists and dicts for all aggregated statistics.
"""
records = [] # one dict per image
ann_records = [] # one dict per annotation
for s in scenes:
coco = s["coco"]
cat_map = s["cat_map"]
supercat_map = s["supercat_map"]
img_map = {img["id"]: img for img in coco.get("images", [])}
ann_by_img = defaultdict(list)
for ann in coco.get("annotations", []):
ann_by_img[ann["image_id"]].append(ann)
for img in coco.get("images", []):
rec = {
"scene_id": s["scene_id"],
"image_id": img["id"],
"file_name": img["file_name"],
"classification": img.get("classification", "unknown"),
"box_type": img.get("box_type", "unknown"),
"camera": img.get("camera", "unknown"),
"robot": img.get("robot", False),
"split": "good" if img["file_name"].startswith("good/") else "anomaly",
"annotations": ann_by_img[img["id"]],
"n_annotations": len(ann_by_img[img["id"]]),
}
records.append(rec)
for ann in ann_by_img[img["id"]]:
cat_name = cat_map.get(ann["category_id"], "unknown")
ann_records.append({
"scene_id": s["scene_id"],
"image_id": img["id"],
"classification": rec["classification"],
"cat_name": cat_name,
"supercat": supercat_map.get(ann["category_id"], "unknown"),
"area": ann.get("area", 0),
"bbox": ann.get("bbox", [0, 0, 0, 0]),
})
return records, ann_records
def load_poses(scenes):
"""
Load poses.json from each scene where available.
Supports:
1. [{"R": ..., "t": ...}, ...]
2. {"id": {"R": ..., "t": ...}, ...}
3. {"image.npy": [{"R": ..., "t": ...}], ...}
"""
pose_records = []
for s in scenes:
poses_file = s["root"] / "poses.json"
if not poses_file.exists():
continue
with open(poses_file) as f:
poses = json.load(f)
if isinstance(poses, list):
iterable = []
for idx, p in enumerate(poses):
iterable.append((idx, p))
elif isinstance(poses, dict):
iterable = []
for key, value in poses.items():
if isinstance(value, list):
for p in value:
iterable.append((key, p))
elif isinstance(value, dict):
iterable.append((key, value))
else:
continue
for image_key, p in iterable:
if not isinstance(p, dict):
continue
t = p.get("cam_t_m2c") or p.get("t") or p.get("translation") or [0, 0, 0]
# Extract the rotation matrix
R = p.get("cam_R_m2c") or p.get("R") or p.get("rotation")
record = {
"scene_id": s["scene_id"],
"tx": t[0],
"ty": t[1],
"tz": t[2],
"image_id": image_key,
}
# Safely add R if it exists in the JSON
if R is not None:
record["R"] = R
pose_records.append(record)
return pose_records
# ---------------------------------------------------------------------------
# Train data loading (reference statistics for train-referenced deltas)
# ---------------------------------------------------------------------------
def _resolve_train_image_path(task_dir, file_name):
"""
Resolve the absolute image path of a train image. Tries, in order:
<task_dir>/<file_name>, <task_dir>/rgb/<file_name>, <task_dir>/rgb/<basename>.
Falls back to the first candidate if none exists.
"""
candidates = [
task_dir / file_name,
task_dir / "rgb" / file_name,
task_dir / "rgb" / Path(file_name).name,
]
for c in candidates:
if c.is_file():
return str(c)
return str(candidates[0])
def load_train_data(train_root):
"""
Load the train split. Expected layout:
<train_root>/[real/]<scene>/<task>/{annotations.coco.json, poses.json, rgb/, ...}
Tasks of the same scene are pooled, so the train scene_id is the scene folder
name (e.g. "000001") and matches the test scene_id.
Returns (train_records, train_pose_records). Records carry '_abs_path'.
Returns ([], []) if train_root is None or nothing is found.
"""
if train_root is None:
return [], []
train_root = Path(train_root)
if not train_root.is_dir():
print(f" [WARN] Train root not found: {train_root}")
return [], []
if (train_root / "real").is_dir():
train_root = train_root / "real"
train_records = []
train_pose_records = []
n_task_dirs = 0
for scene_dir in sorted(p for p in train_root.iterdir() if p.is_dir()):
# Task directories: sub-folders holding annotations; fall back to the
# scene folder itself if it holds annotations directly.
task_dirs = sorted(
p for p in scene_dir.iterdir()
if p.is_dir() and (p / "annotations.coco.json").exists()
)
if not task_dirs and (scene_dir / "annotations.coco.json").exists():
task_dirs = [scene_dir]
for task_dir in task_dirs:
with open(task_dir / "annotations.coco.json") as f:
coco = json.load(f)
cat_map = {}
supercat_map = {}
for c in coco.get("categories", []):
cat_map[c["id"]] = c["name"]
supercat_map[c["id"]] = c.get("supercategory", "unknown")
s = {
"scene_id": scene_dir.name,
"coco": coco,
"cat_map": cat_map,
"supercat_map": supercat_map,
"root": task_dir,
}
recs, _ = aggregate([s])
for r in recs:
r["_abs_path"] = _resolve_train_image_path(task_dir, r["file_name"])
r["_root"] = str(task_dir)
r["task"] = task_dir.name
train_records.extend(recs)
train_pose_records.extend(load_poses([s]))
n_task_dirs += 1
print(f" Train: {len(train_records)} images, {len(train_pose_records)} poses "
f"from {n_task_dirs} task folders under {train_root}")
return train_records, train_pose_records
def _train_reference_stats(train_records, train_pose_records):
"""
Compute the train reference values used for the train-referenced deltas:
mean intensity, translation centroid and mean rotation, per scene and global.
"""
refs = {
"scene_intensity_mean": {},
"global_intensity_mean": None,
"scene_translation_centroid": {},
"global_translation_centroid": None,
"scene_rotation_mean": {},
"global_rotation_mean": None,
}
# Illumination
scene_intensities = defaultdict(list)
all_intensities = []
if PILImage is not None:
for r in train_records:
p = Path(r.get("_abs_path", ""))
if not p.is_file():
continue
try:
img = np.asarray(PILImage.open(p).convert("L"))
m = float(np.mean(img))
except Exception:
continue
scene_intensities[r["scene_id"]].append(m)
all_intensities.append(m)
refs["scene_intensity_mean"] = {
sc: float(np.mean(v)) for sc, v in scene_intensities.items() if v
}
if all_intensities:
refs["global_intensity_mean"] = float(np.mean(all_intensities))
# Pose
scene_t = defaultdict(list)
scene_r = defaultdict(list)
all_t = []
all_r = []
for pose in train_pose_records:
sc = pose["scene_id"]
t = _pose_translation(pose)
rot = _pose_rotation(pose)
if t is not None:
scene_t[sc].append(t)
all_t.append(t)
if rot is not None:
scene_r[sc].append(rot)
all_r.append(rot)
refs["scene_translation_centroid"] = {
sc: np.mean(v, axis=0) for sc, v in scene_t.items() if v
}
if all_t:
refs["global_translation_centroid"] = np.mean(all_t, axis=0)
refs["scene_rotation_mean"] = {
sc: Rotation.concatenate(v).mean() for sc, v in scene_r.items() if v
}
if all_r:
refs["global_rotation_mean"] = Rotation.concatenate(all_r).mean()
return refs
# ---------------------------------------------------------------------------
# Scene metadata
# ---------------------------------------------------------------------------
SCENE_CAMERA = {1: "RealSense", 2: "Zivid", 3: "RealSense",
4: "Zivid", 5: "RealSense", 6: "Zivid"}
LOAD_CARRIER_GROUPS = [
("KLT4314", [1, 2]),
("KLT4315", [3, 4]),
("SetBox", [5, 6]),
]
SCENE_LOAD_CARRIER = {
1: "KLT4314", 2: "KLT4314",
3: "KLT4315", 4: "KLT4315",
5: "SetBox", 6: "SetBox",
}
CAMERA_COLORS = {
"RealSense": "#7EB8D4",
"Zivid": "#D4A87E",
}
BINARY_MAP = {
"empty_clean": "Anomaly-Free",
"empty_dirty": "Anomalous",
"non_empty": "Anomalous",
}
BINARY_CLASSES = ["Anomaly-Free", "Anomalous"]
TRINARY_CLASSES = CLASS_ORDER # ["empty_clean", "empty_dirty", "non_empty"]
PASTEL_GREEN = "#48c16e80"
PASTEL_PURPLE = "#48237480"
PASTEL_TEAL = "#1e9c8980"
PASTEL_YELLOW = "#eae51a80"
BIN_COLORS = {"Anomaly-Free": PASTEL_GREEN, "Anomalous": PASTEL_PURPLE}
TRI_COLORS = {
"empty_clean": PASTEL_GREEN,
"empty_dirty": PASTEL_TEAL,
"non_empty": PASTEL_YELLOW,
}
# ---------------------------------------------------------------------------
# Figure 1: Class distribution per scene — binary & trinary tasks (stacked bars)
# ---------------------------------------------------------------------------
def fig_class_per_scene(records, out_dir):
scenes_ids = sorted(set(r["scene_id"] for r in records))
scenes_ids_int = sorted(set(int(r["scene_id"]) for r in records))
n_scenes = len(scenes_ids)
binary_counts = defaultdict(lambda: defaultdict(int))
trinary_counts = defaultdict(lambda: defaultdict(int))
for r in records:
cls = r["classification"]
sid = r["scene_id"]
binary_counts[sid][BINARY_MAP[cls]] += 1
trinary_counts[sid][cls] += 1
bar_w = 0.30
task_gap = 0.06
scene_gap = 0.85
task1_offsets = np.array([i * scene_gap - (bar_w / 2 + task_gap / 2)
for i in range(n_scenes)])
task2_offsets = task1_offsets + bar_w + task_gap
scene_centres = (task1_offsets + task2_offsets) / 2
fig = plt.figure(figsize=(6.5, 6.0))
fig.patch.set_facecolor("white")
gs = fig.add_gridspec(2, 1, height_ratios=[4, 1.5], hspace=-0.02)
ax = fig.add_subplot(gs[0])
ax_table = fig.add_subplot(gs[1])
ax_table.axis("off")
fig.subplots_adjust(top=0.92, bottom=0.05)
def draw_stacked(ax, x_positions, class_order, color_map, count_dict, scenes):
bottoms = np.zeros(len(scenes))
for cls in class_order:
vals = np.array([count_dict[sc].get(cls, 0) for sc in scenes],
dtype=float)
ax.bar(x_positions, vals, width=bar_w, bottom=bottoms,
color=color_map[cls], label=cls,
edgecolor="white", linewidth=0.5)
for xp, v, bot in zip(x_positions, vals, bottoms):
if v >= 1:
ax.text(xp, bot + v / 2, str(int(v)),
ha="center", va="center",
fontsize=8, color="#444444", fontweight="bold")
bottoms += vals
for xp, tot in zip(x_positions, bottoms):
if tot > 0:
ax.text(xp, tot + 0.8, str(int(tot)),
ha="center", va="bottom",
fontsize=8, color="#333333", fontweight="bold")
draw_stacked(ax, task1_offsets, BINARY_CLASSES, BIN_COLORS,
binary_counts, scenes_ids)
draw_stacked(ax, task2_offsets, TRINARY_CLASSES, TRI_COLORS,
trinary_counts, scenes_ids)
margin = 0.25
x_left = task1_offsets[0] - margin
x_right = task2_offsets[-1] + margin
ax.set_xlim(x_left, x_right)
ax.set_xticks(scene_centres)
ax.set_xticklabels([])
ax.tick_params(axis="x", length=0)
for i in range(1, n_scenes):
sep_x = (task2_offsets[i - 1] + task1_offsets[i]) / 2
ax.axvline(sep_x, color=SPINE_COLOR, linewidth=0.7,
linestyle="dotted", alpha=0.5)
ax.grid(False)
blank = Patch(facecolor="none", edgecolor="none", label="")
legend_elements = (
[Patch(facecolor="none", edgecolor="none", label="Task 1:")] +
[Patch(facecolor=BIN_COLORS[c], edgecolor="#aaaaaa",
linewidth=0.5, label=c) for c in BINARY_CLASSES] +
[blank] +
[Patch(facecolor="none", edgecolor="none", label="Task 2:")] +
[Patch(facecolor=TRI_COLORS[c], edgecolor="#aaaaaa",
linewidth=0.5, label=c) for c in TRINARY_CLASSES]
)
ax.legend(handles=legend_elements,
title="Anomaly Detection Task",
fontsize=8, title_fontsize=10,
framealpha=0.9, edgecolor=SPINE_COLOR,
bbox_to_anchor=(1.0, 1.0),
loc="upper right",
ncol=2,
borderpad=0.6, labelspacing=0.3)
style_ax(ax, xlabel="", ylabel="Number of Images")
row_labels = ["Task", "Camera", "Load Carrier", "Scene"]
task_row = []
cam_row = []
lc_row = []
scene_row = []
row_labels = ["Task", "Camera", "Load Carrier", "Scene"]
# Store the values separately for manual centering later
cam_values = []
lc_values = []
scene_values = []
for sid in scenes_ids_int:
task_row += ["Task 1", "Task 2"]
cam = SCENE_CAMERA.get(sid, "Unknown")
lc = SCENE_LOAD_CARRIER.get(sid, "")
cam_values.append(cam)
lc_values.append(lc)
scene_values.append(f"Scene {sid}")
# leave cells empty, we'll draw centered text manually
cam_row += ["", ""]
lc_row += ["", ""]
scene_row += ["", ""]
cell_text = [task_row, cam_row, lc_row, scene_row]
boundaries = [x_left]
for i in range(n_scenes):
boundaries.append((task1_offsets[i] + task2_offsets[i]) / 2)
if i < n_scenes - 1:
boundaries.append((task2_offsets[i] + task1_offsets[i+1]) / 2)
else:
boundaries.append(x_right)
col_widths_data = [
boundaries[k+1] - boundaries[k]
for k in range(len(boundaries)-1)
]
total_w = sum(col_widths_data)
col_widths = [w / total_w for w in col_widths_data]
#ax_table.set_title(
# "Image Distribution Across Scenes and Classification Tasks",
# fontsize=9,
# pad=2
#)
tbl = ax_table.table(
cellText = cell_text,
rowLabels = row_labels,
colLabels = None,
cellLoc = "center",
loc = "center",
colWidths = col_widths,
)
tbl.auto_set_font_size(False)
tbl.set_fontsize(8)
tbl.scale(1, 1.6)
for (row, col), cell in tbl.get_celld().items():
cell.set_edgecolor("#9C9C9C")
cell.set_linewidth(0.5)
cell.set_facecolor("#FFFFFF")
if col == -1:
cell.set_text_props(
#fontstyle="italic",
#fontweigth="bold",
#color="#818181",
fontweight="bold",
fontsize=8
)
cell.visible_edges = "closed"
elif row == 0:
cell.visible_edges = "closed"
# Visually merge T1/T2 pairs
for row in [1, 2, 3]:
for i in range(n_scenes):
col_t1 = i * 2
col_t2 = i * 2 + 1
cell_t1 = tbl[row, col_t1]
cell_t2 = tbl[row, col_t2]
cell_t1.visible_edges = "LBT"
cell_t2.visible_edges = "RBT"
# Force layout update so cell coordinates are correct
fig.canvas.draw()
# Draw centered labels spanning both T1/T2 columns
for row, values in zip(
[1, 2, 3],
[cam_values, lc_values, scene_values]
):
for i, text in enumerate(values):
c1 = tbl[row, i * 2]
c2 = tbl[row, i * 2 + 1]
x = c1.get_x()
y = c1.get_y()
w = c1.get_width() + c2.get_width()
h = c1.get_height()
ax_table.text(
x + w / 2,
y + h / 2,
text,
ha="center",
va="center",
fontsize=8,
transform=ax_table.transAxes,
)
save(fig, out_dir / "image_dist_per_classification_and_scene.pdf")
# ---------------------------------------------------------------------------
# Figure 7.2: Mask area violin plots per category
# ---------------------------------------------------------------------------
def fig_mask_area_violin(ann_records, out_dir, tick_fs=10, label_fs=12):
cats = sorted(set(r["cat_name"] for r in ann_records))
data = {
c: np.log1p([r["area"] for r in ann_records
if r["cat_name"] == c and r["area"] > 0])
for c in cats
}
cats = [c for c in cats if len(data[c]) > 1]
colors = viridis_palette(len(cats))
x = np.arange(len(cats))
fig, ax = plt.subplots(figsize=(max(4, len(cats) * 0.5 + 1), 5))
fig.patch.set_facecolor("white")
parts = ax.violinplot(
[data[c] for c in cats],
positions=x,
showmedians=True,
showextrema=True,
widths=0.8
)
for pc, col in zip(parts["bodies"], colors):
pc.set_facecolor(col)
pc.set_alpha(0.8)
parts["cmedians"].set_color("white")
parts["cmins"].set_color("#555")
parts["cmaxes"].set_color("#555")
parts["cbars"].set_color("#555")
ax.set_xticks(x)
ax.set_xticklabels(cats, rotation=30, ha="right", fontsize=label_fs)
style_ax(ax, xlabel="Segmentation Mask", ylabel="log(1 + Mask Area in pixels²)")
ax.xaxis.label.set_fontweight("bold")
ax.yaxis.label.set_fontweight("bold")
ax.yaxis.label.set_fontsize(label_fs)
ax.xaxis.label.set_fontsize(label_fs)
ax.tick_params(axis="both", labelsize=label_fs)
ax.set_xlim(-0.5, len(cats) - 0.5)
fig.tight_layout()
save(fig, out_dir / "segmentation_mask_area_violin.pdf")
# ---------------------------------------------------------------------------
# Figure 9.3: Light intensity histograms all scenes
# ---------------------------------------------------------------------------
def _accumulate_gray_histogram(records):
"""
Accumulate the 256-bin grayscale histogram over all readable images of the
given records. Returns (histogram, number_of_loaded_images).
"""
hist_acc = np.zeros(256)
n_loaded = 0
for r in records:
img_path = Path(r.get("_abs_path", ""))
if not img_path.exists():
continue
try:
img_pil = PILImage.open(img_path).convert("L")
img = np.array(img_pil)
h, _ = np.histogram(img, bins=256, range=(0, 256))
hist_acc += h
n_loaded += 1
except Exception:
continue
return hist_acc, n_loaded
def fig_intensity_histogram_global(
records, out_dir, image_meta=None, y_max=0.017, train_records=None
):
if PILImage is None:
print(" [SKIP] Pillow not available for intensity histograms.")
return
if image_meta is None:
image_meta = {
"Dark": ("./test/000006/anomaly/rgb/00027.png", "Scene 6\nImg Num: 27"),
"Midtone": (
"./test/000004/anomaly/rgb/00116.png",
"Scene 4\nImg Num: 116",
),
"Bright": (
"./test/000001/anomaly/rgb/00235.png",
"Scene 1\nImg Num: 235",
),
}
fig, ax = plt.subplots(1, 1, figsize=(6, 4.3))
fig.patch.set_facecolor("white")
global_hist_acc = np.zeros(256)
global_n_loaded = 0
for r in records:
img_path = Path(r.get("_abs_path", ""))
if not img_path.exists():
continue
try:
img_pil = PILImage.open(img_path).convert("L")
img = np.array(img_pil)
h, _ = np.histogram(img, bins=256, range=(0, 256))
global_hist_acc += h
global_n_loaded += 1
except Exception:
continue
if global_n_loaded > 0:
from scipy.ndimage import gaussian_filter1d
global_hist_acc = gaussian_filter1d(global_hist_acc, sigma=2)
global_norm = global_hist_acc / global_hist_acc.sum()
ax.plot(
range(256),
global_norm,
color=plt.cm.viridis(0.2),
alpha=1.0,
linewidth=1.5,
label="Test",
)
if train_records:
train_hist, train_n_loaded = _accumulate_gray_histogram(train_records)
if train_n_loaded > 0:
train_hist = gaussian_filter1d(train_hist, sigma=2)
train_norm = train_hist / train_hist.sum()
ax.plot(
range(256),
train_norm,
color=plt.cm.viridis(0.88),
alpha=1.0,
linewidth=1.5,
linestyle="--",
label="Train",
)
# Legend placed inside the plot area at the bottom
ax.legend(
loc="lower center",
bbox_to_anchor=(0.42, 0.02),
ncol=2,
frameon=True,
framealpha=0.5,
fontsize=10,
borderpad=0.4,
facecolor="white",
edgecolor="gray",
)
if y_max is not None:
ax.set_ylim(0, y_max)
def add_sample_image(
img_path, label_info, xybox, title, highlight_color, is_right
):
if not img_path or not Path(img_path).exists():
return
try:
img_obj = PILImage.open(img_path)
orig_w, orig_h = img_obj.size
zoom_factor = 100.0 / max(orig_w, orig_h)
imagebox = OffsetImage(np.array(img_obj), zoom=zoom_factor)
img_gray = np.array(img_obj.convert("L"))
mean_val = np.mean(img_gray)
x_idx = min(255, max(0, int(mean_val)))
y_val = global_norm[x_idx]
ab = AnnotationBbox(
imagebox,
(mean_val, y_val),
xybox=xybox,
xycoords="data",
boxcoords="axes fraction",
arrowprops=dict(arrowstyle="->", color=highlight_color, lw=1),
bboxprops=dict(edgecolor=highlight_color),
)
ax.add_artist(ab)
ax.text(
xybox[0],
xybox[1] + 0.21,
title,
transform=ax.transAxes,
ha="center",
fontsize=8,
color=highlight_color,
weight="bold",
)
text_x_offset = -0.065 if is_right else 0.035
ax.text(
xybox[0] + text_x_offset,
xybox[1] - 0.23,
label_info,
transform=ax.transAxes,
ha="center",
va="center",
fontsize=8,
color="black",
)
except Exception:
pass
colors = [plt.cm.viridis(0.2), plt.cm.viridis(0.5), plt.cm.viridis(0.8)]
# Shifted image box y coordinates up from 0.78 to 0.86
positions = [(0.19, 0.80), (0.5, 0.80), (0.81, 0.80)]
titles = ["Dark", "Midtone", "Bright"]
for i, key in enumerate(titles):
if key in image_meta:
path, label = image_meta[key]
is_right = i == 2
add_sample_image(path, label, positions[i], key, colors[i], is_right)
style_ax(
ax, title="", xlabel="Pixel Intensity", ylabel="Normalized Pixel Frequency"
)
ax.set_facecolor("white")
fig.tight_layout()
save(fig, out_dir / "intensity_histogram_global.pdf")
# ---------------------------------------------------------------------------
# Figure 9.4: Light intensity statistics
# ---------------------------------------------------------------------------
def calc_intensity_statistics_global(records, label="Dataset"):
if PILImage is None:
print(" [SKIP] Pillow not available for intensity calculations.")
return
# Use int64 to prevent overflow when summing millions of pixels
global_hist_acc = np.zeros(256, dtype=np.int64)
global_n_loaded = 0
for r in records:
img_path = Path(r.get("_abs_path", ""))
if not img_path.exists():
continue
try:
img_pil = PILImage.open(img_path).convert("L")
img = np.array(img_pil)
h, _ = np.histogram(img, bins=256, range=(0, 256))
global_hist_acc += h
global_n_loaded += 1
except Exception:
continue
if global_n_loaded == 0:
print("No images were loaded successfully.")
return
total_pixels = global_hist_acc.sum()
if total_pixels == 0:
print("Total pixels is 0. Cannot compute statistics.")
return
intensities = np.arange(256)
# Calculate Mean
mean_intensity = np.sum(intensities * global_hist_acc) / total_pixels
# Calculate Variance and Standard Deviation
mean_sq_intensity = np.sum((intensities ** 2) * global_hist_acc) / total_pixels
variance = mean_sq_intensity - (mean_intensity ** 2)
std_intensity = np.sqrt(variance)
# Calculate Min and Max
non_zero_bins = np.where(global_hist_acc > 0)[0]
min_val = non_zero_bins[0] if len(non_zero_bins) > 0 else 0
max_val = non_zero_bins[-1] if len(non_zero_bins) > 0 else 0
# Calculate Percentiles via Cumulative Distribution
cum_hist = np.cumsum(global_hist_acc)
cum_hist_norm = cum_hist / total_pixels
p25 = np.searchsorted(cum_hist_norm, 0.25)
median = np.searchsorted(cum_hist_norm, 0.50)
p75 = np.searchsorted(cum_hist_norm, 0.75)
print(f"{label} Intensity Statistics (Over {global_n_loaded} images):")
print(f" Total Pixels: {total_pixels:,}")
print(f" Mean: {mean_intensity:.2f}")
print(f" Std Dev: {std_intensity:.2f}")
print(f" Min: {min_val}")
print(f" Max: {max_val}")
print(f" 25th Pct: {p25}")
print(f" Median: {median}")
print(f" 75th Pct: {p75}")
return {
"n_images": global_n_loaded,
"total_pixels": total_pixels,
"mean": mean_intensity,
"std": std_intensity,
"min": min_val,
"max": max_val,
"p25": p25,
"median": median,
"p75": p75
}
# ---------------------------------------------------------------------------
# Figure 12.1: Pose translation 3D scatter 3D angle axis
# ---------------------------------------------------------------------------
def draw_working_frustum(ax, K, R, t, min_depth, actual_max_depth, draw_max_depth=None, color='magenta', label='Camera'):
if draw_max_depth is None or draw_max_depth > actual_max_depth:
draw_max_depth = actual_max_depth
fx, fy = K[0, 0], K[1, 1]
cx, cy = K[0, 2], K[1, 2]
w = cx * 2
h = cy * 2
corners = np.array([[0,0], [w,0], [w,h], [0,h]])
def get_pts_at_depth(depth):
pts = np.zeros((4, 3))
pts[:, 0] = (corners[:, 0] - cx) * depth / fx
pts[:, 1] = (corners[:, 1] - cy) * depth / fy
pts[:, 2] = depth
return pts
near_pts = get_pts_at_depth(min_depth)
far_pts = get_pts_at_depth(draw_max_depth)
origin = np.array([[0, 0, 0]])
all_pts = np.vstack((origin, near_pts, far_pts))
has_extension = actual_max_depth > draw_max_depth
if has_extension:
ext_pts = get_pts_at_depth(draw_max_depth + 150.0)
all_pts = np.vstack((all_pts, ext_pts))
all_pts = (R.T @ (all_pts.T - t.reshape(3, 1))).T
orig = all_pts[0]
n = all_pts[1:5]
f = all_pts[5:9]
for i in range(4):
ax.plot([orig[0], f[i,0]], [orig[1], f[i,1]], [orig[2], f[i,2]], color=color, alpha=0.3, linestyle=':')
for i in range(4):
next_i = (i + 1) % 4
ax.plot([n[i,0], n[next_i,0]], [n[i,1], n[next_i,1]], [n[i,2], n[next_i,2]], color=color, linewidth=1.5)
far_ls = ':' if has_extension else '-'
ax.plot([f[i,0], f[next_i,0]], [f[i,1], f[next_i,1]], [f[i,2], f[next_i,2]], color=color, linewidth=1.5, linestyle=far_ls)
ax.plot([n[i,0], f[i,0]], [n[i,1], f[i,1]], [n[i,2], f[i,2]], color=color, linewidth=1.5)
if has_extension:
ext = all_pts[9:13]
ax.plot([f[i,0], ext[i,0]], [f[i,1], ext[i,1]], [f[i,2], ext[i,2]], color=color, linewidth=1.5, linestyle=':')
if i == 0:
ax.text(ext[i,0], ext[i,1], ext[i,2] - 40, f"Max depth range at {actual_max_depth}mm",
color=color, fontsize=11, style='italic',
bbox=dict(facecolor='white', alpha=0.8, edgecolor='none', pad=2))
# Realistic Camera Body Geometry
lw, lh, l_depth = 10.0, 10.0, -12.0
bw, bh, b_front, b_back = 20.0, 15.0, -12.0, -35.0
cam_body_pts = np.array([
[0, 0, 0],
[-lw, -lh, l_depth], [lw, -lh, l_depth], [lw, lh, l_depth], [-lw, lh, l_depth],
[-bw, -bh, b_front], [bw, -bh, b_front], [bw, bh, b_front], [-bw, bh, b_front],
[-bw, -bh, b_back], [bw, -bh, b_back], [bw, bh, b_back], [-bw, bh, b_back],
])
cam_body_world = (R.T @ (cam_body_pts.T - t.reshape(3, 1))).T
box_edges = [
(0,1), (0,2), (0,3), (0,4),
(1,2), (2,3), (3,4), (4,1),
(5,6), (6,7), (7,8), (8,5),
(9,10), (10,11), (11,12), (12,9),
(5,9), (6,10), (7,11), (8,12)
]
for e1, e2 in box_edges:
ax.plot([cam_body_world[e1,0], cam_body_world[e2,0]],
[cam_body_world[e1,1], cam_body_world[e2,1]],
[cam_body_world[e1,2], cam_body_world[e2,2]],
color=color, linewidth=0.8)
ax.plot([], [], [], color=color, linewidth=1.5, label=label)
return all_pts
def fig_pose_3d_with_frames(pose_records, out_dir, cam_properties=None, voxel_size=100):
if not pose_records and not cam_properties:
print(" [SKIP] No pose data found.")
return
plt.rcParams.update({
'font.size': 14,
'axes.titlesize': 16,
'axes.labelsize': 14,
'legend.fontsize': 12
})
fig = plt.figure(figsize=(12, 9))
ax = fig.add_subplot(111, projection="3d")
ax.set_facecolor('white')
ax.xaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))
ax.yaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))
ax.zaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))
tx_list, ty_list, tz_list = [], [], []
length = 100.0
alpha_val = 0.4
occupied_voxels = set()
if pose_records:
for p in pose_records:
if "tx" in p:
t = np.array([p["tx"], p["ty"], p["tz"]])
elif "t" in p:
t = np.array(p["t"])
else:
continue
if voxel_size is not None and voxel_size > 0:
voxel_idx = (
int(np.floor(t[0] / voxel_size)),
int(np.floor(t[1] / voxel_size)),
int(np.floor(t[2] / voxel_size))
)
if voxel_idx in occupied_voxels:
continue
occupied_voxels.add(voxel_idx)
tx_list.append(t[0])
ty_list.append(t[1])
tz_list.append(t[2])
R = np.array(p["R"]).reshape(3, 3)
for i, color in enumerate(['r', 'g', 'b']):
ax.quiver(t[0], t[1], t[2], R[0, i] * length, R[1, i] * length, R[2, i] * length,
color=color, alpha=alpha_val)
ax.plot([], [], [], color='r', label='X Axis Rotation')
ax.plot([], [], [], color='g', label='Y Axis Rotation')
ax.plot([], [], [], color='b', label='Z Axis Rotation')
all_x, all_y, all_z = list(tx_list), list(ty_list), list(tz_list)
all_x.append(0.0)
all_y.append(0.0)
all_z.append(0.0)
if cam_properties:
cmap = plt.get_cmap('viridis')
safe_viridis_values = [0.1, 0.88]
for idx, (cam_id, props) in enumerate(cam_properties.items()):
K = np.array(props["cam_K"]).reshape(3, 3)
R = np.array(props.get("R", np.eye(3))).reshape(3, 3)
t = np.array(props.get("t", np.zeros(3)))
min_depth = props.get("min_depth", 300.0)
max_depth = props.get("max_depth", 1000.0)
draw_max_depth = props.get("draw_max_depth", max_depth)
color_val = safe_viridis_values[idx % len(safe_viridis_values)]
cam_color = cmap(color_val)
legend_label = f"{cam_id} Frustum"
pts = draw_working_frustum(ax, K, R, t, min_depth, max_depth, draw_max_depth=draw_max_depth, color=cam_color, label=legend_label)
all_x.extend(pts[:, 0])
all_y.extend(pts[:, 1])
all_z.extend(pts[:, 2])
if all_x:
ax.set_xlim(min(all_x), max(all_x))
ax.set_ylim(min(all_y), max(all_y))
ax.set_zlim(min(all_z), max(all_z))
ax.set_xlabel("X Translation [mm]", labelpad=20)
ax.set_ylabel("Y Translation [mm]", labelpad=20)
ax.set_zlabel("Z Translation [mm]", labelpad=20)
ax.tick_params(axis='z', pad=10)
if cam_properties or pose_records:
ax.legend(loc='upper right', bbox_to_anchor=(0.4, 0.78), ncol = 1)
ax.view_init(elev=8, azim=-79)
ax.invert_zaxis()
plt.tight_layout()
plt.savefig(out_dir / "translation_rotation_3d.pdf", bbox_inches='tight')
plt.rcParams.update(plt.rcParamsDefault)
def _pose_translation(p):
if "tx" in p:
return np.array([p["tx"], p["ty"], p["tz"]], dtype=float)
if "t" in p:
return np.array(p["t"], dtype=float)
return None
def fig_pose_3d_train_vs_test(pose_records, train_pose_records, out_dir=None,
cam_properties=None, voxel_size=135,
sphere_coverage=100.0, show_points=False,
show_vectors=True, show_ellipsoids=True,
task2_parity="odd"):
import re
if not pose_records and not train_pose_records:
print(" [SKIP] No pose data found for train/test comparison.")
return
task2_parity = str(task2_parity).lower()
if task2_parity not in {"odd", "even", "both"}:
raise ValueError("task2_parity must be 'odd', 'even', or 'both'")
def is_task2_pose(p):
task = str(p.get("task", "")).lower().replace(" ", "")
if task in {"2", "task2", "task_2"}:
return True
for key in ("image_path", "_abs_path", "file_path", "path",
"image_name", "file_name"):
value = str(p.get(key, "")).replace("\\", "/").lower()
if re.search(r"(?:^|/)task[_]?2(?:/|$)", value):
return True
return False
def get_image_number(p):
for key in ("image_id", "image_name", "file_name",
"image_path", "_abs_path", "file_path", "path"):
value = str(p.get(key, ""))
if not value or value.lower() == "none":
continue
match = re.search(r"(\d+)(?=\.[^.]+$|$)", value)
if match:
return int(match.group(1))
return None
sets = [
("Test", pose_records, "#fde725"),
("Train", train_pose_records, "#20a486"),
]
rc = {
'font.size': 14,
'axes.titlesize': 16,
'axes.labelsize': 14,
'legend.fontsize': 12,
}
task2_seen = 0
task2_kept = 0
with plt.rc_context(rc):
fig = plt.figure(figsize=(12, 9))
ax = fig.add_subplot(111, projection="3d")
ax.set_facecolor('white')
ax.xaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))
ax.yaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))
ax.zaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))
length = 100.0
alpha_val = 0.4
all_x, all_y, all_z = [0.0], [0.0], [0.0]
sphere_proxies = []
point_proxies = []
scatter_x, scatter_y, scatter_z, scatter_c = [], [], [], []
for name, poses, color in sets:
if not poses:
continue
all_translations = []
filtered_translations = []
occupied_voxels = set()
for p in poses:
# Apply parity filtering only to Task 2 poses in the training set.
if name == "Train" and is_task2_pose(p):
task2_seen += 1
if task2_parity != "both":
image_number = get_image_number(p)
if image_number is None:
print(
" [WARNING] Could not determine image number "
"for a Task 2 training pose; skipping it for "
f"task2_parity='{task2_parity}'."
)
continue
if task2_parity == "odd" and image_number % 2 == 0:
continue
if task2_parity == "even" and image_number % 2 != 0:
continue
task2_kept += 1
t = _pose_translation(p)
if t is None:
continue
all_translations.append(t)
if voxel_size is not None and voxel_size > 0:
voxel_idx = (
int(np.floor(t[0] / voxel_size)),
int(np.floor(t[1] / voxel_size)),
int(np.floor(t[2] / voxel_size)),
)
if voxel_idx in occupied_voxels:
continue
occupied_voxels.add(voxel_idx)
filtered_translations.append(t)
if show_vectors and p.get("R") is not None:
R = np.asarray(p["R"], dtype=float).reshape(3, 3)
for i, axis_color in enumerate(['r', 'g', 'b']):
ax.quiver(t[0], t[1], t[2],
R[0, i] * length, R[1, i] * length, R[2, i] * length,
color=axis_color, alpha=alpha_val)
if not all_translations:
continue
t_arr_all = np.array(all_translations)
t_arr_filtered = np.array(filtered_translations)
if show_points and len(t_arr_filtered) > 0:
scatter_x.extend(t_arr_filtered[:, 0])
scatter_y.extend(t_arr_filtered[:, 1])
scatter_z.extend(t_arr_filtered[:, 2])
scatter_c.extend([color] * len(t_arr_filtered))
point_proxies.append(
Line2D([0], [0], marker='o', color='w', markerfacecolor=color,
markersize=6, label=f"{name} translations")
)
center = t_arr_all.mean(axis=0)
if show_ellipsoids:
dists = np.linalg.norm(t_arr_all - center, axis=1)
threshold = np.percentile(dists, sphere_coverage)
core_points = t_arr_all[dists <= threshold]
if len(core_points) >= 4:
hull = ConvexHull(core_points)
faces = [core_points[simplex] for simplex in hull.simplices]
poly = Poly3DCollection(faces, alpha=0.2, facecolors=color, linewidths=0)#, shade=True)
ax.add_collection3d(poly)
sphere_proxies.append(
Patch(facecolor=color, edgecolor=color, alpha=0.3,
label=f"{name} convex hull")
)
all_x.extend([core_points[:, 0].min(), core_points[:, 0].max()])
all_y.extend([core_points[:, 1].min(), core_points[:, 1].max()])
all_z.extend([core_points[:, 2].min(), core_points[:, 2].max()])
else:
all_x.extend(t_arr_filtered[:, 0])
all_y.extend(t_arr_filtered[:, 1])
all_z.extend(t_arr_filtered[:, 2])
if task2_parity != "both":
print(
f" Train Task 2 parity filter ('{task2_parity}'): "
f"kept {task2_kept}/{task2_seen} Task 2 poses."
)
if show_points and scatter_x:
ax.scatter(scatter_x, scatter_y, scatter_z,
s=0.2, c=scatter_c, alpha=1, depthshade=False)
if show_vectors:
ax.plot([], [], [], color='r', label='X Axis Rotation')
ax.plot([], [], [], color='g', label='Y Axis Rotation')
ax.plot([], [], [], color='b', label='Z Axis Rotation')
if cam_properties:
cmap = plt.get_cmap('viridis')
safe_viridis_values = [0.1, 0.88]
for idx, (cam_id, props) in enumerate(cam_properties.items()):
K = np.array(props["cam_K"]).reshape(3, 3)
R = np.array(props.get("R", np.eye(3))).reshape(3, 3)
t = np.array(props.get("t", np.zeros(3)))
min_depth = props.get("min_depth", 300.0)
max_depth = props.get("max_depth", 1000.0)
draw_max_depth = props.get("draw_max_depth", max_depth)
color_val = safe_viridis_values[idx % len(safe_viridis_values)]
cam_color = cmap(color_val)
pts = draw_working_frustum(
ax, K, R, t, min_depth, max_depth,
draw_max_depth=draw_max_depth,
color=cam_color,
label=f"{cam_id} Frustum",
)
all_x.extend(pts[:, 0])
all_y.extend(pts[:, 1])
all_z.extend(pts[:, 2])
if all_x:
ax.set_xlim(min(all_x), max(all_x))
ax.set_ylim(min(all_y), max(all_y))
ax.set_zlim(min(all_z), max(all_z))
ax.set_xlabel("X Translation [mm]", labelpad=20)
ax.set_ylabel("Y Translation [mm]", labelpad=20)
ax.set_zlabel("Z Translation [mm]", labelpad=20)
ax.tick_params(axis='z', pad=10)
handles, labels = ax.get_legend_handles_labels()
handles = point_proxies + handles + sphere_proxies
ax.legend(handles=handles, loc='upper left', bbox_to_anchor=(0.13, 0.78), ncol=1)
ax.view_init(elev=8, azim=-79)
ax.invert_zaxis()
plt.tight_layout()
if out_dir:
out_path = out_dir / "translation_rotation_3d_train_vs_test_vectors.pdf"
plt.savefig(out_path, bbox_inches='tight')
plt.show()
plt.close(fig)
# ---------------------------------------------------------------------------
# INFO Function: Print 6DOF stats
# ---------------------------------------------------------------------------
def print_6dof_stats(pose_records, label=None):
if label:
print(f"\n[{label}]")
if not pose_records:
print(" [SKIP] No pose data found.")
return
translations = []
rotations_euler = []
for p in pose_records:
if "tx" in p:
t = [p["tx"], p["ty"], p["tz"]]
elif "t" in p:
t = p["t"]
else:
continue
translations.append(t)
if "R" in p:
rmat = np.array(p["R"]).reshape(3, 3)
euler = Rotation.from_matrix(rmat).as_euler('xyz', degrees=True)
rotations_euler.append(euler)
elif "rx" in p:
rvec = [p["rx"], p["ry"], p["rz"]]
euler = Rotation.from_rotvec(rvec).as_euler('xyz', degrees=True)
rotations_euler.append(euler)
else:
rotations_euler.append([0.0, 0.0, 0.0])
t_arr = np.array(translations)
r_arr = np.array(rotations_euler)
t_mean = np.mean(t_arr, axis=0)
t_std = np.std(t_arr, axis=0)
r_mean = np.mean(r_arr, axis=0)
r_std = np.std(r_arr, axis=0)
print("Translation Statistics [mm]:")
print(f" X: Mean {t_mean[0]:.3f}, Std {t_std[0]:.3f}")
print(f" Y: Mean {t_mean[1]:.3f}, Std {t_std[1]:.3f}")
print(f" Z: Mean {t_mean[2]:.3f}, Std {t_std[2]:.3f}")
print("Rotation Statistics (Euler XYZ) [degrees]:")
print(f" RX: Mean {r_mean[0]:.3f}, Std {r_std[0]:.3f}")
print(f" RY: Mean {r_mean[1]:.3f}, Std {r_std[1]:.3f}")
print(f" RZ: Mean {r_mean[2]:.3f}, Std {r_std[2]:.3f}")
return t_mean, t_std, r_mean, r_std
# ---------------------------------------------------------------------------
# Figure 14.2: Spatial annotation heatmap per category
# ---------------------------------------------------------------------------
def fig_spatial_heatmap_ungrouped(ann_records, out_dir):
H, W = 480, 640
if not HAS_PYCOCOTOOLS:
return
FS = 19 # base font size; adjust as needed
# Merge nuisance_dent and nuisance_plastic into one entry
MERGED = {
"nuisance_dent+plastic": ["nuisance_dent", "nuisance_plastic"],
}
MERGED_LOOKUP = {}
for merged_name, members in MERGED.items():
for m in members:
MERGED_LOOKUP[m] = merged_name
# Discover all unique category names, replacing merged members with the merged key
all_cats_raw = sorted({r["cat_name"] for r in ann_records if "cat_name" in r})
seen = set()
all_cats = []
for cat in all_cats_raw:
display = MERGED_LOOKUP.get(cat, cat)
if display not in seen:
all_cats.append(display)
seen.add(display)
# Build one heatmap per display category
heatmaps = {cat: np.zeros((H, W), dtype=float) for cat in all_cats}
for r in ann_records:
seg = r.get("_segmentation")
if seg is None:
continue
cat = r.get("cat_name")
if cat is None:
continue
display = MERGED_LOOKUP.get(cat, cat)
if display not in heatmaps:
continue
try:
if isinstance(seg, dict) and not isinstance(seg.get("counts"), list):
rle = seg
else:
rle = coco_mask_utils.frPyObjects(seg, H, W)
m = coco_mask_utils.decode(rle)
if m.ndim == 3:
m = m.sum(axis=2)
heatmaps[display] += m.astype(float)
except Exception:
continue
n_cats = len(all_cats) # 11 after merge
n_rows, n_cols = 2, 6
fig, axes = plt.subplots(n_rows, n_cols, figsize=(n_cols * 4, n_rows * 3.5))
fig.patch.set_facecolor("white")
axes = axes.flatten()
for ax, cat in zip(axes, all_cats):
im = ax.imshow(heatmaps[cat], cmap="viridis", interpolation="bilinear")
ax.set_title(cat, fontsize=FS)
ax.axis("off")
cbar = fig.colorbar(im, ax=ax, fraction=0.046, pad=0.04)
cbar.ax.tick_params(labelsize=FS - 2)
for ax in axes[n_cats:]:
ax.set_visible(False)
fig.tight_layout()
save(fig, out_dir / "spatial_heatmap_ungrouped.pdf")
def fig_spatial_heatmap_ungrouped_common_legend(ann_records, out_dir):
H, W = 480, 640
if not HAS_PYCOCOTOOLS:
return
FS = 14 # base font size; adjust as needed
# Merge nuisance_dent and nuisance_plastic into one entry
MERGED = {
"nuisance_dent+plastic": ["nuisance_dent", "nuisance_plastic"],
}
MERGED_LOOKUP = {}
for merged_name, members in MERGED.items():
for m in members:
MERGED_LOOKUP[m] = merged_name
# Discover all unique category names, replacing merged members with the merged key
all_cats_raw = sorted({r["cat_name"] for r in ann_records if "cat_name" in r})
seen = set()
all_cats = []
for cat in all_cats_raw:
display = MERGED_LOOKUP.get(cat, cat)
if display not in seen:
all_cats.append(display)
seen.add(display)
# Build one heatmap per display category
heatmaps = {cat: np.zeros((H, W), dtype=float) for cat in all_cats}
for r in ann_records:
seg = r.get("_segmentation")
if seg is None:
continue
cat = r.get("cat_name")
if cat is None:
continue
display = MERGED_LOOKUP.get(cat, cat)
if display not in heatmaps:
continue
try:
if isinstance(seg, dict) and not isinstance(seg.get("counts"), list):
rle = seg
else:
rle = coco_mask_utils.frPyObjects(seg, H, W)
m = coco_mask_utils.decode(rle)
if m.ndim == 3:
m = m.sum(axis=2)
heatmaps[display] += m.astype(float)
except Exception:
continue
n_cats = len(all_cats) # 11 after merge
n_rows, n_cols = 4, 3
fig, axes = plt.subplots(n_rows, n_cols, figsize=(n_cols * 4, n_rows * 2.9))
fig.patch.set_facecolor("white")
axes = axes.flatten()
# Exactly 3 pixel ticks per axis
x_ticks = [0, W // 2, W - 1]
y_ticks = [0, H // 2, H - 1]
for ax, cat in zip(axes, all_cats):
im = ax.imshow(
heatmaps[cat],
cmap="viridis",
interpolation="bilinear"
)
ax.set_title(cat, fontsize=FS)
# Axis names
ax.set_xlabel("x (pixels)", fontsize=FS - 1)
ax.set_ylabel("y (pixels)", fontsize=FS - 1)
# Pixel values
ax.set_xticks(x_ticks)
ax.set_yticks(y_ticks)
ax.tick_params(
axis="both",
which="major",
labelsize=FS - 3
)
ax.tick_params(
axis="y",
labelrotation=70
)
cbar = fig.colorbar(
im,
ax=ax,
fraction=0.046,
pad=0.07
)
cbar.set_label(
"Annotation count",
fontsize=FS - 2
)
cbar.ax.tick_params(labelsize=FS - 2)
for ax in axes[n_cats:]:
ax.set_visible(False)
fig.subplots_adjust(
left=0.08,
right=0.95,
top=0.97,
bottom=0.05,
hspace=0.5,
wspace=0.30
)
fig.tight_layout()
save(fig, out_dir / "spatial_heatmap_ungrouped.pdf")
# ---------------------------------------------------------------------------
# Main orchestration
# ---------------------------------------------------------------------------
def inject_abs_paths(records, scenes):
"""Attach absolute image paths to each record for pixel-level figures."""
scene_root_map = {s["scene_id"]: s["root"] for s in scenes}
for r in records:
root = scene_root_map.get(r["scene_id"])
if root:
r["_abs_path"] = str(root / r["file_name"])
r["_root"] = str(root)
def inject_segmentation(ann_records, scenes):
"""Attach segmentation data to ann_records for spatial heatmap figure."""
# Build lookup: (scene_id, image_id, category_name) -> [segmentations]
for s in scenes:
scene_id = s["scene_id"]
cat_map = s["cat_map"]
for ann in s["coco"].get("annotations", []):
cat_name = cat_map.get(ann["category_id"], "unknown")
seg = ann.get("segmentation")
if seg:
# Find matching ann_record and inject
for ar in ann_records:
if (ar["scene_id"] == scene_id and
ar["image_id"] == ann["image_id"] and
ar["cat_name"] == cat_name and
"_segmentation" not in ar):
ar["_segmentation"] = seg
break
my_cameras = {
"RealSense": {
"cam_K": [608.43, 0.0, 311.2, 0.0, 608.4, 239.6, 0.0, 0.0, 1.0],
"min_depth": 300.0,
"max_depth": 3000.0,
"draw_max_depth": 1200.0
},
"Zivid": {
"cam_K": [1242.25, 0.0, 620.7, 0.0, 1241.8, 503.7, 0.0, 0.0, 1.0],
"min_depth": 350.0,
"max_depth": 1100.0,
"draw_max_depth": 1100.0
}
}
def calc_variability_metrics(records, pose_records, label="", ignore_sym=False, sym_axis='z'):
print("Variability Metrics Report" + label)
# ------------------------------------------------------------------
# Illumination spread
# ------------------------------------------------------------------
scene_intensity = defaultdict(list)
all_intensity = []
if PILImage is not None:
for r in records:
img_path_str = r.get("_abs_path", "")
if not img_path_str:
continue
img_path = Path(img_path_str)
if img_path.is_file():
try:
img = np.array(PILImage.open(img_path).convert("L"))
mean_val = np.mean(img)
scene_intensity[r["scene_id"]].append(mean_val)
all_intensity.append(mean_val)
except Exception:
pass
print("\nIllumination Spread per Scene (Mean Pixel Intensity):")
for sc in sorted(scene_intensity.keys()):
means = scene_intensity[sc]
if means:
print(f" Scene {sc}: Mean {np.mean(means):.2f}, StdDev {np.std(means):.2f}, "
f"Min {np.min(means):.2f}, Max {np.max(means):.2f}")
if all_intensity:
print(f"\nIllumination Spread (All Scenes Pooled): "
f"Mean {np.mean(all_intensity):.2f}, StdDev {np.std(all_intensity):.2f}, "
f"Min {np.min(all_intensity):.2f}, Max {np.max(all_intensity):.2f}")
if not pose_records:
return
# ------------------------------------------------------------------
# Pose collection
# ------------------------------------------------------------------
scene_poses = defaultdict(lambda: {"t": [], "rot": []})
t_all = []
rot_all = []
scene_ids_all = [] # Track scene IDs for the global calculation
for p in pose_records:
sc = p["scene_id"]
if "tx" in p:
t = [p["tx"], p["ty"], p["tz"]]
elif "t" in p:
t = p["t"]
else:
t = None
rot = None
if "R" in p:
rmat = np.array(p["R"]).reshape(3, 3)
rot = Rotation.from_matrix(rmat)
elif "rx" in p:
rvec = [p["rx"], p["ry"], p["rz"]]
rot = Rotation.from_rotvec(rvec)
if t is not None:
t_all.append(t)
scene_poses[sc]["t"].append(t)
if rot is not None:
rot_all.append(rot)
scene_poses[sc]["rot"].append(rot)
scene_ids_all.append(sc) # Append to the global tracking list
def _translation_spread_mm(t_list):
"""Per-pose Euclidean distance from the centroid, merging X/Y/Z
into a single scalar. Returns (mean, std, min, max)."""
if len(t_list) < 2:
return None
t_arr = np.array(t_list)
centroid = np.mean(t_arr, axis=0)
dist = np.linalg.norm(t_arr - centroid, axis=1)
return float(np.mean(dist)), float(np.std(dist)), float(np.min(dist)), float(np.max(dist))
def _quat_spread_deg(rot_list, scene_ids=None):
if len(rot_list) < 2:
return None
rots = Rotation.concatenate(rot_list)
mean_rot = rots.mean()
rel = mean_rot.inv() * rots
dev_deg = rel.magnitude() * 180.0 / np.pi
if ignore_sym and scene_ids is not None:
vec = [0.0, 0.0, 0.0]
vec[{'x': 0, 'y': 1, 'z': 2}[sym_axis.lower()]] = np.pi
sym_rot = Rotation.from_rotvec(vec)
rel_sym = mean_rot.inv() * (rots * sym_rot)
dev_deg_sym = rel_sym.magnitude() * 180.0 / np.pi
# Apply symmetry only to indices where scene_id <= 4
mask = np.array([int(sid) <= 4 for sid in scene_ids])
dev_deg[mask] = np.minimum(dev_deg[mask], dev_deg_sym[mask])
return float(np.mean(dev_deg)), float(np.std(dev_deg)), float(np.min(dev_deg)), float(np.max(dev_deg))
# ------------------------------------------------------------------
# Global (all scenes pooled)
# ------------------------------------------------------------------
print("\nGlobal Pose Diversity:")
t_global = _translation_spread_mm(t_all)
if t_global is not None:
mean_t, std_t, min_t, max_t = t_global
print(f" Translation Spread [mm]: Mean {mean_t:.1f}, StdDev {std_t:.1f}, "
f"Min {min_t:.1f}, Max {max_t:.1f}")
r_global = _quat_spread_deg(rot_all, scene_ids=scene_ids_all)
if r_global is not None:
mean_r, std_r, min_r, max_r = r_global
print(f" Rotation Spread [deg]: Mean {mean_r:.1f}, StdDev {std_r:.1f}, "
f"Min {min_r:.1f}, Max {max_r:.1f}")
# ------------------------------------------------------------------
# Per-scene
# ------------------------------------------------------------------
print("\nPer-Scene Pose Spread:")
for sc in sorted(scene_poses.keys()):
ts = scene_poses[sc]["t"]
rots_sc = scene_poses[sc]["rot"]
line_parts = [f" Scene {sc}:"]
t_summary = _translation_spread_mm(ts)
if t_summary is not None:
mean_t, std_t, min_t, max_t = t_summary
line_parts.append(
f"Translation [mm] Mean {mean_t:.1f} StdDev {std_t:.1f} Min {min_t:.1f} Max {max_t:.1f}"
)
r_summary = _quat_spread_deg(rots_sc, scene_ids=[sc] * len(rots_sc))
if r_summary is not None:
mean_r, std_r, min_r, max_r = r_summary
line_parts.append(
f"Rotation [deg] Mean {mean_r:.1f} StdDev {std_r:.1f} Min {min_r:.1f} Max {max_r:.1f}"
)
print(" | ".join(line_parts))
def _pose_rotation(pose):
"""Convert a pose record to a scipy Rotation object."""
if "R" in pose:
rmat = np.asarray(pose["R"], dtype=float).reshape(3, 3)
return Rotation.from_matrix(rmat)
if "rx" in pose:
rvec = np.array(
[pose["rx"], pose["ry"], pose["rz"]],
dtype=float,
)
return Rotation.from_rotvec(rvec)
return None
def _pose_translation(pose):
"""Extract the translation vector from a pose record."""
if "tx" in pose:
return np.array(
[pose["tx"], pose["ty"], pose["tz"]],
dtype=float,
)
if "t" in pose:
return np.asarray(pose["t"], dtype=float)
return None
def _pose_key_variants(value):
"""
Generate possible identifiers for matching a pose record to an image.
Pose files in I-BADAS may use integer indices, image filenames,
or filename stems as keys.
"""
variants = set()
if value is None:
return variants
text = str(value)
variants.add(text)
path = Path(text)
variants.add(path.name)
variants.add(path.stem)
try:
number = int(text)
variants.add(str(number))
variants.add(f"{number:05d}")
variants.add(f"{number:06d}")
variants.add(f"{number:08d}")
except (TypeError, ValueError):
pass
return variants
def _build_pose_lookup(pose_records):
"""
Build a lookup table from scene/image identifiers to pose records.
"""
lookup = {}
for pose in pose_records:
scene_id = pose["scene_id"]
for key in _pose_key_variants(pose.get("image_id")):
lookup[(scene_id, key)] = pose
return lookup
def _find_pose_for_record(record, pose_lookup):
"""Find the pose corresponding to an image record."""
scene_id = record["scene_id"]
candidates = set()
candidates.update(_pose_key_variants(record.get("image_id")))
candidates.update(_pose_key_variants(record.get("file_name")))
for key in candidates:
pose = pose_lookup.get((scene_id, key))
if pose is not None:
return pose
return None
def _rotation_distance_deg(reference_rotation, rotation, scene_id=None, ignore_sym=False, sym_axis='z'):
relative = reference_rotation.inv() * rotation
dist = float(relative.magnitude() * 180.0 / np.pi)
if ignore_sym and scene_id is not None and int(scene_id) <= 4:
vec = [0.0, 0.0, 0.0]
vec[{'x': 0, 'y': 1, 'z': 2}[sym_axis.lower()]] = np.pi
sym_rot = Rotation.from_rotvec(vec)
relative_sym = reference_rotation.inv() * (rotation * sym_rot)
dist_sym = float(relative_sym.magnitude() * 180.0 / np.pi)
dist = min(dist, dist_sym)
return dist
def _percentile_rank(values):
"""
Convert values to percentile ranks in [0, 1].
Lower values correspond to lower variation.
"""
values = np.asarray(values, dtype=float)
if len(values) == 0:
return np.array([])
order = np.argsort(values, kind="stable")
ranks = np.empty(len(values), dtype=float)
if len(values) == 1:
ranks[order] = 0.0
return ranks
ranks[order] = np.arange(len(values)) / (len(values) - 1)
return ranks
def export_variation_csv(records, pose_records, out_dir,
train_records=None, train_pose_records=None,
ignore_sym=False, sym_axis='y'):
"""
Compute per-image illumination and pose variation scores and export them
to a CSV file.
The CSV contains raw measurements, per-scene variation scores,
global variation scores, and percentile ranks.
If train_records / train_pose_records are given, the CSV additionally
contains the same deltas measured against the TRAIN data references
(per train scene and over the whole train set), plus percentile ranks.
"""
if PILImage is None:
print(" [SKIP] Pillow not available for illumination analysis.")
return
out_dir = Path(out_dir)
out_dir.mkdir(parents=True, exist_ok=True)
pose_lookup = _build_pose_lookup(pose_records)
rows = []
# ---------------------------------------------------------------
# Train reference statistics
# ---------------------------------------------------------------
use_train = bool(train_records) or bool(train_pose_records)
if use_train:
train_refs = _train_reference_stats(
train_records or [], train_pose_records or []
)
else:
train_refs = None
# ---------------------------------------------------------------
# Illumination measurements
# ---------------------------------------------------------------
scene_intensities = defaultdict(list)
all_intensities = []
for record in records:
image_path = Path(record.get("_abs_path", ""))
if not image_path.is_file():
continue
try:
image = np.asarray(PILImage.open(image_path).convert("L"))
mean_intensity = float(np.mean(image))
except Exception:
continue
scene_intensities[record["scene_id"]].append(mean_intensity)
all_intensities.append(mean_intensity)
scene_intensity_mean = {
scene_id: float(np.mean(values))
for scene_id, values in scene_intensities.items()
if values
}
global_intensity_mean = (
float(np.mean(all_intensities))
if all_intensities
else np.nan
)
# ---------------------------------------------------------------
# Pose measurements
# ---------------------------------------------------------------
scene_translations = defaultdict(list)
scene_rotations = defaultdict(list)
all_translations = []
all_rotations = []
matched_pose_count = 0
for record in records:
pose = _find_pose_for_record(record, pose_lookup)
if pose is None:
continue
translation = _pose_translation(pose)
rotation = _pose_rotation(pose)
if translation is not None:
scene_translations[record["scene_id"]].append(translation)
all_translations.append(translation)
if rotation is not None:
scene_rotations[record["scene_id"]].append(rotation)
all_rotations.append(rotation)
if translation is not None or rotation is not None:
matched_pose_count += 1
# Scene translation centroids.
scene_translation_centroids = {
scene_id: np.mean(values, axis=0)
for scene_id, values in scene_translations.items()
if values
}
# Global translation centroid.
global_translation_centroid = (
np.mean(all_translations, axis=0)
if all_translations
else None
)
# Scene mean rotations.
scene_rotation_means = {}
for scene_id, rotations in scene_rotations.items():
if rotations:
scene_rotation_means[scene_id] = (
Rotation.concatenate(rotations).mean()
)
# Global mean rotation.
global_rotation_mean = None
if all_rotations:
global_rotation_mean = (
Rotation.concatenate(all_rotations).mean()
)
# ---------------------------------------------------------------
# Compute one row per image
# ---------------------------------------------------------------
for record in records:
scene_id = record["scene_id"]
row = {
"scene_id": scene_id,
"image_id": record["image_id"],
"file_name": record["file_name"],
"classification": record.get("classification", ""),
"camera": record.get("camera", ""),
"box_type": record.get("box_type", ""),
}
# -----------------------------------------------------------
# Illumination
# -----------------------------------------------------------
image_path = Path(record.get("_abs_path", ""))
mean_intensity = np.nan
if image_path.is_file():
try:
image = np.asarray(
PILImage.open(image_path).convert("L")
)
mean_intensity = float(np.mean(image))
except Exception:
pass
row["mean_intensity"] = mean_intensity
if (
np.isfinite(mean_intensity)
and scene_id in scene_intensity_mean
):
row["illumination_variation_scene"] = abs(
mean_intensity - scene_intensity_mean[scene_id]
)
else:
row["illumination_variation_scene"] = np.nan
if np.isfinite(mean_intensity):
row["illumination_variation_global"] = abs(
mean_intensity - global_intensity_mean
)
else:
row["illumination_variation_global"] = np.nan
# -----------------------------------------------------------
# Pose
# -----------------------------------------------------------
pose = _find_pose_for_record(record, pose_lookup)
translation = None
rotation = None
if pose is not None:
translation = _pose_translation(pose)
rotation = _pose_rotation(pose)
if translation is not None:
row["tx"] = float(translation[0])
row["ty"] = float(translation[1])
row["tz"] = float(translation[2])
scene_centroid = scene_translation_centroids.get(scene_id)
if scene_centroid is not None:
row["translation_variation_scene_mm"] = float(
np.linalg.norm(translation - scene_centroid)
)
if global_translation_centroid is not None:
row["translation_variation_global_mm"] = float(
np.linalg.norm(
translation - global_translation_centroid
)
)
else:
row["tx"] = np.nan
row["ty"] = np.nan
row["tz"] = np.nan
row["translation_variation_scene_mm"] = np.nan
row["translation_variation_global_mm"] = np.nan
if rotation is not None:
scene_rotation = scene_rotation_means.get(scene_id)
if scene_rotation is not None:
row["rotation_variation_scene_deg"] = (
_rotation_distance_deg(
scene_rotation,
rotation,
scene_id=scene_id,
ignore_sym=ignore_sym,
sym_axis=sym_axis
)
)
if global_rotation_mean is not None:
row["rotation_variation_global_deg"] = (
_rotation_distance_deg(
global_rotation_mean,
rotation,
scene_id=scene_id,
ignore_sym=ignore_sym,
sym_axis=sym_axis
)
)
else:
row["rotation_variation_scene_deg"] = np.nan
row["rotation_variation_global_deg"] = np.nan
# -----------------------------------------------------------
# Deltas with respect to the TRAIN data
# -----------------------------------------------------------
if use_train:
# Illumination
ill_train_scene = np.nan
ill_train_global = np.nan
if np.isfinite(mean_intensity):
ref_scene_int = train_refs["scene_intensity_mean"].get(scene_id)
if ref_scene_int is not None:
ill_train_scene = abs(mean_intensity - ref_scene_int)
if train_refs["global_intensity_mean"] is not None:
ill_train_global = abs(
mean_intensity - train_refs["global_intensity_mean"]
)
# Translation
trans_train_scene = np.nan
trans_train_global = np.nan
if translation is not None:
ref_scene_t = train_refs["scene_translation_centroid"].get(scene_id)
if ref_scene_t is not None:
trans_train_scene = float(
np.linalg.norm(translation - ref_scene_t)
)
if train_refs["global_translation_centroid"] is not None:
trans_train_global = float(
np.linalg.norm(
translation - train_refs["global_translation_centroid"]
)
)
# Rotation
rot_train_scene = np.nan
rot_train_global = np.nan
if rotation is not None:
ref_scene_r = train_refs["scene_rotation_mean"].get(scene_id)
if ref_scene_r is not None:
rot_train_scene = _rotation_distance_deg(
ref_scene_r, rotation,
scene_id=scene_id,
ignore_sym=ignore_sym,
sym_axis=sym_axis
)
if train_refs["global_rotation_mean"] is not None:
rot_train_global = _rotation_distance_deg(
train_refs["global_rotation_mean"], rotation,
scene_id=scene_id,
ignore_sym=ignore_sym,
sym_axis=sym_axis
)
row["illumination_variation_train_scene"] = ill_train_scene
row["illumination_variation_train_global"] = ill_train_global
row["translation_variation_train_scene_mm"] = trans_train_scene
row["translation_variation_train_global_mm"] = trans_train_global
row["rotation_variation_train_scene_deg"] = rot_train_scene
row["rotation_variation_train_global_deg"] = rot_train_global
rows.append(row)
# ---------------------------------------------------------------
# Percentile ranks
# ---------------------------------------------------------------
score_columns = [
"illumination_variation_scene",
"illumination_variation_global",
"translation_variation_scene_mm",
"translation_variation_global_mm",
"rotation_variation_scene_deg",
"rotation_variation_global_deg",
]
if use_train:
score_columns += [
"illumination_variation_train_scene",
"illumination_variation_train_global",
"translation_variation_train_scene_mm",
"translation_variation_train_global_mm",
"rotation_variation_train_scene_deg",
"rotation_variation_train_global_deg",
]
for column in score_columns:
valid = np.isfinite(
np.asarray([row[column] for row in rows], dtype=float)
)
values = np.asarray(
[row[column] for row in rows],
dtype=float,
)
ranks = np.full(len(rows), np.nan)
if np.any(valid):
ranks[valid] = _percentile_rank(values[valid])
rank_column = f"{column}_percentile"
for row, rank in zip(rows, ranks):
row[rank_column] = rank
# ---------------------------------------------------------------
# Per-scene percentile ranks
# ---------------------------------------------------------------
scene_score_columns = [
"illumination_variation_scene",
"translation_variation_scene_mm",
"rotation_variation_scene_deg",
]
if use_train:
scene_score_columns += [
"illumination_variation_train_scene",
"translation_variation_train_scene_mm",
"rotation_variation_train_scene_deg",
]
for score_column in scene_score_columns:
for scene_id in sorted(
set(row["scene_id"] for row in rows)
):
indices = [
i
for i, row in enumerate(rows)
if row["scene_id"] == scene_id
and np.isfinite(row[score_column])
]
if not indices:
continue
values = np.asarray(
[rows[i][score_column] for i in indices],
dtype=float,
)
ranks = _percentile_rank(values)
for i, rank in zip(indices, ranks):
rows[i][f"{score_column}_percentile"] = rank
# ---------------------------------------------------------------
# Sort by scene and then by each individual variation score.
# The CSV itself is sorted by scene and illumination variation.
# The rank columns allow sorting externally by any other factor.
# ---------------------------------------------------------------
rows.sort(
key=lambda row: (
str(row["scene_id"]),
np.inf
if not np.isfinite(row["illumination_variation_scene"])
else row["illumination_variation_scene"],
)
)
if not rows:
print(" [SKIP] No image measurements could be generated.")
return
import csv
csv_path = out_dir / "image_variation_scores.csv"
fieldnames = list(rows[0].keys())
with open(csv_path, "w", newline="") as f:
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(rows)
print(f" Saved: {csv_path}")
print(f" Images in CSV: {len(rows)}")
print(f" Images with matched poses: {matched_pose_count}")
# ---------------------------------------------------------------------------
# Train vs. test mean deltas (terminal output, Test minus Train)
# ---------------------------------------------------------------------------
def print_intensity_stat_deltas(test_stats, train_stats):
"""Delta of the global pixel-mean intensity (Test minus Train)."""
if not test_stats or not train_stats:
print(" [SKIP] Missing intensity statistics for train/test delta.")
return
print("\nIntensity Mean Delta (Test minus Train):")
print(f" Train mean: {train_stats['mean']:.2f}, "
f"Test mean: {test_stats['mean']:.2f}, "
f"Delta: {test_stats['mean'] - train_stats['mean']:+.2f}")
def print_6dof_stat_deltas(test_result, train_result):
"""
Delta of the translation means and of the Euler XYZ rotation means
(Test minus Train). Inputs are the tuples returned by print_6dof_stats.
"""
if test_result is None or train_result is None:
print(" [SKIP] Missing 6DOF statistics for train/test delta.")
return
t_mean_test, _, r_mean_test, _ = test_result
t_mean_train, _, r_mean_train, _ = train_result
dt = t_mean_test - t_mean_train
dr = r_mean_test - r_mean_train
print("\n6DOF Mean Delta (Test minus Train):")
print("Translation [mm]:")
print(f" X: {dt[0]:+.3f}")
print(f" Y: {dt[1]:+.3f}")
print(f" Z: {dt[2]:+.3f}")
print(f" Euclidean norm: {np.linalg.norm(dt):.3f}")
print("Rotation (Euler XYZ) [degrees]:")
print(f" RX: {dr[0]:+.3f}")
print(f" RY: {dr[1]:+.3f}")
print(f" RZ: {dr[2]:+.3f}")
def print_train_test_mean_deltas(records, pose_records, train_records, train_pose_records, ignore_sym=False, sym_axis='z'):
"""
Global and per-scene deltas between the test and train mean values
(Test minus Train): mean image intensity, translation centroid, and the
geodesic angle between the mean rotations.
"""
if not train_records and not train_pose_records:
print(" [SKIP] No train data available for train/test deltas.")
return
test_refs = _train_reference_stats(records, pose_records)
train_refs = _train_reference_stats(train_records, train_pose_records)
print("\nTrain vs. Test Mean Deltas (Test minus Train):")
# ------------------------------------------------------------------
# Illumination
# ------------------------------------------------------------------
print("\n Illumination (mean image intensity):")
test_g = test_refs["global_intensity_mean"]
train_g = train_refs["global_intensity_mean"]
if test_g is not None and train_g is not None:
print(f" Global: Train {train_g:.2f}, Test {test_g:.2f}, "
f"Delta {test_g - train_g:+.2f}")
common = sorted(set(test_refs["scene_intensity_mean"])
& set(train_refs["scene_intensity_mean"]))
for sc in common:
tr = train_refs["scene_intensity_mean"][sc]
te = test_refs["scene_intensity_mean"][sc]
print(f" Scene {sc}: Train {tr:.2f}, Test {te:.2f}, Delta {te - tr:+.2f}")
# ------------------------------------------------------------------
# Translation
# ------------------------------------------------------------------
print("\n Translation centroid [mm]:")
test_c = test_refs["global_translation_centroid"]
train_c = train_refs["global_translation_centroid"]
if test_c is not None and train_c is not None:
d = test_c - train_c
print(f" Global: Delta X {d[0]:+.1f}, Y {d[1]:+.1f}, Z {d[2]:+.1f}, "
f"|Delta| {np.linalg.norm(d):.1f}")
common = sorted(set(test_refs["scene_translation_centroid"])
& set(train_refs["scene_translation_centroid"]))
for sc in common:
d = (test_refs["scene_translation_centroid"][sc]
- train_refs["scene_translation_centroid"][sc])
print(f" Scene {sc}: Delta X {d[0]:+.1f}, Y {d[1]:+.1f}, Z {d[2]:+.1f}, "
f"|Delta| {np.linalg.norm(d):.1f}")
# ------------------------------------------------------------------
# Rotation
# ------------------------------------------------------------------
print("\n Rotation (geodesic angle between mean rotations) [deg]:")
test_r = test_refs["global_rotation_mean"]
train_r = train_refs["global_rotation_mean"]
if test_r is not None and train_r is not None:
print(f" Global: {_rotation_distance_deg(train_r, test_r, scene_id=sc, ignore_sym=ignore_sym, sym_axis=sym_axis):.2f}")
common = sorted(set(test_refs["scene_rotation_mean"]) & set(train_refs["scene_rotation_mean"]))
for sc in common:
ang = _rotation_distance_deg(train_refs["scene_rotation_mean"][sc],
test_refs["scene_rotation_mean"][sc],
scene_id=sc, ignore_sym=ignore_sym, sym_axis=sym_axis)
print(f" Scene {sc}: {ang:.2f}")
def fig_pose_3d_train_vs_test_hover(
pose_records,
train_pose_records,
out_dir=None,
cam_properties=None,
voxel_size=135,
sphere_coverage=100.0,
show_points=False,
show_vectors=True,
show_ellipsoids=True,
):
if not pose_records and not train_pose_records:
print(" [SKIP] No pose data found for train/test comparison.")
return
sets = [
("Test", pose_records, "#fde725"),
("Train", train_pose_records, "#20a486"),
]
rc = {
"font.size": 14,
"axes.titlesize": 16,
"axes.labelsize": 14,
"legend.fontsize": 12,
}
def get_image_metadata(p):
"""
Extract the image name and path from a pose record.
Add keys here if your dataset uses different field names.
"""
# Common path keys.
path_keys = (
"image_path",
"abs_path",
"absolute_path",
"file_path",
"filepath",
"path",
"image",
)
# Common image-name keys.
name_keys = (
"image_name",
"filename",
"file_name",
"name",
)
image_path = None
image_name = None
for key in path_keys:
value = p.get(key)
if isinstance(value, (str, os.PathLike)):
image_path = os.fspath(value)
break
for key in name_keys:
value = p.get(key)
if isinstance(value, (str, os.PathLike)):
image_name = os.fspath(value)
break
# Derive the image name from the path when necessary.
if image_name is None and image_path is not None:
image_name = os.path.basename(image_path)
if image_name is None:
image_name = "Unknown"
if image_path is None:
image_path = "Unknown"
return image_name, image_path
with plt.rc_context(rc):
fig = plt.figure(figsize=(12, 9))
ax = fig.add_subplot(111, projection="3d")
ax.set_facecolor("white")
ax.xaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))
ax.yaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))
ax.zaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))
length = 100.0
alpha_val = 0.4
all_x = [0.0]
all_y = [0.0]
all_z = [0.0]
sphere_proxies = []
point_proxies = []
# Coordinates and metadata for points that survive voxel filtering.
scatter_x = []
scatter_y = []
scatter_z = []
scatter_c = []
scatter_metadata = []
for split_name, poses, color in sets:
if not poses:
continue
all_translations = []
filtered_translations = []
# Prevent multiple points from occupying the same voxel
# within the same split.
occupied_voxels = set()
for p in poses:
t = _pose_translation(p)
if t is None:
continue
t = np.asarray(t, dtype=float).reshape(-1)
if t.size != 3 or not np.all(np.isfinite(t)):
continue
all_translations.append(t)
# Apply voxel filtering.
if voxel_size is not None and voxel_size > 0:
voxel_idx = (
int(np.floor(t[0] / voxel_size)),
int(np.floor(t[1] / voxel_size)),
int(np.floor(t[2] / voxel_size)),
)
if voxel_idx in occupied_voxels:
continue
occupied_voxels.add(voxel_idx)
filtered_translations.append(t)
# Store coordinates and metadata together.
# This ensures that hover information corresponds
# to the exact point retained by voxel filtering.
if show_points:
image_name, image_path = get_image_metadata(p)
scatter_x.append(float(t[0]))
scatter_y.append(float(t[1]))
scatter_z.append(float(t[2]))
scatter_c.append(color)
scatter_metadata.append({
"name": image_name,
"path": image_path,
"set": split_name,
"translation": t.copy(),
})
# Draw rotation vectors for retained poses.
if show_vectors and p.get("R") is not None:
R = np.asarray(
p["R"], dtype=float
).reshape(3, 3)
for i, axis_color in enumerate(["r", "g", "b"]):
ax.quiver(
t[0],
t[1],
t[2],
R[0, i] * length,
R[1, i] * length,
R[2, i] * length,
color=axis_color,
alpha=alpha_val,
)
if not all_translations:
continue
t_arr_all = np.asarray(all_translations)
t_arr_filtered = np.asarray(filtered_translations)
# Legend entry for each split.
if show_points and len(t_arr_filtered) > 0:
point_proxies.append(
Line2D(
[0],
[0],
marker="o",
color="w",
markerfacecolor=color,
markersize=6,
label=f"{split_name} translations",
)
)
center = t_arr_all.mean(axis=0)
if show_ellipsoids:
dists = np.linalg.norm(
t_arr_all - center,
axis=1,
)
threshold = np.percentile(
dists,
sphere_coverage,
)
core_points = t_arr_all[dists <= threshold]
# Compute the convex hull when enough points exist.
if len(core_points) >= 4:
try:
hull = ConvexHull(core_points)
faces = [
core_points[simplex]
for simplex in hull.simplices
]
poly = Poly3DCollection(
faces,
alpha=0.2,
facecolors=color,
linewidths=0,
shade=True,
)
ax.add_collection3d(poly)
except QhullError:
# Degenerate point configurations cannot
# define a 3D convex hull.
pass
sphere_proxies.append(
Patch(
facecolor=color,
edgecolor=color,
alpha=0.3,
label=f"{split_name} convex hull",
)
)
if len(core_points) > 0:
all_x.extend([
core_points[:, 0].min(),
core_points[:, 0].max(),
])
all_y.extend([
core_points[:, 1].min(),
core_points[:, 1].max(),
])
all_z.extend([
core_points[:, 2].min(),
core_points[:, 2].max(),
])
else:
all_x.extend(t_arr_filtered[:, 0])
all_y.extend(t_arr_filtered[:, 1])
all_z.extend(t_arr_filtered[:, 2])
# ---------------------------------------------------------
# Scatter plot and interactive hover annotations.
# ---------------------------------------------------------
if show_points and scatter_x:
scatter = ax.scatter(
scatter_x,
scatter_y,
scatter_z,
s=12,
c=scatter_c,
alpha=1.0,
depthshade=False,
picker=True,
)
# Create the annotation once and update it on mouse movement.
annot = ax.annotate(
"",
xy=(0, 0),
xytext=(15, 15),
textcoords="offset points",
bbox={
"boxstyle": "round,pad=0.5",
"fc": "white",
"ec": "gray",
"alpha": 0.95,
},
arrowprops={
"arrowstyle": "->",
"color": "gray",
},
zorder=100,
)
annot.set_visible(False)
# Store the current hovered point to avoid unnecessary redraws.
hover_state = {"index": None}
def on_move(event):
if event.inaxes != ax or event.x is None or event.y is None:
if annot.get_visible():
annot.set_visible(False)
hover_state["index"] = None
fig.canvas.draw_idle()
return
# Project the 3D coordinates into the current 2D view.
xyz = np.column_stack((
scatter_x,
scatter_y,
scatter_z,
))
projected_x, projected_y, projected_z = (
proj3d.proj_transform(
xyz[:, 0],
xyz[:, 1],
xyz[:, 2],
ax.get_proj(),
)
)
# Convert projected coordinates to display pixels.
display_points = ax.transData.transform(
np.column_stack((
projected_x,
projected_y,
))
)
mouse_position = np.array([
event.x,
event.y,
])
distances = np.linalg.norm(
display_points - mouse_position,
axis=1,
)
# Find the nearest projected point.
idx = int(np.argmin(distances))
# Hover radius in screen pixels.
hover_radius = 12
if distances[idx] > hover_radius:
if annot.get_visible():
annot.set_visible(False)
hover_state["index"] = None
fig.canvas.draw_idle()
return
# Do not redraw if the mouse remains over the same point.
if (
hover_state["index"] == idx
and annot.get_visible()
):
return
metadata = scatter_metadata[idx]
image_name = metadata["name"]
image_path = metadata["path"]
split_name = metadata["set"]
translation = metadata["translation"]
# Position the annotation at the projected point.
annot.xy = (
projected_x[idx],
projected_y[idx],
)
annot.set_text(
f"Image: {image_name}\n"
f"Path: {image_path}\n"
f"Split: {split_name}\n"
f"X: {translation[0]:.2f} mm\n"
f"Y: {translation[1]:.2f} mm\n"
f"Z: {translation[2]:.2f} mm"
)
annot.set_visible(True)
hover_state["index"] = idx
fig.canvas.draw_idle()
# Keep the callback registered for the lifetime of the figure.
fig.canvas.mpl_connect(
"motion_notify_event",
on_move,
)
# ---------------------------------------------------------
# Rotation-vector legend.
# ---------------------------------------------------------
if show_vectors:
ax.plot(
[], [], [],
color="r",
label="X Axis Rotation",
)
ax.plot(
[], [], [],
color="g",
label="Y Axis Rotation",
)
ax.plot(
[], [], [],
color="b",
label="Z Axis Rotation",
)
# ---------------------------------------------------------
# Camera frustums.
# ---------------------------------------------------------
if cam_properties:
cmap = plt.get_cmap("viridis")
safe_viridis_values = [0.1, 0.88]
for idx, (cam_id, props) in enumerate(
cam_properties.items()
):
K = np.asarray(
props["cam_K"]
).reshape(3, 3)
R = np.asarray(
props.get("R", np.eye(3))
).reshape(3, 3)
t = np.asarray(
props.get("t", np.zeros(3))
)
min_depth = props.get("min_depth", 300.0)
max_depth = props.get("max_depth", 1000.0)
draw_max_depth = props.get(
"draw_max_depth",
max_depth,
)
color_val = safe_viridis_values[
idx % len(safe_viridis_values)
]
cam_color = cmap(color_val)
pts = draw_working_frustum(
ax,
K,
R,
t,
min_depth,
max_depth,
draw_max_depth=draw_max_depth,
color=cam_color,
label=f"{cam_id} Frustum",
)
all_x.extend(pts[:, 0])
all_y.extend(pts[:, 1])
all_z.extend(pts[:, 2])
# ---------------------------------------------------------
# Axes and formatting.
# ---------------------------------------------------------
if all_x:
ax.set_xlim(min(all_x), max(all_x))
ax.set_ylim(min(all_y), max(all_y))
ax.set_zlim(min(all_z), max(all_z))
ax.set_xlabel("X Translation [mm]", labelpad=20)
ax.set_ylabel("Y Translation [mm]", labelpad=20)
ax.set_zlabel("Z Translation [mm]", labelpad=20)
ax.tick_params(axis="z", pad=10)
handles, labels = ax.get_legend_handles_labels()
handles = point_proxies + handles + sphere_proxies
ax.legend(
handles=handles,
loc="upper left",
bbox_to_anchor=(0.13, 0.78),
ncol=1,
)
ax.view_init(elev=8, azim=-79)
ax.invert_zaxis()
plt.tight_layout()
# Save the static PDF.
if out_dir:
out_path = (
out_dir
/ "translation_rotation_3d_train_vs_test_vectors.pdf"
)
plt.savefig(
out_path,
bbox_inches="tight",
)
print(f" Saved figure: {out_path}")
# Keep the figure open for interactive inspection.
plt.show(block=True)
def attach_image_metadata(pose_records, image_records, label=""):
"""Attach image names and paths to pose records."""
def normalize_stem(value):
stem = Path(str(value)).stem
# Handle filenames such as rgb_00001.png.
if stem.startswith("rgb_"):
stem = stem[4:]
# Normalize numeric IDs while preserving leading-zero equivalence.
if stem.isdigit():
stem = str(int(stem))
return stem
image_lookup = {}
for record in image_records:
scene_id = str(record.get("scene_id", "")).strip()
filename = record.get("file_name", "")
# Prefer the actual filename over the numeric image_id.
image_stem = normalize_stem(
filename if filename else record.get("image_id", "")
)
key = (scene_id, image_stem)
# Store a list so duplicate keys cannot silently overwrite records.
image_lookup.setdefault(key, []).append(record)
matched = 0
unmatched = []
for pose in pose_records:
scene_id = str(pose.get("scene_id", "")).strip()
pose_image_id = str(pose.get("image_id", ""))
image_stem = normalize_stem(pose_image_id)
key = (scene_id, image_stem)
candidates = image_lookup.get(key, [])
if len(candidates) == 1:
image_record = candidates[0]
pose["image_name"] = image_record.get(
"file_name",
pose_image_id,
)
pose["image_path"] = image_record.get(
"_abs_path",
image_record.get("file_name", "Unknown"),
)
matched += 1
else:
pose["image_name"] = pose_image_id
pose["image_path"] = (
"Not found" if not candidates else "Ambiguous match"
)
if len(unmatched) < 10:
unmatched.append({
"scene_id": scene_id,
"pose_image_id": pose_image_id,
"candidate_count": len(candidates),
})
print(
f" Matched {label}pose records to images: "
f"{matched}/{len(pose_records)}"
)
if unmatched:
print(f" Unmatched {label}pose examples:")
for item in unmatched:
print(f" {item}")
return pose_records
def main():
import matplotlib.ticker
parser = argparse.ArgumentParser(
description="Generate I-BADAS dataset statistics figures.")
parser.add_argument("--root", type=str, default="/media/rtx5090/i-badas/test",
help="Path to the dataset root (containing scene folders)")
parser.add_argument("--train_root", type=str, default="/media/rtx5090/i-badas/train",
help="Optional path to the train split (train/ or train/real/). "
"If given, train-referenced deltas are added to the "
"variation CSV.")
parser.add_argument("--out", type=str, default="/media/rtx5090/i-badas/scripts/figures",
help="Output directory for figures")
args = parser.parse_args()
root = Path(args.root)
out_dir = Path(args.out)
out_dir.mkdir(parents=True, exist_ok=True)
print("=" * 60)
print("I-BADAS Dataset Statistics Generator")
print("=" * 60)
plt.rcParams.update({
"font.family": "DejaVu Sans",
"axes.titlepad": 10,
"figure.dpi": 100,
"savefig.facecolor": "white",
})
# --- Load data ---
print("\n[1/4] Loading annotations...")
scenes, global_cats = load_all_scenes(root)
records, ann_records = aggregate(scenes)
inject_abs_paths(records, scenes)
inject_segmentation(ann_records, scenes)
pose_records = load_poses(scenes)
print(f" Total images : {len(records)}")
print(f" Total annots : {len(ann_records)}")
print(f" Total poses : {len(pose_records)}")
print(f" Categories : {sorted(global_cats.keys())}")
print("\n[1/4] Loading train data (reference for train-referenced deltas)...")
train_records, train_pose_records = load_train_data(args.train_root)
have_train = bool(train_records) or bool(train_pose_records)
print("\n[1/4] Exporting Variation Metrics")
export_variation_csv(records, pose_records, out_dir,
train_records=train_records,
train_pose_records=train_pose_records,
ignore_sym=True, sym_axis='y')
print("\n[3/4] Generating figures...")
# Paper selection
fig_class_per_scene(records, out_dir)
fig_mask_area_violin(ann_records, out_dir)
fig_intensity_histogram_global(records, out_dir,
train_records=train_records if train_records else None)
test_int_stats = calc_intensity_statistics_global(
records, label="Test" if have_train else "Dataset")
if have_train and train_records:
print()
train_int_stats = calc_intensity_statistics_global(train_records, label="Train")
print_intensity_stat_deltas(test_int_stats, train_int_stats)
fig_pose_3d_with_frames(pose_records, out_dir, my_cameras)
attach_image_metadata(
pose_records=pose_records,
image_records=records,
label="test ",
)
attach_image_metadata(
pose_records=train_pose_records,
image_records=train_records,
label="train ",
)
if have_train:
fig_pose_3d_train_vs_test(pose_records=pose_records, train_pose_records=train_pose_records,
task2_parity="both", out_dir=out_dir, cam_properties=my_cameras,
show_points=False,
show_vectors=True,
show_ellipsoids=True,
voxel_size=135)
# --- Interactive 3D pose visualization ---
print("\n[Interactive] Generating 3D train/test pose visualization...")
#fig_pose_3d_train_vs_test_hover(
# pose_records=pose_records,
# train_pose_records=train_pose_records,
# out_dir=out_dir,
# voxel_size=135,
# sphere_coverage=100.0,
# show_points=True,
# show_vectors=True,
# show_ellipsoids=True,
#)
test_6dof = print_6dof_stats(pose_records, label="Test" if have_train else None)
if have_train and train_pose_records:
train_6dof = print_6dof_stats(train_pose_records, label="Train")
print_6dof_stat_deltas(test_6dof, train_6dof)
fig_spatial_heatmap_ungrouped_common_legend(ann_records, out_dir)
calc_variability_metrics(records, pose_records,
label=" (Test)" if have_train else "", ignore_sym=True, sym_axis="y")
if have_train:
print()
calc_variability_metrics(train_records, train_pose_records, label=" (Train)", ignore_sym=True, sym_axis="y")
print_train_test_mean_deltas(records, pose_records,
train_records, train_pose_records, ignore_sym=True, sym_axis="y")
print("\n[4/4] Done.")
print(f" All figures written to: {out_dir.resolve()}")
print("=" * 60)
if __name__ == "__main__":
main()