File size: 12,157 Bytes
ccc6a60 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 | from __future__ import annotations
import argparse
import shutil
from pathlib import Path
import cv2
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
MODEL_LABELS = {
"mcfd_rgb_cnn": "RGB-CNN",
"mcfd_rgb_cnn_lstm": "RGB-CNN-LSTM",
"mcfd_rgb_resnet18_lstm": "RGB-ResNet18-LSTM",
"mcfd_pose_lstm": "Pose-LSTM",
"mcfd_pose_gru_attention": "Pose-GRU-Attn",
"mcfd_pose_tcn_attention": "Proposed",
"mcfd_ablation_no_velocity": "w/o velocity",
"mcfd_ablation_no_confidence": "w/o confidence",
}
SKELETON = [
(5, 7),
(7, 9),
(6, 8),
(8, 10),
(5, 6),
(5, 11),
(6, 12),
(11, 12),
(11, 13),
(13, 15),
(12, 14),
(14, 16),
(0, 1),
(0, 2),
(1, 3),
(2, 4),
]
def ensure_dirs(*dirs: Path) -> None:
for d in dirs:
d.mkdir(parents=True, exist_ok=True)
def savefig(path: Path, paper_dir: Path | None = None) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
plt.tight_layout()
plt.savefig(path, dpi=300, bbox_inches="tight")
plt.close()
if paper_dir is not None:
paper_dir.mkdir(parents=True, exist_ok=True)
shutil.copy2(path, paper_dir / path.name)
def plot_main_results(results_csv: Path, out_dir: Path, paper_dir: Path) -> None:
df = pd.read_csv(results_csv)
order = [
"mcfd_rgb_cnn",
"mcfd_rgb_cnn_lstm",
"mcfd_rgb_resnet18_lstm",
"mcfd_pose_lstm",
"mcfd_pose_gru_attention",
"mcfd_pose_tcn_attention",
]
df = df[df["run"].isin(order)].copy()
df["label"] = pd.Categorical(df["run"].map(MODEL_LABELS), [MODEL_LABELS[r] for r in order], ordered=True)
df = df.sort_values("label")
metrics = ["test_accuracy", "test_precision", "test_recall", "test_f1"]
names = ["Accuracy", "Precision", "Recall", "F1"]
x = np.arange(len(df))
width = 0.19
colors = ["#4C78A8", "#F58518", "#54A24B", "#B279A2"]
plt.figure(figsize=(8.2, 4.2))
for i, (metric, name) in enumerate(zip(metrics, names, strict=True)):
plt.bar(x + (i - 1.5) * width, df[metric], width, label=name, color=colors[i])
plt.xticks(x, df["label"], rotation=20, ha="right")
plt.ylim(0, 1.05)
plt.ylabel("Score")
plt.legend(ncol=4, loc="upper center", bbox_to_anchor=(0.5, 1.18), frameon=False)
plt.grid(axis="y", alpha=0.25)
savefig(out_dir / "main_results_metrics.png", paper_dir)
plt.figure(figsize=(7.2, 3.8))
bars = plt.bar(df["label"], df["test_f1"], color=["#9E9E9E", "#777777", "#4C78A8", "#54A24B", "#B279A2"])
plt.ylim(0, 0.6)
plt.ylabel("F1-score")
plt.xticks(rotation=20, ha="right")
plt.grid(axis="y", alpha=0.25)
for bar in bars:
h = bar.get_height()
plt.text(bar.get_x() + bar.get_width() / 2, h + 0.012, f"{h:.3f}", ha="center", va="bottom", fontsize=9)
savefig(out_dir / "main_results_f1.png", paper_dir)
def plot_ablation(results_csv: Path, out_dir: Path, paper_dir: Path) -> None:
df = pd.read_csv(results_csv)
order = ["mcfd_ablation_no_velocity", "mcfd_ablation_no_confidence", "mcfd_pose_tcn_attention"]
df = df[df["run"].isin(order)].copy()
df["label"] = pd.Categorical(df["run"].map(MODEL_LABELS), [MODEL_LABELS[r] for r in order], ordered=True)
df = df.sort_values("label")
metrics = ["test_accuracy", "test_precision", "test_f1"]
names = ["Accuracy", "Precision", "F1"]
x = np.arange(len(df))
width = 0.25
plt.figure(figsize=(6.6, 3.8))
for i, (metric, name, color) in enumerate(zip(metrics, names, ["#4C78A8", "#F58518", "#B279A2"], strict=True)):
plt.bar(x + (i - 1) * width, df[metric], width, label=name, color=color)
plt.xticks(x, df["label"], rotation=15, ha="right")
plt.ylim(0, 0.75)
plt.ylabel("Score")
plt.legend(ncol=3, loc="upper center", bbox_to_anchor=(0.5, 1.17), frameon=False)
plt.grid(axis="y", alpha=0.25)
savefig(out_dir / "ablation_metrics.png", paper_dir)
def plot_robustness(robustness_csv: Path, out_dir: Path, paper_dir: Path) -> None:
df = pd.read_csv(robustness_csv)
frame = df[df["setting"].str.startswith("frame_drop") | (df["setting"] == "clean")].copy()
frame["drop_ratio"] = frame["setting"].map(
{"clean": 0, "frame_drop_10": 10, "frame_drop_20": 20, "frame_drop_30": 30}
)
order = ["mcfd_pose_lstm", "mcfd_pose_gru_attention", "mcfd_pose_tcn_attention"]
colors = {"mcfd_pose_lstm": "#4C78A8", "mcfd_pose_gru_attention": "#54A24B", "mcfd_pose_tcn_attention": "#B279A2"}
plt.figure(figsize=(6.6, 3.8))
for run in order:
part = frame[frame["run"] == run].sort_values("drop_ratio")
plt.plot(part["drop_ratio"], part["f1"], marker="o", linewidth=2, label=MODEL_LABELS[run], color=colors[run])
plt.xlabel("Frame drop ratio (%)")
plt.ylabel("F1-score")
plt.ylim(0.48, 0.54)
plt.xticks([0, 10, 20, 30])
plt.legend(frameon=False)
plt.grid(alpha=0.25)
savefig(out_dir / "robustness_frame_drop_f1.png", paper_dir)
noise = df[df["setting"].str.startswith("keypoint_noise") | (df["setting"] == "clean")].copy()
noise["noise_px"] = noise["setting"].map(
{"clean": 0, "keypoint_noise_px_2": 2, "keypoint_noise_px_5": 5, "keypoint_noise_px_10": 10}
)
plt.figure(figsize=(6.6, 3.8))
for run in order:
part = noise[noise["run"] == run].sort_values("noise_px")
plt.plot(part["noise_px"], part["f1"], marker="o", linewidth=2, label=MODEL_LABELS[run], color=colors[run])
plt.xlabel("Gaussian keypoint noise (px)")
plt.ylabel("F1-score")
plt.ylim(0.48, 0.54)
plt.xticks([0, 2, 5, 10])
plt.legend(frameon=False)
plt.grid(alpha=0.25)
savefig(out_dir / "robustness_keypoint_noise_f1.png", paper_dir)
def plot_confusion_matrices(results_csv: Path, out_dir: Path, paper_dir: Path) -> None:
df = pd.read_csv(results_csv)
for run in ["mcfd_rgb_cnn", "mcfd_rgb_resnet18_lstm", "mcfd_pose_lstm", "mcfd_pose_gru_attention", "mcfd_pose_tcn_attention"]:
row = df[df["run"] == run].iloc[0]
cm = np.array([[row["test_tn"], row["test_fp"]], [row["test_fn"], row["test_tp"]]], dtype=int)
plt.figure(figsize=(3.7, 3.4))
plt.imshow(cm, cmap="Blues")
plt.xticks([0, 1], ["ADL", "Fall"])
plt.yticks([0, 1], ["ADL", "Fall"])
plt.xlabel("Predicted")
plt.ylabel("True")
plt.title(MODEL_LABELS[run])
for y in range(2):
for x in range(2):
color = "white" if cm[y, x] > cm.max() * 0.55 else "black"
plt.text(x, y, str(cm[y, x]), ha="center", va="center", color=color, fontsize=12)
savefig(out_dir / f"confusion_{run}.png", paper_dir)
def draw_box_diagram(labels: list[str], title: str, path: Path, paper_dir: Path) -> None:
fig, ax = plt.subplots(figsize=(8.4, 1.8))
ax.set_axis_off()
n = len(labels)
box_w = 0.86 / n
y = 0.35
for i, label in enumerate(labels):
x = 0.05 + i * (0.9 / n)
rect = plt.Rectangle((x, y), box_w, 0.32, facecolor="#F7F7F7", edgecolor="#333333", linewidth=1.2)
ax.add_patch(rect)
ax.text(x + box_w / 2, y + 0.16, label, ha="center", va="center", fontsize=9)
if i < n - 1:
ax.annotate("", xy=(x + box_w + 0.025, y + 0.16), xytext=(x + box_w + 0.005, y + 0.16), arrowprops={"arrowstyle": "->", "lw": 1.2})
ax.text(0.5, 0.88, title, ha="center", va="center", fontsize=11, fontweight="bold")
savefig(path, paper_dir)
def draw_pose_overlay(frame: np.ndarray, pose: np.ndarray, conf_thr: float = 0.2) -> np.ndarray:
img = frame.copy()
for a, b in SKELETON:
if pose[a, 2] > conf_thr and pose[b, 2] > conf_thr:
p1 = tuple(np.round(pose[a, :2]).astype(int))
p2 = tuple(np.round(pose[b, :2]).astype(int))
cv2.line(img, p1, p2, (255, 190, 0), 2, cv2.LINE_AA)
for x, y, c in pose:
if c > conf_thr:
cv2.circle(img, (int(round(x)), int(round(y))), 3, (20, 220, 80), -1, cv2.LINE_AA)
return img
def make_contact_sheet(frames: np.ndarray, poses: np.ndarray, path: Path, title: str, paper_dir: Path) -> None:
idx = np.linspace(0, len(frames) - 1, 8).round().astype(int)
overlays = [draw_pose_overlay(frames[i], poses[i]) for i in idx]
h, w = overlays[0].shape[:2]
canvas = np.full((2 * h + 56, 4 * w, 3), 255, dtype=np.uint8)
cv2.putText(canvas, title, (12, 28), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (25, 25, 25), 2, cv2.LINE_AA)
for j, img in enumerate(overlays):
r = j // 4
c = j % 4
y0 = 44 + r * h
x0 = c * w
canvas[y0 : y0 + h, x0 : x0 + w] = img
path.parent.mkdir(parents=True, exist_ok=True)
cv2.imwrite(str(path), cv2.cvtColor(canvas, cv2.COLOR_RGB2BGR))
if paper_dir is not None:
paper_dir.mkdir(parents=True, exist_ok=True)
shutil.copy2(path, paper_dir / path.name)
def pose_aspect_score(pose: np.ndarray) -> float:
best = 0.0
for t in range(pose.shape[0]):
mask = pose[t, :, 2] > 0.2
if mask.sum() < 5:
continue
pts = pose[t, mask, :2]
wh = pts.max(axis=0) - pts.min(axis=0)
best = max(best, float(wh[0] / max(wh[1], 1.0)))
return best
def choose_pose_example(merged: pd.DataFrame, label: int) -> pd.Series:
candidates = merged[merged["label"] == label].copy()
scores = []
for _, row in candidates.iterrows():
pose = np.load(row["pose_path"])
quality = float((pose[..., 2] > 0.2).mean())
if label == 1:
scores.append(pose_aspect_score(pose) * max(quality, 0.05))
else:
scores.append(quality)
candidates["example_score"] = scores
return candidates.sort_values("example_score", ascending=False).iloc[0]
def plot_pose_examples(pose_manifest: Path, rgb_manifest: Path, out_dir: Path, paper_dir: Path) -> None:
pose_df = pd.read_csv(pose_manifest)
rgb_df = pd.read_csv(rgb_manifest)
merged = pose_df.merge(rgb_df[["video_id", "rgb_path"]], on="video_id", how="inner")
for label, name in [(1, "fall"), (0, "adl")]:
row = choose_pose_example(merged, label)
frames = np.load(row["rgb_path"])
poses = np.load(row["pose_path"])
scale_x = frames.shape[2] / 640.0
scale_y = frames.shape[1] / 480.0
poses = poses.copy()
poses[..., 0] *= scale_x
poses[..., 1] *= scale_y
make_contact_sheet(frames, poses, out_dir / f"pose_sequence_{name}.png", f"Pose overlay: {name.upper()} segment", paper_dir)
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--results", default="outputs/tables/mcfd_results.csv")
parser.add_argument("--robustness", default="outputs/tables/mcfd_robustness_summary.csv")
parser.add_argument("--pose-manifest", default="data/manifests/mcfd_pose_t32.csv")
parser.add_argument("--rgb-manifest", default="data/manifests/mcfd_rgb_t32.csv")
parser.add_argument("--out-dir", default="outputs/figures")
parser.add_argument("--paper-dir", default="paper/figures")
args = parser.parse_args()
out_dir = Path(args.out_dir)
paper_dir = Path(args.paper_dir)
ensure_dirs(out_dir, paper_dir)
plot_main_results(Path(args.results), out_dir, paper_dir)
plot_ablation(Path(args.results), out_dir, paper_dir)
plot_robustness(Path(args.robustness), out_dir, paper_dir)
plot_confusion_matrices(Path(args.results), out_dir, paper_dir)
draw_box_diagram(
["Input video", "Frame sampling", "Pose extraction", "Normalization", "Temporal model", "Fall prediction"],
"Overall Fall Detection Pipeline",
out_dir / "pipeline.png",
paper_dir,
)
draw_box_diagram(
["Keypoints", "Velocity", "TCN blocks", "Temporal attention", "Classifier"],
"Proposed Pose-TCN-Attention Architecture",
out_dir / "architecture.png",
paper_dir,
)
plot_pose_examples(Path(args.pose_manifest), Path(args.rgb_manifest), out_dir, paper_dir)
print(f"Wrote figures to {out_dir} and {paper_dir}")
if __name__ == "__main__":
main()
|