minhy112's picture
Add files using upload-large-folder tool
1fe7814 verified
Raw
History Blame Contribute Delete
12.2 kB
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()