Dynamic object aware egomotion

From XuShuwenn/RedAct · View interactive version

Dynamic object aware egomotion is an AI agent skill from the GitHub repository XuShuwenn/RedAct. Analyze video files for camera motion (egomotion) and detect dynamic objects, outputting motion labels and binary masks.

How to use this skill

Skill file

Dynamic Object Aware Egomotion Detection

When to Use

Completion Rule

Treat the task as incomplete until both output files exist at the required paths:

Do not stop at environment exploration, package inspection, frame extraction, or a written summary. Use reconnaissance only to unblock execution, then run the analysis and save the artifacts.

If the environment or task specifies a required runtime/tool-call protocol or exact completion string, follow it exactly.

Treat protocol requirements as hard correctness constraints.

Mandatory workspace/protocol gate before creating files or acting:

Mandatory protocol gate before acting:

Output Files

  1. /root/pred_instructions.json - Frame intervals to motion labels
  2. /root/pred_dyn_masks.npz - Binary masks for dynamic objects

Important indexing and coverage rules:

Motion Labels

Valid labels: Stay, Dolly In, Dolly Out, Pan Left, Pan Right, Tilt Up, Tilt Down, Roll Left, Roll Right

Format:

{
  "0->1": ["Pan Right"]
}

Use interval keys over sampled-frame positions, not raw frame IDs. If sampled frames are [0, 10, 20, 30] in the source video, transitions are keyed as "0->1", "1->2", "2->3" — not "0->10", "10->20".

Treat motion predictions as labels for transitions between consecutive sampled frames, not labels for individual frames. If you have N sampled frames, there are N-1 adjacent transitions; a per-transition label at position i maps to interval "i->i+1" before any compression/merging. Do not assign a standalone motion label to frame 0 by itself.

When smoothing, voting, or merging per-transition motion labels, handle boundary transitions explicitly. Do not let neighbor-based smoothing erase or invent the first or last valid transition just because one side lacks context.

Stay is mutually exclusive with all active motion labels; do not emit Stay together with Pan, Tilt, Roll, or Dolly for the same interval.

Prefer the smallest plausible label set per interval. Treat motion prediction as selecting the single dominant camera-motion label by default unless the task specification explicitly permits multi-label intervals with clear visual evidence. After any smoothing, merging, or voting, re-enforce that if Stay is present, it is the only label for that interval.

When compressing consecutive sampled-frame motions into intervals, ensure coverage spans the full sampled sequence, including the final sampled frame. Example: if 22 sampled frames all share one motion label, use "0->21".

Do not use a reduced classifier that can only emit pan/tilt/stay. The task label space includes Dolly In, Dolly Out, Roll Left, and Roll Right.

Before writing JSON, verify that interval keys use sampled-frame index space and that every label is one of: Stay, Dolly In, Dolly Out, Pan Left, Pan Right, Tilt Up, Tilt Down, Roll Left, Roll Right.

Proven baseline for motion inference: estimate a global partial affine transform between consecutive sampled frames from tracked features (for example with goodFeaturesToTrack + calcOpticalFlowPyrLK + estimateAffinePartial2D), then map translation, scale, and rotation to the allowed motion labels.

Mask Format (CSR Sparse)

For frame i, store in NPZ:

Index mask entries by sampled-frame position.

Implementation guardrails:

```python

mask_u8 = (mask > 0).astype(np.uint8)

num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(mask_u8, connectivity=8)

assert mask_u8.dtype == np.uint8 and mask_u8.ndim == 2

```

Dynamic-object detection default: when the camera moves, estimate global inter-frame motion first, warp one frame into the other view, then threshold residual differences rather than relying on raw frame differencing.

CSR serialization hint: when writing keys without SciPy, derive indices and indptr from the binary mask row-by-row so indices, data, and indptr stay internally consistent even for empty rows or fully empty frames.

After saving the NPZ, run a quick programmatic validation that checks key presence, shared shape, and CSR consistency before finalizing.

Key Parameters

Required Workflow and Done Criteria

  1. At startup, check for any task-specific protocol constraints on tool calls or final signaling; protocol compliance is part of completion.
  2. After brief reconnaissance, switch to execution. If you catch yourself preparing a report before both artifacts exist, stop and resume the pipeline.
  3. Prefer one end-to-end pipeline/script that samples frames once and produces both deliverables from the same sampled-frame sequence; reuse shared decoding, tracking, and motion estimates so JSON intervals and NPZ mask indices stay aligned.

8a. Prefer a single saved script that reads metadata, freezes sample_ids, runs motion inference, generates masks, writes both artifacts, and then invokes a lightweight validator/check. This integrated pattern reduces cross-file indexing drift.

8b. Keep that single pipeline authoritative: derive sampled-frame count, sampled-index mapping, and frame shape once, then reuse those exact values for both JSON interval export and NPZ mask serialization instead of recomputing them in separate code paths.

  1. If a traceback identifies a concrete fix, inspect the surrounding code for the reported line/function, patch the exact failing line or call, verify the edit is present, then rerun.

9a. Make edits against exact observed source text only; do not use descriptive placeholders such as "fix boolean input", "remove unavailable import", or "adjust mask code" as patch targets.

9b. After a dependency, API, or OpenCV error, confirm the specific failing import/call site in the saved script, patch that concrete code, then rerun to verify the original error is gone.

9c. Before editing after a traceback, open the saved script and inspect the exact reported line plus nearby lines/functions. Edit against the observed file contents; do not apply placeholder or prose-described replacements without first reading the code on disk.

9d. Do not say you "fixed" or "patched" anything unless the transcript shows an actual edit command between the failing run and the rerun.

9e. Do not use placeholder patch targets such as remove unavailable import, fix boolean input, or adjust mask code.

9f. After editing, re-open, print, or diff the relevant snippet from the saved script so the transcript shows the concrete change before rerunning.

9g. If the same traceback appears after a claimed fix, stop patching by description. Re-open the saved script at the reported line/function, inspect the exact call and arguments, make a text-grounded edit, then verify the edited code before rerunning.

9h. If the failing path involved masks, dtypes, or OpenCV image-processing calls, add a targeted post-fix check on regenerated outputs: reload the NPZ and verify CSR lengths, key coverage, and binary-valued mask data rather than treating a clean rerun alone as proof.

  1. After any failed run, treat existing /root/pred_instructions.json and /root/pred_dyn_masks.npz as stale until a later successful run regenerates them.
  2. If transform estimation fails on some interval, handle that interval explicitly rather than silently skipping frames or leaving coverage gaps.
  3. Before writing outputs, run a spec-first validation pass independent of the generator: confirm JSON interval endpoints are sampled-frame indices, NPZ keys are f_0_* through f_{N-1}_* for the same sampled-frame sequence, and no raw source-frame numbers appear in either file.
  4. Explicitly compare counts before finalizing: if there are N sampled frames, the NPZ must contain mask entries for all indices 0..N-1, and the motion JSON must cover the same sampled-frame index sequence through N-1.
  5. Treat boundary indices as mandatory checks: verify frame 0 and the final sampled frame are both represented in the exported outputs.
  6. Treat file-format validation as necessary but insufficient: inspect representative sampled frames or clips, confirm motion labels match visible camera motion, and confirm masks isolate moving objects rather than camera-motion residuals.
  7. Keep the script or command sequence that produced the outputs until final semantic validation and any protocol-specific completion handoff are complete; do not delete debugging artifacts immediately after the first successful run.
  1. Before the first real command, make a short preflight checklist covering: exact required tool-call syntax, exact completion string, intended interpreter, planned dependency imports, and the exact artifact paths/schema you must produce.

17a. Include allowed read/write locations in that preflight checklist. Confirm where intermediates may be created before saving scripts, validators, logs, or caches.

17b. If a strict action schema is specified, write down one literal example of the required wrapper before issuing the first action, then mirror that format exactly for every subsequent tool call.

17c. Include in that preflight the exact allowed tool names/casing, planned dependency import checks, and the input media properties you will rely on (at minimum width, height, FPS, and frame count).

17d. Before the first implementation edit, explicitly reconcile the live task instructions with this skill: verify the exact artifact paths, schema/indexing rules, and required final completion signal from the task/environment itself.

17e. Quickly check for task-local guidance already present in the environment, then stop reconnaissance; do not spend multiple turns re-reading docs or inventorying the environment once the contract is known.

17f. In that preflight, write down the exact next executable action in the mandated schema, and on the very next turn send that real command rather than a readiness summary or prose handoff.

  1. After reconnaissance confirms the video path and usable libraries, execute an end-to-end run immediately; do not end the turn with a readiness report, exploration report, or implementation plan.
  2. Every tool invocation must contain a concrete executable command or literal script body. Do not send placeholders such as run the pipeline, install required Python packages, check outputs, or inspect NPZ keys.

19a. Treat natural-language intent strings as invalid tool input. Replace them with the exact command you will execute, including executable name, script path, flags, redirections, and concrete file paths.

19b. Do not use abbreviated or ellipsis-style stand-ins such as ffprobe ..., python ..., inspect the generated JSON file, or remove temporary scripts.

19c. The command text itself must perform the claimed check. Do not issue descriptive no-op commands such as python3 -c "validated the JSON and NPZ outputs"; include real code that loads the artifacts and asserts the required properties.

19d. If the environment exposes only one permitted execution tool/schema, route all command execution through that exact interface rather than mixing tool-call styles.

  1. If you create a script via heredoc or redirection, write the full executable code into the file; do not substitute placeholder text or a prose summary for code.

20a. The same rule applies to heredocs, JSON/config/data files, and scripted actions: write the actual executable or parseable content, not descriptive text.

20b. After any nontrivial write/edit, reopen the file around the changed lines or parse it directly to confirm the exact code/data now on disk before rerunning.

  1. After writing or heavily editing a script, run a lightweight validation before the first full execution: inspect the saved file and/or run python3 -m py_compile <script> (or the confirmed interpreter equivalent), then fix any reported syntax errors before the end-to-end run.

21a. If python fails or is unavailable, switch immediately to the confirmed interpreter (typically python3) instead of retrying with the missing command.

21b. Before the first full run, smoke-test fragile assumptions: confirm the intended interpreter works, confirm each non-stdlib import actually imports, confirm OpenCV calls use the installed signature (for example calcOpticalFlowPyrLK(..., prev_pts, None, ...)), and confirm mask-processing inputs reaching OpenCV are uint8 single-channel arrays rather than bool.

21c. If any dependency or API smoke test fails, immediately revise the pipeline toward the documented NumPy/OpenCV-only path and rerun the smoke test before attempting the end-to-end job.

  1. Smoke-test fragile APIs with tiny inputs before the first full run. In particular, verify the exact OpenCV signatures you will use and confirm connected-components/morphology inputs are uint8, not bool.
  2. If a planned dependency import fails or an API smoke test fails, revise the implementation immediately instead of launching the full script and hoping later stages will work.
  3. Do not say a fix was applied unless the transcript shows an actual code edit between the failing run and the rerun.
  4. After any substantial run, confirm completion explicitly before trusting outputs: check normal process termination, and if stdout is truncated, cut off, or ambiguous, rerun with a quieter command, redirected log, or targeted post-run check until completion is unambiguous.

25a. Treat long or noisy pipeline stdout as inconclusive by default. If output stops mid-line, is truncated by the interface, or lacks a clear shell exit signal, do not proceed to artifact validation until you have confirmed the process ended successfully.

25b. If a run exits nonzero or output is truncated before the exception is visible, first rerun to capture the full traceback before editing code.

25c. Treat any verification command that exits nonzero, raises an exception, or depends on a missing import as failed/incomplete verification. Do not summarize that check as passed unless a later successful command explicitly covers the same requirement.

25d. If a helper validator fails because of an unnecessary dependency, replace it with a dependency-light parser/check that verifies the same requirement and base your summary only on the successful replacement check.

25e. After an edit, claim only the exact change the transcript proves; do not claim the whole bug is fixed until a rerun confirms the original failure is gone.

  1. After any traceback-driven fix and rerun, treat the task as unfinished until you revalidate both artifacts end-to-end; file existence or a helper validator's summary line is not enough.
  2. If you change JSON interval indexing, mask key naming, sampling logic, or any shared schema assumption, regenerate the outputs and revalidate both /root/pred_instructions.json and /root/pred_dyn_masks.npz; never inspect only the artifact that first exposed the issue.
  3. Reconcile indexing semantics across the whole run before finalizing: metadata-derived sampled-frame IDs, per-transition motion analysis, merged JSON intervals, and NPZ frame keys must all refer to the same declared sampled-frame output coordinate system.
  4. If validation output is structurally green but semantically surprising — for example unexpectedly few intervals, suspiciously dense masks, or a sudden switch between raw frame IDs and sampled indices — reopen the written files and inspect the mapping/merge logic before declaring success.
  5. Do not delete the main analysis script or validator before final semantic validation and any required completion handoff are finished.
  6. Immediately before the final response, perform one last contract audit: required files exist and were regenerated successfully in this run, validation is complete, every tool call followed the mandated schema, and the final response matches the exact required completion token/string if one is specified.
  7. If you used a todo list or multi-step plan earlier in the run, revisit it during the final audit and confirm no core task items remain pending. An unfinished plan means the task is unfinished.
  8. If you change indexing, interval semantics, mask key naming, or any shared output schema, rerun the generator and then re-open and validate both /root/pred_instructions.json and /root/pred_dyn_masks.npz in the same post-fix cycle; do not stop after checking only the artifact that first revealed the bug.
  9. Record concise run metadata after generation and before finalizing: source video properties, sampled-frame count N, and resulting motion-interval count. Use these counts to sanity-check that JSON coverage and NPZ frame entries align with the same sampled sequence.
  10. Do not delete the main pipeline script, validator, logs, or other generated diagnostic artifacts during wrap-up unless the task explicitly instructs you to remove them.
  11. If the environment specifies an exact termination token/string, the final response must be that exact string and nothing else; do not append explanations, file summaries, or confidence statements.

Required Workflow and Done Criteria

  1. Read/sample the video at the target rate.
  2. Infer camera motion for sampled-frame intervals and write /root/pred_instructions.json.
  3. Detect dynamic objects for each sampled frame and write /root/pred_dyn_masks.npz in the required CSR key format.
  4. Treat frame extraction, sampling metadata, and environment inspection as preparation only; they are not task completion.
  5. If a run fails and you identify a fix, rerun after applying the fix; treat outputs from earlier failed runs as stale until regenerated successfully.

Tips

```python

flow = cv2.calcOpticalFlowFarneback(

prev_gray, next_gray, None,

pyr_scale=0.5, levels=3, winsize=15,

iterations=3, poly_n=5, poly_sigma=1.2, flags=0

)

```

Tips

Final Validation

Protocol Compliance Check

Before finalizing, verify interaction compliance separately from artifact correctness:

Treat protocol review as a hard stop and a literal checklist:

If any of those checks fail, do not finalize even when both files validate.

If protocol compliance and artifact correctness disagree, protocol compliance still governs task success.

Before declaring completion, open and inspect the deliverables, not just their file paths.

Read the generated files back in their final serialized form: parse the full JSON with json.load(...) and load the NPZ with NumPy. Base any final fixes on what was actually written to disk, not only on in-memory structures or intended logic. Inspect the written interval keys and NPZ key set directly so post-processing bugs in compression/remapping are caught before finalizing.

Use this final stop-check:

If any answer is no, do not finalize.

Treat validation levels separately:

Bound all status claims to observed evidence:

Validation must be spec-driven, not only self-defined.

Use parser-based checks as the default evidence standard:

Also verify the interaction contract is complete: if the task required a specific action syntax or exact completion token, ensure your final response uses that exact form rather than a narrative summary.

Hard-stop final-response rule:

If either required artifact is missing, unreadable, stale from an earlier failed run, or replaced by preprocessing outputs, do not finalize; resume the pipeline and regenerate the true deliverables first.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.