Post-Processing: Digging Bout & ROI Overlap Analysis#
This runnable notebook migrates docs/tutorials/Digging_Analysis_tutorial.ipynb into a clean, bug-fixed local workflow (fixing argument ordering in timestamp formatting and set-indexing in bout merging, with zero Colab or private-file dependencies).
What you will learn:
Convert smoothly between video frame numbers and
HH:MM:SS.mmmtimestamps.Detect digging bouts from head-in-ROI overlap and smoothed
rat–cupmask IoU.Merge nearby trigger frames into clean bout onset events with
reduce_bout_onsets.Evaluate detected bout onsets against optional ground-truth timestamps and export a clean CSV.
1. Timestamp & Bout-Merging Helpers#
import ast
from pathlib import Path
import cv2
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
try:
from pycocotools import mask as mask_util
except ImportError:
mask_util = None
WORK_DIR = Path("./annolid_digging_demo")
WORK_DIR.mkdir(parents=True, exist_ok=True)
FPS = 30.0
def convert_time_to_frame_number(time_stamp: str, fps: float = FPS) -> int:
"""Convert 'HH:MM:SS.mmm' timestamp string into an integer frame index."""
h_str, m_str, s_str = time_stamp.strip().split(":")
if "." in s_str:
sec_str, ms_str = s_str.split(".", 1)
ms = int(ms_str.ljust(3, "0")[:3])
else:
sec_str, ms = s_str, 0
total_seconds = int(h_str) * 3600 + int(m_str) * 60 + int(sec_str) + ms / 1000.0
return int(round(total_seconds * fps))
def convert_frame_number_to_time(frame_number: int, fps: float = FPS) -> str:
"""Convert a frame index into 'HH:MM:SS.mmm'."""
total_seconds = float(frame_number) / float(fps)
hours = int(total_seconds // 3600)
minutes = int((total_seconds % 3600) // 60)
seconds = int(total_seconds % 60)
milliseconds = int(round((total_seconds - int(total_seconds)) * 1000))
if milliseconds == 1000:
milliseconds = 0
seconds += 1
return f"{hours:02d}:{minutes:02d}:{seconds:02d}.{milliseconds:03d}"
def reduce_bout_onsets(frames, *, min_gap_frames: int = 30) -> list[int]:
"""Collapse contiguous/nearby positive frames into distinct bout-onset frame indices."""
ordered = sorted({int(x) for x in frames})
if not ordered:
return []
bouts = [ordered[0]]
prev = ordered[0]
for f in ordered[1:]:
if f - prev >= min_gap_frames:
bouts.append(f)
prev = f
return bouts
# Quick round-trip sanity check
sample_ts = convert_frame_number_to_time(135, fps=FPS)
print(f"Frame 135 @ {FPS:.0f} FPS -> {sample_ts} -> frame {convert_time_to_frame_number(sample_ts, fps=FPS)}")
Frame 135 @ 30 FPS -> 00:00:04.500 -> frame 135
2. Load Tracking CSV (or Generate a Realistic Digging Assay Demo)#
TRACKING_CSV_PATH = None # Set to your own tracking CSV path or keep None for synthetic demo
def encode_circle(h: int, w: int, cx: int, cy: int, radius: int) -> str:
canvas = np.zeros((h, w), dtype=np.uint8)
cv2.circle(canvas, (cx, cy), radius, 1, -1)
if mask_util is not None:
rle = mask_util.encode(np.asfortranarray(canvas))
rle["counts"] = rle["counts"].decode("ascii")
return repr(rle)
return repr({"size": [h, w], "bbox_fallback": [cx - radius, cy - radius, cx + radius, cy + radius]})
def mask_iou_rle(rle_a_str: str, rle_b_str: str) -> float:
a_obj = ast.literal_eval(rle_a_str)
b_obj = ast.literal_eval(rle_b_str)
if mask_util is not None and "counts" in a_obj and "counts" in b_obj:
a_rle = {"size": a_obj["size"], "counts": a_obj["counts"].encode("ascii")}
b_rle = {"size": b_obj["size"], "counts": b_obj["counts"].encode("ascii")}
return float(mask_util.iou([a_rle], [b_rle], [0])[0][0])
# Fallback bbox IoU
ax1, ay1, ax2, ay2 = a_obj["bbox_fallback"]
bx1, by1, bx2, by2 = b_obj["bbox_fallback"]
ix1, iy1, ix2, iy2 = max(ax1, bx1), max(ay1, by1), min(ax2, bx2), min(ay2, by2)
inter = max(0, ix2 - ix1) * max(0, iy2 - iy1)
area_a = max(0, ax2 - ax1) * max(0, ay2 - ay1)
area_b = max(0, bx2 - bx1) * max(0, by2 - by1)
union = area_a + area_b - inter
return float(inter / union) if union > 0 else 0.0
def build_demo_digging_csv(out_path: Path, *, num_frames: int = 360) -> tuple[Path, list[int]]:
"""Simulate a rodent approaching and digging in a cup across three distinct bouts."""
h, w = 240, 320
cup_cx, cup_cy, cup_r = 210, 125, 28
gt_bouts = [(55, 95), (165, 210), (275, 315)]
cup_rle = encode_circle(h, w, cup_cx, cup_cy, cup_r)
rows = []
for f in range(num_frames):
in_bout = any(s <= f <= e for s, e in gt_bouts)
if in_bout:
rat_cx = int(cup_cx - 10 + 4 * np.sin(f * 0.5))
rat_cy = int(cup_cy + 4 * np.cos(f * 0.4))
else:
rat_cx = int(95 + 25 * np.sin(f * 0.07))
rat_cy = int(125 + 35 * np.cos(f * 0.05))
rat_r = 26
rows.append(
{
"frame_number": f,
"x1": rat_cx - rat_r,
"y1": rat_cy - rat_r,
"x2": rat_cx + rat_r,
"y2": rat_cy + rat_r,
"instance_name": "rat",
"class_score": 0.98,
"segmentation": encode_circle(h, w, rat_cx, rat_cy, rat_r),
}
)
rows.append(
{
"frame_number": f,
"x1": cup_cx - cup_r,
"y1": cup_cy - cup_r,
"x2": cup_cx + cup_r,
"y2": cup_cy + cup_r,
"instance_name": "cup",
"class_score": 0.99,
"segmentation": cup_rle,
}
)
pd.DataFrame(rows).to_csv(out_path, index=False)
return out_path, [s for s, _ in gt_bouts]
if TRACKING_CSV_PATH:
csv_path = Path(TRACKING_CSV_PATH)
gt_onsets: list[int] = []
else:
csv_path, gt_onsets = build_demo_digging_csv(WORK_DIR / "digging_session_tracking.csv")
df = pd.read_csv(csv_path)
print(f"Loaded {len(df)} rows across {df['frame_number'].nunique()} frames from {csv_path.name}")
print("Ground-truth demo bout onsets (frames):", gt_onsets)
Loaded 720 rows across 360 frames from digging_session_tracking.csv
Ground-truth demo bout onsets (frames): [55, 165, 275]
3. Compute Frame-Wise Rat–Cup IoU, Detect Digging Onsets & Evaluate#
iou_rows = []
for frame_num, grp in df.groupby("frame_number", sort=True):
rat_rows = grp[grp["instance_name"] == "rat"]
cup_rows = grp[grp["instance_name"] == "cup"]
if rat_rows.empty or cup_rows.empty:
continue
iou_val = mask_iou_rle(rat_rows["segmentation"].iloc[0], cup_rows["segmentation"].iloc[0])
iou_rows.append({"frame_number": int(frame_num), "iou": iou_val})
iou_df = pd.DataFrame(iou_rows).sort_values("frame_number").reset_index(drop=True)
iou_df["smoothed_iou"] = iou_df["iou"].rolling(window=7, min_periods=1, center=True).mean()
# Identify positive overlap frames above IoU cutoff, then collapse into bout onsets
IOU_THRESHOLD = 0.15
positive_frames = iou_df.loc[iou_df["smoothed_iou"] >= IOU_THRESHOLD, "frame_number"].tolist()
predicted_onsets = reduce_bout_onsets(positive_frames, min_gap_frames=30)
pred_table = pd.DataFrame(
{
"Bout": range(1, len(predicted_onsets) + 1),
"Frame_number": predicted_onsets,
"Timestamp": [convert_frame_number_to_time(f, fps=FPS) for f in predicted_onsets],
}
)
out_csv = WORK_DIR / "predicted_digging_onsets.csv"
pred_table.to_csv(out_csv, index=False)
print("Detected digging bout onsets:")
print(pred_table.to_string(index=False))
if gt_onsets:
tolerance_frames = 10
matched = sum(
any(abs(p - g) <= tolerance_frames for p in predicted_onsets)
for g in gt_onsets
)
precision = matched / max(len(predicted_onsets), 1)
recall = matched / max(len(gt_onsets), 1)
print(f"\nEvaluation (±{tolerance_frames} frames): precision={precision:.2f}, recall={recall:.2f}")
print(f"Exported digging timestamps -> {out_csv.name}")
Detected digging bout onsets:
Bout Frame_number Timestamp
1 53 00:00:01.767
2 163 00:00:05.433
3 273 00:00:09.100
Evaluation (±10 frames): precision=1.00, recall=1.00
Exported digging timestamps -> predicted_digging_onsets.csv
4. Plot Smoothed Rat–Cup IoU & Detected Bout Onsets#
fig, ax = plt.subplots(figsize=(10.0, 3.6))
ax.plot(iou_df["frame_number"], iou_df["iou"], color="#94a3b8", alpha=0.55, linewidth=1.0, label="Raw IoU")
ax.plot(iou_df["frame_number"], iou_df["smoothed_iou"], color="#0d9488", linewidth=2.0, label="Smoothed IoU")
ax.axhline(IOU_THRESHOLD, color="#dc2626", linestyle="--", linewidth=1.1, label=f"Threshold ({IOU_THRESHOLD})")
for idx, f in enumerate(predicted_onsets):
ax.axvline(f, color="#2563eb", linestyle=":", linewidth=1.6, label="Predicted onset" if idx == 0 else None)
for idx, f in enumerate(gt_onsets):
ax.scatter([f], [iou_df["smoothed_iou"].max() * 1.04], marker="v", color="#16a34a", s=55, label="Ground-truth onset" if idx == 0 else None)
ax.set_title("Rat–Cup Mask IoU & Digging Bout Onset Detection")
ax.set_xlabel("Frame number")
ax.set_ylabel("Mask IoU")
ax.legend(fontsize=8, loc="upper right")
ax.grid(alpha=0.25)
plt.tight_layout()
plt.show()