AI-Powered Video Analyzer: Which Frames It Samples and Skips
The AI-Powered Video Analyzer does not run its models on every frame. It decodes the video from the start and keeps a frame when it differs enough from the frame just before it, or when about one second has passed since the last kept frame. Object detection and captioning only see the kept frames. After 2,000 kept frames (the default) it stops reading, and the report gets no note saying so. At 30 frames per second that cap covers somewhere between about 9 and 33 minutes of video, depending on how much the picture moves.
This page walks through the sampling code of version 1.1.0 (commit 313448a), reproduces it in a few lines of NumPy, and checks the result on a synthetic clip.
The decision for each frame
The sampler is FrameSampler in frames.py. For every decoded frame it converts the image to grayscale and computes one number, the mean absolute pixel difference to the previous decoded frame (not to the previous kept frame). The report stores it as scene_score and again as motion_score; the two fields are always equal.
With the default strategy, adaptive, the frame is then judged in this order:
How the adaptive strategy judges one decoded frame
Four checks in order for each decoded frame: a minimum gap since the last kept frame, a scene change threshold, a motion threshold and a periodic rule.
| stage | input | output | what happens |
|---|---|---|---|
| 1. Minimum gap | frames since the last kept frame | skip, or continue | If fewer than round(fps / 4) frames have passed, the frame is dropped, however large its difference score is. |
| 2. Scene change | difference score | keep as scene_change | Kept if the mean absolute grey difference to the previous frame is at least 30. |
| 3. Motion | difference score | keep as motion | Otherwise kept if the difference is at least 5. |
| 4. Periodic | frames since the last kept frame | keep as periodic, or skip | Otherwise kept if at least round(fps / target_fps) frames have passed, about one second by default. |
Stage 1 of 4, Minimum gap. Input: frames since the last kept frame. Output: skip, or continue.
| Setting | Default | Command-line flag | Used by adaptive |
|---|---|---|---|
| strategy | adaptive |
--strategy |
|
| target_fps | 1.0 | --target-fps |
yes |
| max_fps | 4.0 | none | yes, as the minimum gap |
| min_fps | 0.25 | none | no |
| scene_threshold | 30 | none | yes |
| motion_threshold | 5 | none | yes |
| max_frames | 2000 | --max-frames |
yes |
Three details are easy to miss:
hybridruns exactly the same branch asadaptive.min_fpsonly matters forscene_changeandmotion_aware, which fall back to one frame everyround(fps / min_fps)frames (4 seconds) when nothing passes their threshold.uniformapplies only the gap rules.- The 4 frames per second ceiling is approximate because the gap is rounded to whole frames. At 30 fps the gap is 8 frames (3.75 samples per second), at 25 fps it is 6 (4.17 per second), and at 29.97 fps it is 7 (4.28 per second).
The rule in runnable form
You do not need the analyzer or any video to explore the rule. Selection depends only on the frame rate and the per-frame difference scores, so a short function reproduces it. I compared this function with the package's FrameSampler on 60 generated videos across all five strategies (300 comparisons): the kept frame indices and reasons were identical.
from collections import Counter
import numpy as np
def select_frames(scores, fps, strategy="adaptive", target_fps=1.0, min_fps=0.25,
max_fps=4.0, scene_threshold=30.0, motion_threshold=5.0,
max_frames=2000):
"""scores[i]: mean absolute grey difference between frames i-1 and i."""
min_gap = max(1, round(fps / max_fps))
max_gap = max(1, round(fps / min_fps))
target_gap = max(1, round(fps / target_fps))
picked, last = [], -999
for i, score in enumerate(scores):
if len(picked) >= max_frames:
break
gap = i - last
if gap < min_gap:
continue
reason = None
if strategy in ("adaptive", "hybrid"):
if score >= scene_threshold:
reason = "scene_change"
elif score >= motion_threshold:
reason = "motion"
elif gap >= target_gap:
reason = "periodic"
elif strategy in ("scene_change", "motion_aware"):
limit = scene_threshold if strategy == "scene_change" else motion_threshold
if score >= limit:
reason = "scene_change" if strategy == "scene_change" else "motion"
elif gap >= max_gap:
reason = "max_interval_fallback"
elif gap >= target_gap: # uniform
reason = "uniform"
if reason:
picked.append((i, reason))
last = i
return picked
# A 40 s clip at 30 fps: still, a cut at 20 s into a moving shot, a cut at 30 s.
fps = 30
scores = np.zeros(40 * fps)
scores[20 * fps] = 74.9 # first cut
scores[20 * fps + 1 : 30 * fps] = 14.0 # panning shot
scores[30 * fps] = 63.2 # second cut
picked = select_frames(scores, fps)
for start, end in ((0, 20), (20, 30), (30, 40)):
part = [r for i, r in picked if start <= i / fps < end]
print(f"{start:>2}-{end} s: {len(part):>2} frames", dict(Counter(part)))
print("kept around 30 s:", [i for i, _ in picked if 880 <= i <= 940])
Output:
0-20 s: 20 frames {'periodic': 20}
20-30 s: 38 frames {'scene_change': 1, 'motion': 37}
30-40 s: 10 frames {'periodic': 10}
kept around 30 s: [880, 888, 896, 926]
Look at the last line. The second cut is at frame 900 and its score, 63.2, is far above the scene threshold. But frame 896 had just been kept, so frame 900 falls inside the 8-frame minimum gap. One frame later the score is back to zero, because it compares neighbouring frames only. The cut is never registered; the new shot first appears 26 frames later as an ordinary periodic sample.
What happened on a real file
I rendered the same structure as an actual video: 640 by 480 at 30 fps, 20 seconds of a still photograph, 10 seconds of a panning photograph of a coffee cup, 10 seconds of a still photograph of a cat, with three synthetic spoken sentences as audio. Version 1.1.0 kept 67 of the 1,200 frames:
| Segment | Kept | Reasons recorded |
|---|---|---|
| 0 to 20 s, still | 20 | 20 periodic |
| 20 to 30 s, panning | 37 | 1 scene_change, 36 motion |
| 30 to 40 s, still | 10 | 10 periodic |
It behaved as the rule predicts, including the miss: the cut at 30 s scored about 63, but the first frame kept after it was at 30.87 s with reason periodic. The panning segment yielded one frame fewer than the idealised version, since a real pan does not have a constant difference score.
Two practical consequences follow. A shot shorter than about a second that starts right after a kept frame can be sampled once or not at all. And the reason periodic does not mean "nothing changed here".
How much of a long video is covered
The loop is while sampled < max_frames, so the cap counts kept frames and the video is read front to back. Everything after the 2,000th kept frame is never decoded for detection or captioning. Between two kept frames the gap is at least the minimum gap and, in adaptive, at most the target gap, which gives hard bounds:
coverage is about N × g / fps seconds, where N is the frame cap and g is the gap in frames (between the minimum gap and the target gap).
def covered_minutes(fps, score, **settings):
"""Time of the last kept frame in a very long video with a constant score."""
n = int(fps * 3 * 3600) # three hours of frames
picked = select_frames([score] * n, fps, **settings)
return picked[-1][0] / fps / 60
print(" fps still moving (minutes covered with default settings)")
for fps in (24, 25, 29.97, 30, 60):
print(f"{fps:>5} {covered_minutes(fps, 0.0):5.1f} {covered_minutes(fps, 10.0):6.1f}")
Output:
fps still moving (minutes covered with default settings)
24 33.3 8.3
25 33.3 8.0
29.97 33.4 7.8
30 33.3 8.9
60 33.3 8.3
So a one-hour recording is always cut off with the defaults. Footage whose neighbouring frames differ constantly, which can happen with a hand-held camera or a noisy picture as well as with real action, pushes the sampler toward its maximum rate.
The audio side does not stop at the cap. Audio is extracted and transcribed from the whole file, so a truncated run can contain speech from minutes that no detector ever looked at. I forced this on the 40-second clip with --max-frames 25: the last observation was at 21.17 s, the transcript still held the sentence spoken after 30 s, and limitations had no entry about truncation.
Check every report for it:
def coverage(report):
"""Fraction of the video that lies before the last analysed frame."""
observations = report["frame_observations"]
last = observations[-1]["timestamp_sec"] if observations else 0.0
return last, report["duration_sec"], last / report["duration_sec"]
# Synthetic stand-in with the report's field names; load yours with json.load.
report = {"duration_sec": 3600.0,
"frame_observations": [{"timestamp_sec": 0.0}, {"timestamp_sec": 1999.0}]}
last, duration, share = coverage(report)
print(f"analysed up to {last:.0f} s of {duration:.0f} s ({share:.0%})")
Output:
analysed up to 1999 s of 3600 s (56%)
With the default settings a gap of up to about one second at the end is normal; with a lower --target-fps or another strategy, allow one sampling interval. A larger one means the cap was reached or decoding stopped early.
What it costs to raise the cap
sample() returns a list that holds every kept frame as an uncompressed array, and the list stays in memory for the rest of the run. Each frame needs width × height × 3 bytes:
| Resolution | Per frame | 2,000 frames |
|---|---|---|
| 640 × 480 | 0.92 MB | 1.8 GB |
| 1280 × 720 | 2.76 MB | 5.5 GB |
| 1920 × 1080 | 6.22 MB | 12.4 GB |
I measured one point of this: 600 kept 720p frames held 1.66 GB of pixel data, and the process's peak memory rose by 1.71 GB. Doubling --max-frames for a long 1080p video therefore adds about 12 GB on top of the models.
Choosing settings
--target-fps does not limit the rate in adaptive. It only sets how often still passages are sampled. Moving passages are still taken at up to about 4 per second. Values above 4 have no effect beyond the minimum gap.
For predictable coverage use uniform. --strategy uniform --target-fps 0.5 keeps one frame every 2 seconds, so 2,000 frames reach about 67 minutes at 30 fps, whatever the picture does. You give up the extra frames around action and cuts.
For long videos at full density, split the file. This copies the streams into parts of roughly 7 minutes, short enough to stay under the cap at the frame rates in the table, and writes their start times to a CSV file:
ffmpeg -i long.mp4 -c copy -map 0 -f segment -segment_time 420 \
-reset_timestamps 1 -segment_list parts.csv part%03d.mp4
Parts are cut at keyframes, so their lengths vary a little. Add each part's start time from parts.csv to the timestamps in its report, and expect an error of a few tens of milliseconds. Each part gets its own transcript and summary, and a sentence that crosses a boundary is split. Give each run its own --output-dir, because the file report.txt in an output folder is overwritten by every run.
Limits of these checks
- The measurements come from synthetic clips on one machine. They show how the code behaves, not how well the thresholds suit your footage.
- The thresholds are absolute grey-level differences, so exposure flicker, compression noise or a small bright moving object affect them differently from what a person would call motion.
- Timestamps are computed as frame index divided by the frame rate that OpenCV reports. For variable-frame-rate recordings, such as some phone and screen captures, they may drift from the player's clock. I did not test this case.
- The
benchmarksubcommand has its own default of 100 frames, so its frame counts will not matchanalyze. - Later releases may change any of this.
ai-video-analyzer --versiontells you what you run.
For what to do with the kept frames downstream, for example building a graph with one node per frame, see building vision graphs.
References
- Sajjadi, A. (2026). AI-Powered Video Analyzer, version 1.1.0, source repository (commit
313448a;frames.py,core.py,config.py,cli.py). https://github.com/arashsajjadi/ai-powered-video-analyzer