TGraphX › Insights › Scene Change Detection in Python: Frame-Difference Metrics and Thresholds
← Back to Insights

Scene Change Detection in Python: Frame-Difference Metrics and Thresholds

Topic: Vision, multimodal and domain applications

To detect scene changes in Python, compute a difference between each frame and the one before it, and report a change when the difference reaches a threshold. The code is short. The work lies in choosing the difference metric and the threshold, and the only reliable way to choose is to score them against clips whose boundaries you know.

This tutorial builds such a clip with a hard cut, a dissolve, a camera pan, a flash and a brief object, compares three common metrics and several decision rules on it, and then tests the chosen settings on two further clips, with the same events but other textures and noise, that were not used to choose them. All numbers below were printed by the code shown, with Python 3.13, NumPy 2.5.5 and OpenCV 5.1.0.

Three ways to measure how different two frames are

Let Y_t be frame t in grayscale, with values from 0 to 255, height H and width W.

Mean absolute difference (MAD) compares pixels at the same position:

text
MAD_t = (1 / (H * W)) * sum over x, y of | Y_t(x, y) - Y_{t-1}(x, y) |

It reacts to any change of intensity: a new scene, but also motion, a lighting change and sensor noise.

Histogram distance compares how often each intensity occurs and ignores where. With p and q the two histograms normalised to sum to one, OpenCV's Hellinger option computes:

text
d(p, q) = sqrt( 1 - sum over bins i of sqrt(p_i * q_i) )

It is 0 for identical histograms and 1 when no bin is occupied in both. It tolerates motion well, and it cannot see a rearrangement of the same intensities.

Structural similarity (SSIM) compares local means, variances and covariance of two images a and b (Wang et al., 2004):

text
SSIM = ((2*mu_a*mu_b + C1) * (2*cov_ab + C2)) / ((mu_a^2 + mu_b^2 + C1) * (var_a + var_b + C2))

The statistics are taken in a Gaussian window, here 11 by 11 pixels with standard deviation 1.5, and the resulting map is averaged. The constants are C1 = (0.01 * 255)^2 and C2 = (0.03 * 255)^2. SSIM is 1 for identical images, so use 1 - SSIM as the difference.

A test sequence with known boundaries

The sequence has 40 grayscale frames at 10 frames per second. Three places count as scene boundaries: a hard cut at frame 6, a six frame dissolve (an alarm anywhere in frames 18 to 24 is accepted) and a hard cut at frame 28. The pan, the flash and the brief object are distractors that should raise no alarm. Scene D is scene C mirrored left to right, so the two have the same histogram before noise.

python
import cv2
import numpy as np

H, W, FPS = 120, 160, 10


def texture(seed, width, low, high):
    grid = np.random.default_rng(seed).uniform(low, high, (6, width // 20)).astype(np.float32)
    return cv2.resize(grid, (width, H), interpolation=cv2.INTER_CUBIC)


def make_sequence(seed=0, noise=2.0):
    a = texture(seed + 1, W, 30, 130)
    wide = texture(seed + 2, W + 48, 90, 220)   # scene B is wider so it can pan
    c = texture(seed + 3, W, 40, 200)
    d = np.fliplr(c)                            # same pixel values, other layout
    frames = [a] * 6                            # 0-5    scene A, static
    for i in range(6):                          # 6-11   scene B, a small square moves
        f = wide[:, :W].copy()
        f[50:66, 20 + 6 * i:36 + 6 * i] = 40
        frames.append(f)
    frames += [wide[:, 8 * k:8 * k + W] for k in range(1, 7)]                # 12-17  pan
    frames += [(1 - k / 7) * wide[:, 48:] + (k / 7) * c for k in range(1, 7)]  # 18-23
    frames += [c] * 4                           # 24-27  scene C
    frames += [d] * 12                          # 28-39  scene D
    frames[33] = d + 90                         # one-frame flash
    for i in (36, 37, 38):                      # a small bright object appears briefly
        f = d.copy()
        f[20:44, 110:134] = 250
        frames[i] = f
    rng = np.random.default_rng(seed)
    return [np.clip(f + rng.normal(0, noise, f.shape), 0, 255).round().astype(np.uint8)
            for f in frames]


# Frame indices at which a boundary alarm counts as correct.
TRUTH = {"cut A-B": range(6, 7), "dissolve B-C": range(18, 25), "cut C-D": range(28, 29)}

Compute the three curves

python
def mad(a, b):
    return float(np.mean(cv2.absdiff(a, b)))


def hist_distance(a, b, bins=32):
    h = [cv2.calcHist([x], [0], None, [bins], [0, 256]) for x in (a, b)]
    return float(cv2.compareHist(h[0], h[1], cv2.HISTCMP_HELLINGER))


def ssim(a, b):
    a, b = a.astype(np.float64), b.astype(np.float64)
    c1, c2 = (0.01 * 255) ** 2, (0.03 * 255) ** 2

    def blur(x):
        return cv2.GaussianBlur(x, (11, 11), 1.5, borderType=cv2.BORDER_REFLECT)

    mu_a, mu_b = blur(a), blur(b)
    var_a, var_b = blur(a * a) - mu_a ** 2, blur(b * b) - mu_b ** 2
    cov = blur(a * b) - mu_a * mu_b
    s = ((2 * mu_a * mu_b + c1) * (2 * cov + c2)) / (
        (mu_a ** 2 + mu_b ** 2 + c1) * (var_a + var_b + c2))
    return float(s[5:-5, 5:-5].mean())          # drop the 5-pixel border


def one_minus_ssim(a, b):
    return 1 - ssim(a, b)


def curve(frames, metric):
    return [0.0] + [metric(p, q) for p, q in zip(frames, frames[1:])]


frames = make_sequence()
curves = {name: curve(frames, fn) for name, fn in
          (("MAD", mad), ("histogram", hist_distance), ("1-SSIM", one_minus_ssim))}
events = {"static": range(1, 6), "cut A-B": [6], "moving square": range(7, 12), "pan": range(12, 18),
          "dissolve": range(18, 25), "cut C-D": [28], "flash on/off": [33, 34], "small object": [36, 39]}
print(f"{'frames':14s}" + "".join(f"{n:>16s}" for n in curves))
for label, where in events.items():
    cells = []
    for values in curves.values():
        lo, hi = min(values[t] for t in where), max(values[t] for t in where)
        cells.append(f"{lo:.2f}" if f"{lo:.2f}" == f"{hi:.2f}" else f"{lo:.2f}-{hi:.2f}")
    print(f"{label:14s}" + "".join(f"{c:>16s}" for c in cells))
text
frames                     MAD       histogram          1-SSIM
static               2.24-2.26            0.01            0.08
cut A-B                  82.96            0.86            0.66
moving square        3.60-3.84            0.01            0.11
pan                13.06-15.91       0.02-0.08       0.19-0.23
dissolve             7.03-7.11       0.09-0.13       0.08-0.10
cut C-D                  47.13            0.01            0.62
flash on/off       88.26-88.27       0.76-0.77            0.23
small object         7.03-7.06            0.12            0.12

Three facts are already visible, before any threshold is chosen:

  • The histogram distance at the cut from C to D is 0.01, the same as for a static scene. No histogram threshold can find that cut.
  • The flash gives the largest MAD of the whole sequence. A threshold that catches real cuts will catch it too.
  • The dissolve changes each frame by about 7 grey levels, the same amount as the brief object and less than the pan.
Metric Compares Blind or weak spot On this clip
MAD intensities at the same position a flash looks like a cut; motion raises the baseline both cuts stand out; dissolve and small object tie at about 7
Histogram distance how often each intensity occurs any rearrangement of the same intensities misses the second cut entirely
1 - SSIM local means, contrast and structure sensitive to noise in flat areas; small per-step change in a dissolve both cuts stand out above the pan and the flash

The SSIM implementation above agreed with scikit-image's structural_similarity (Gaussian weights, same constants) to within 1e-13 on all frame pairs of the three clips used here.

Mean absolute difference between consecutive frames of the test clip

MAD, grey levels044.13588.269ABpanCDthreshold 30036912151821242730333639frame

MAD, values at or above the threshold: 4 of 40 (6, 28, 33, 34)

Windows
windowcoversat or above threshold at
A0 to 5none
B6 to 116
pan12 to 17none
dissolve18 to 24none
C25 to 27none
D28 to 3928, 33, 34
MAD, grey levels by frame
frameMADat or above threshold
00none
12.244none
22.251none
32.262none
42.256none
52.257none
682.961MAD
73.602none
83.688none
93.779none
103.794none
113.843none
1215.908none
1314.245none
1414.11none
1513.878none
1613.761none
1713.057none
187.059none
197.095none
207.077none
217.065none
227.07none
237.109none
247.031none
252.248none
262.275none
272.245none
2847.127MAD
292.261none
302.251none
312.249none
322.273none
3388.264MAD
3488.269MAD
352.26none
367.056none
372.26none
382.257none
397.034none

Threshold 30. MAD is at or above it at 4 of 40 (6, 28, 33, 34).

Move the threshold. Brackets mark the labelled segments; the peak inside D is the flash, not a boundary. Measured values, as recorded by the author: 40 frame 160x120 synthetic sequence from this article's code, seed 0, noise sigma 2; NumPy 2.5.5, OpenCV 5.1.0. The figure only displays and compares them. Which values cross the threshold is computed from them.

Histogram distance and structural dissimilarity on the same clip

dissimilarity00.51threshold 0.3036912151821242730333639frame

histogram distance (circles)1 - SSIM (squares, dashed)

histogram distance, values at or above the threshold: 3 of 40 (6, 33, 34)

1 - SSIM, values at or above the threshold: 2 of 40 (6, 28)

dissimilarity by frame
framehistogram distance1 - SSIMat or above threshold
000none
10.0120.082none
20.010.083none
30.0090.085none
40.0090.083none
50.0090.083none
60.8590.657histogram distance, 1 - SSIM
70.0080.111none
80.0110.111none
90.0110.11none
100.0110.107none
110.0110.11none
120.0820.233none
130.0180.206none
140.0240.203none
150.0270.196none
160.0290.192none
170.0390.188none
180.1210.094none
190.1140.102none
200.0940.104none
210.0980.101none
220.1050.096none
230.1180.091none
240.1290.08none
250.0130.066none
260.0130.067none
270.0120.066none
280.010.6171 - SSIM
290.0070.066none
300.0090.066none
310.0080.066none
320.0090.067none
330.7640.228histogram distance
340.7650.228histogram distance
350.0120.067none
360.1240.119none
370.0070.065none
380.0080.065none
390.1240.118none

Threshold 0.3. histogram distance is at or above it at 3 of 40 (6, 33, 34). 1 - SSIM is at or above it at 2 of 40 (6, 28).

Compare frame 28: structural dissimilarity jumps at the second cut while histogram distance stays at its floor. Measured values, as recorded by the author: Same 40 frame synthetic sequence; 32 bin histograms with Hellinger distance; SSIM with 11x11 Gaussian window. The figure only displays and compares them. Which values cross the threshold is computed from them.

Predict the size of each effect

You can estimate most of these values before running anything, which tells you when no threshold can work.

Noise. If every pixel carries independent Gaussian noise of standard deviation s, the difference of two frames of a static scene has standard deviation s * sqrt(2), and its mean absolute value is 2 * s / sqrt(pi). This is the floor below which a threshold detects only noise.

Dissolve. A linear dissolve from image A to image B over L intermediate frames shows A + k/(L+1) * (B - A) at step k. Consecutive frames therefore differ by (B - A) / (L+1), and the per-step MAD is MAD(A, B) / (L+1). Make the dissolve twice as long and its signal roughly halves.

Small object. An object covering a fraction a of the frame with contrast c against what it replaces adds about a * c; the rest of the frame still shows the noise floor.

python
clean = make_sequence(noise=0.0)
blend_step = mad(clean[17], clean[24]) / 7          # 6 intermediate frames, so 7 steps
print("noise floor 2*sigma/sqrt(pi):", round(float(2 * 2.0 / np.sqrt(np.pi)), 2), " measured:", round(float(np.mean(curves["MAD"][1:6])), 2))
print("dissolve step, MAD(B, C)/7:  ", round(blend_step, 2), " measured:", round(float(np.mean(curves["MAD"][18:25])), 2))
area = 24 * 24 / (H * W)
contrast = float(np.mean(np.abs(clean[36][20:44, 110:134].astype(float) - clean[35][20:44, 110:134])))
estimate = area * contrast + (1 - area) * 2 * 2.0 / np.sqrt(np.pi)
print("object, a*contrast + (1-a)*noise:", round(float(estimate), 2), f"(a = {area:.1%}, contrast {contrast:.0f})  measured:", round(curves["MAD"][36], 2))
text
noise floor 2*sigma/sqrt(pi): 2.26  measured: 2.25
dissolve step, MAD(B, C)/7:   6.73  measured: 7.07
object, a*contrast + (1-a)*noise: 7.05 (a = 3.0%, contrast 162)  measured: 7.06

The dissolve estimate ignores noise, so the measured value is slightly higher. The coincidence that matters is the last two lines: a dissolve between two quite different scenes and a small bright square produce nearly the same global number, so no threshold on adjacent MAD separates them.

Score thresholds against the labels

A detector that fires on several frames in a row should count as one alarm, so each run of frames at or above the threshold becomes one alarm located at its first frame. An alarm is correct if it falls inside a labelled boundary that has not been found yet. Then:

text
precision = correct alarms / all alarms
recall    = boundaries found / 3

State this matching rule whenever you report such numbers. A rule that credits any overlap would, for example, let a run that starts in the pan and continues into the dissolve count as finding the dissolve.

Besides fixed thresholds on adjacent frames, the code below implements three common repairs:

  • a flash check, which drops an alarm if the frames before and after it are similar again;
  • a local ratio, which compares each difference with the mean of its neighbours, so that steady motion raises its own baseline;
  • a reference comparison, which measures change against the last accepted keyframe instead of the previous frame, so that slow changes accumulate.
python
def onsets(flags):
    return [t for t, on in enumerate(flags) if on and not (t and flags[t - 1])]


def adjacent(frames, metric, threshold, flash_check=False):
    alarms = onsets([v >= threshold for v in curve(frames, metric)])
    if flash_check:             # drop an alarm if the next frame is back to normal
        alarms = [t for t in alarms
                  if t + 1 == len(frames) or metric(frames[t - 1], frames[t + 1]) >= threshold]
    return alarms


def local_ratio(frames, ratio=4.0, floor=10.0, half=2):
    v = curve(frames, mad)
    flags = [False]
    for t in range(1, len(v)):
        around = [v[i] for i in range(max(1, t - half), min(len(v), t + half + 1)) if i != t]
        flags.append(v[t] >= floor and v[t] >= ratio * np.mean(around))
    return onsets(flags)


def against_reference(frames, threshold, metric=mad):
    reference, last, alarms = frames[0], -2, []
    for t in range(1, len(frames)):
        if metric(reference, frames[t]) >= threshold:
            if t + 1 < len(frames) and metric(reference, frames[t + 1]) < threshold:
                continue                             # a flash: the old scene returns
            if t != last + 1:
                alarms.append(t)
            reference, last = frames[t], t
    return alarms


def score(alarms):
    found, correct = set(), 0
    for t in alarms:
        hit = next((n for n, span in TRUTH.items() if t in span and n not in found), None)
        if hit:
            found.add(hit)
            correct += 1
    precision = correct / len(alarms) if alarms else 0.0
    return f"{precision:.2f}/{len(found) / len(TRUTH):.2f}"


detectors = {
    "MAD >= 30": lambda f: adjacent(f, mad, 30),
    "MAD >= 7.08": lambda f: adjacent(f, mad, 7.08),
    "histogram >= 0.5": lambda f: adjacent(f, hist_distance, 0.5),
    "1-SSIM >= 0.3": lambda f: adjacent(f, one_minus_ssim, 0.3),
    "MAD >= 30, flash check": lambda f: adjacent(f, mad, 30, flash_check=True),
    "local ratio >= 4": local_ratio,
    "reference MAD >= 40": lambda f: against_reference(f, 40),
}
clips = {"dev": frames, "noisier": make_sequence(10, 4.0), "other": make_sequence(20, 2.0)}
print(f"{'precision/recall':24s}" + "".join(f"{n:>11s}" for n in clips) + "   alarms on dev")
for name, run in detectors.items():
    print(f"{name:24s}" + "".join(f"{score(run(c)):>11s}" for c in clips.values()), "  ", run(frames))

The noisier clip uses other textures with noise of standard deviation 4 instead of 2; other uses a third set of textures. Neither was used to pick a setting. The output was:

text
precision/recall                dev    noisier      other   alarms on dev
MAD >= 30                 0.67/0.67  0.67/0.67  0.67/0.67    [6, 28, 33]
MAD >= 7.08               0.50/1.00  0.33/0.67  0.50/0.67    [6, 12, 19, 23, 28, 33]
histogram >= 0.5          0.50/0.33  0.50/0.33  0.50/0.33    [6, 33]
1-SSIM >= 0.3             1.00/0.67  0.50/0.67  1.00/0.67    [6, 28]
MAD >= 30, flash check    1.00/0.67  1.00/0.67  1.00/0.67    [6, 28]
local ratio >= 4          1.00/0.67  1.00/0.67  1.00/0.67    [6, 28]
reference MAD >= 40       1.00/1.00  0.75/1.00  0.67/0.67    [6, 23, 28]

How to choose a threshold

The table shows the trap. A MAD threshold of 7.08, set at the level of the dissolve, finds all three boundaries on the development clip at the price of three false alarms. On the other two clips each dissolve step is larger than 7.08 (about 9.6 and 7.7), so the run of frames that starts in the pan continues straight into the dissolve: one alarm, placed in the pan, covers both, and the dissolve counts as missed. The reference comparison looks perfect on the development clip and is not on the other two. Its threshold of 40 was chosen after looking at that clip.

A procedure that avoids fooling yourself:

  1. Label boundaries in several clips that resemble your material, including the distractors it contains.
  2. Split the clips. Tune on one part and report results on the other.
  3. Plot the curve and look for a threshold with a wide margin: here, any MAD threshold between about 20 and 40 gives the same three alarms on all three clips. A setting that works only within a few tenths of a grey level will not survive another camera.
  4. Measure the noise floor of your footage. Compression artefacts and grain raise every metric, and the threshold must sit above that floor. On the noisier clip a static scene already scored about twice the MAD of the development clip.
  5. Decide which error costs more. For selecting frames to send to a model, an extra sample is cheap and a missed scene is not.

For a maintained implementation rather than your own, PySceneDetect documents several detectors: a content based one on HSV differences, an adaptive one with a rolling average, a threshold based one for fades to and from black, and histogram and hash based ones. It was not run for this article. Score it with the same labels and matching rule before trusting its defaults.

Failure modes

Situation What goes wrong Possible response
Hard cut between similar tones histogram distance does not move use a metric that keeps position, such as MAD or SSIM
Dissolve or fade each step is small compare with a reference frame, or over a window
Flash or strobe two very large differences check that the old scene returns
Camera pan or shake sustained large differences local ratio, or compensate global motion first
Slow motion or drift never reaches an adjacent frame threshold add a maximum interval between samples
Brief or small object barely changes a global average block-wise differences, or sample more densely
Scene that returns later each return looks like a new scene keep descriptors of past keyframes and compare

From boundaries to sampled frames

A frame sampler has a different goal from a shot detector. It chooses which frames a model will see, so measure it by what it shows: does every scene receive a sample, how long after the scene starts, and how many frames did that cost?

The sampler in AI-Powered Video Analyzer is a convenient example to measure. At v1.1.0 (commit 313448a, checked 2026-11-27) its sampler uses one metric: MAD between consecutive decoded frames at full resolution. The same number is reported as both scene_score and motion_score. The sampler module's own description speaks of histogram differences, but no histogram is computed, and no SSIM, optical flow or deduplication either.

Setting Command line flag AnalysisConfig field Default
Strategy --strategy frame_strategy adaptive
Regular rate, samples per second --target-fps target_fps 1.0
Rate bounds none min_fps, max_fps 0.25, 4.0
Scene threshold none scene_threshold 30.0
Motion threshold none motion_threshold 5.0
Frame budget --max-frames max_frames 2000

The strategies are uniform, adaptive, scene_change, motion_aware and hybrid; hybrid runs the same branch as adaptive. The two thresholds can be changed only from Python. The frame budget is counted from the start of the video, not spread over it: once it is reached, the rest is not analyzed. Timestamps are the frame index divided by the reported frame rate.

The next block writes the test sequence losslessly (the decoded pixels were identical to the originals) and asks the analyzer which frames it would give to its models. No model is loaded.

python
from ai_powered_video_analyzer.config import AnalysisConfig
from ai_powered_video_analyzer.core import analyze_video

out = cv2.VideoWriter("labelled.avi", cv2.VideoWriter_fourcc(*"FFV1"), FPS, (W, H))   # lossless
for f in frames:
    out.write(cv2.cvtColor(f, cv2.COLOR_GRAY2BGR))
out.release()

segments = {"A": (0, 5), "B": (6, 17), "C": (24, 27), "D": (28, 39)}
for strategy in ("uniform", "adaptive", "hybrid", "scene_change", "motion_aware"):
    report = analyze_video(AnalysisConfig(
        video_path="labelled.avi", output_dir=f"out_{strategy}", backend="none",
        frame_strategy=strategy, enable_captioning=False, enable_audio_events=False,
        enable_summarization=False, ollama_model="unused"))
    picked = [o["frame_index"] for o in report.frame_observations]
    delay = {name: next((i - a for i in picked if a <= i <= b), None)
             for name, (a, b) in segments.items()}
    print(f"{strategy:13s}{len(picked):3d} frames  delay per scene {delay}")
    if strategy in ("adaptive", "scene_change"):
        print("   ", picked)
text
uniform        4 frames  delay per scene {'A': 0, 'B': 4, 'C': None, 'D': 2}
adaptive      13 frames  delay per scene {'A': 0, 'B': 0, 'C': 0, 'D': 0}
    [0, 6, 12, 14, 16, 18, 20, 22, 24, 28, 33, 36, 39]
hybrid        13 frames  delay per scene {'A': 0, 'B': 0, 'C': 0, 'D': 0}
scene_change   4 frames  delay per scene {'A': 0, 'B': 0, 'C': None, 'D': 0}
    [0, 6, 28, 33]
motion_aware  13 frames  delay per scene {'A': 0, 'B': 0, 'C': 0, 'D': 0}
Strategy Selects Frames here Scenes reached What it cost or missed
uniform one frame per target interval 4 3 of 4 missed scene C
scene_change large differences, else a long fallback interval 4 3 of 4 missed scene C, which arrived by dissolve
motion_aware moderate differences, else the fallback 13 4 of 4 many samples in pan and dissolve
adaptive, hybrid large or moderate differences, else the target interval 13 4 of 4 same frames as motion_aware here

Delays are in frames. None means that the scene was never sampled: the uniform grid and the scene_change strategy both skip scene C, which appears through the dissolve and lasts four frames before the next cut. The adaptive run reaches every scene at once but spends 13 frames on four scenes, because the pan and the dissolve both stay above the motion threshold of 5. It also spends samples on the flash and on the brief object. For a model pipeline that may be acceptable; for a list of scene boundaries it is not.

Uniform, adaptive and scene change sampling on the labelled clip

ScenesAB, then panCDTransition and distractorsuniformadaptivescene_change00.511.522.533.54seconds
What each lane holds at the selected time
laneholds
ScenesC
Transition and distractorsnothing
uniformno frame here (nearest at 2 s)
adaptivea sampled frame
scene_changeno frame here (nearest at 2.8 s)
Events, with the sampled frames inside each visual event
eventlanetimeuniformadaptivescene_change
AScenes0 to 0.5 sframe at 0 sframe at 0 sframe at 0 s
B, then panScenes0.6 to 1.7 sframe at 1 sframe at 0.6, 1.2, 1.4 s and 1 moreframe at 0.6 s
CScenes2.4 to 2.7 smissedframe at 2.4 smissed
DScenes2.8 to 3.9 sframe at 3 sframe at 2.8, 3.3, 3.6 s and 1 moreframe at 2.8, 3.3 s
dissolveTransition and distractors1.8 to 2.3 sframe at 2 sframe at 1.8, 2, 2.2 smissed
flashTransition and distractors3.3 smissedframe at 3.3 sframe at 3.3 s
objectTransition and distractors3.6 to 3.8 smissedframe at 3.6 smissed

uniform: 4 frames in 4 s (1 per second); visual events without a sampled frame: 3 of 7 (C, flash, object).

adaptive: 13 frames in 4 s (3.25 per second); visual events without a sampled frame: 0 of 7.

scene_change: 4 frames in 4 s (1 per second); visual events without a sampled frame: 3 of 7 (C, dissolve, object).

At 2.4 s. Scenes: C. Transition and distractors: nothing. uniform: no frame here (nearest at 2 s). adaptive: a sampled frame. scene_change: no frame here (nearest at 2.8 s).

Select a time. Dashed outlines mark labelled segments or events that a row of samples missed. Measured times and events, as recorded by the author: Analyzer v1.1.0 sampler with default settings on the article's 40 frame sequence at 10 fps, lossless FFV1; OpenCV 5.1.0. The figure only displays and compares them. A frame shows a visual event when its time lies from the start to the end, both included.

Timestamps and a frame budget

For a video file, compute scores in one streaming pass and keep only numbers in memory. The function below also downscales each frame, which makes the pass cheaper and smooths noise; it changes the scale of the scores, so tune thresholds at the resolution you will run.

The time index / fps is right for constant frame rate files only. For variable frame rate input, look up the presentation timestamp of each index with ffprobe instead.

A budget of K frames can be spent in different ways. Stopping after the first K selections analyzes the start of a long video in detail and nothing after it. If you can afford a first pass over the whole file, take the largest changes first, with a minimum gap so that one event does not use several slots:

python
def video_scores(path, metric=mad, width=160):
    """Yield (frame index, seconds, score against the previous frame) for a video file."""
    cap = cv2.VideoCapture(path)
    fps = cap.get(cv2.CAP_PROP_FPS) or 25.0
    previous, index = None, 0
    while True:
        ok, frame = cap.read()
        if not ok:
            break
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        height = round(gray.shape[0] * width / gray.shape[1])
        gray = cv2.resize(gray, (width, height), interpolation=cv2.INTER_AREA)
        yield index, index / fps, 0.0 if previous is None else metric(previous, gray)
        previous, index = gray, index + 1
    cap.release()


def budgeted(scores, budget, min_gap):
    """Frame 0, then the largest changes first, keeping a minimum gap."""
    chosen = [0]
    for t in sorted(range(1, len(scores)), key=lambda t: -scores[t]):
        if len(chosen) < budget and all(abs(t - c) >= min_gap for c in chosen):
            chosen.append(t)
    return sorted(chosen)


scores = [s for _, _, s in video_scores("labelled.avi")]
for budget in (4, 5, 6, 8):
    print(budget, "frames:", budgeted(scores, budget, min_gap=3))
text
4 frames: [0, 6, 28, 34]
5 frames: [0, 6, 12, 28, 34]
6 frames: [0, 6, 12, 15, 28, 34]
8 frames: [0, 6, 12, 15, 19, 23, 28, 34]

The first slot after frame 0 goes to the flash (frame 34, where the picture changes back), because it has the largest difference of all. Scene C is missing from all four selections, even the one with eight frames. A practical compromise reserves part of the budget for evenly spaced samples, so that no long stretch goes unseen, and gives the rest to the largest changes.

What an unsampled stretch of video means for the conclusions of an analysis is covered in from frames to timestamped evidence.

Every sampled frame costs detector time; the CPU and GPU detector benchmark gives measured values.

What this test does and does not show

The clips are small, synthetic and designed to contain each failure once. They show how a metric fails and give you a scoring harness; they do not rank the metrics for real footage, where compression, grain, exposure changes and gradual camera motion all move the numbers. Replace make_sequence with your own labelled clips and keep the rest.

References