Scene Change Detection in Python: Frame-Difference Metrics and Thresholds
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:
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:
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):
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.
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
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))
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
Frame difference over 40 frames. High peaks at the two hard cuts and at the flash, a plateau around 13 to 16 during the pan, and a low plateau near 7 during the dissolve, the same height as the brief object.
MAD, values at or above the threshold: 4 of 40 (6, 28, 33, 34)
| window | covers | at or above threshold at |
|---|---|---|
| A | 0 to 5 | none |
| B | 6 to 11 | 6 |
| pan | 12 to 17 | none |
| dissolve | 18 to 24 | none |
| C | 25 to 27 | none |
| D | 28 to 39 | 28, 33, 34 |
| frame | MAD | at or above threshold |
|---|---|---|
| 0 | 0 | none |
| 1 | 2.244 | none |
| 2 | 2.251 | none |
| 3 | 2.262 | none |
| 4 | 2.256 | none |
| 5 | 2.257 | none |
| 6 | 82.961 | MAD |
| 7 | 3.602 | none |
| 8 | 3.688 | none |
| 9 | 3.779 | none |
| 10 | 3.794 | none |
| 11 | 3.843 | none |
| 12 | 15.908 | none |
| 13 | 14.245 | none |
| 14 | 14.11 | none |
| 15 | 13.878 | none |
| 16 | 13.761 | none |
| 17 | 13.057 | none |
| 18 | 7.059 | none |
| 19 | 7.095 | none |
| 20 | 7.077 | none |
| 21 | 7.065 | none |
| 22 | 7.07 | none |
| 23 | 7.109 | none |
| 24 | 7.031 | none |
| 25 | 2.248 | none |
| 26 | 2.275 | none |
| 27 | 2.245 | none |
| 28 | 47.127 | MAD |
| 29 | 2.261 | none |
| 30 | 2.251 | none |
| 31 | 2.249 | none |
| 32 | 2.273 | none |
| 33 | 88.264 | MAD |
| 34 | 88.269 | MAD |
| 35 | 2.26 | none |
| 36 | 7.056 | none |
| 37 | 2.26 | none |
| 38 | 2.257 | none |
| 39 | 7.034 | none |
Threshold 30. MAD is at or above it at 4 of 40 (6, 28, 33, 34).
Histogram distance and structural dissimilarity on the same clip
Two curves over 40 frames. Both peak at the first cut and the flash. At frame 28 only one minus SSIM peaks; histogram distance does not move because the new scene has the same intensities.
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)
| frame | histogram distance | 1 - SSIM | at or above threshold |
|---|---|---|---|
| 0 | 0 | 0 | none |
| 1 | 0.012 | 0.082 | none |
| 2 | 0.01 | 0.083 | none |
| 3 | 0.009 | 0.085 | none |
| 4 | 0.009 | 0.083 | none |
| 5 | 0.009 | 0.083 | none |
| 6 | 0.859 | 0.657 | histogram distance, 1 - SSIM |
| 7 | 0.008 | 0.111 | none |
| 8 | 0.011 | 0.111 | none |
| 9 | 0.011 | 0.11 | none |
| 10 | 0.011 | 0.107 | none |
| 11 | 0.011 | 0.11 | none |
| 12 | 0.082 | 0.233 | none |
| 13 | 0.018 | 0.206 | none |
| 14 | 0.024 | 0.203 | none |
| 15 | 0.027 | 0.196 | none |
| 16 | 0.029 | 0.192 | none |
| 17 | 0.039 | 0.188 | none |
| 18 | 0.121 | 0.094 | none |
| 19 | 0.114 | 0.102 | none |
| 20 | 0.094 | 0.104 | none |
| 21 | 0.098 | 0.101 | none |
| 22 | 0.105 | 0.096 | none |
| 23 | 0.118 | 0.091 | none |
| 24 | 0.129 | 0.08 | none |
| 25 | 0.013 | 0.066 | none |
| 26 | 0.013 | 0.067 | none |
| 27 | 0.012 | 0.066 | none |
| 28 | 0.01 | 0.617 | 1 - SSIM |
| 29 | 0.007 | 0.066 | none |
| 30 | 0.009 | 0.066 | none |
| 31 | 0.008 | 0.066 | none |
| 32 | 0.009 | 0.067 | none |
| 33 | 0.764 | 0.228 | histogram distance |
| 34 | 0.765 | 0.228 | histogram distance |
| 35 | 0.012 | 0.067 | none |
| 36 | 0.124 | 0.119 | none |
| 37 | 0.007 | 0.065 | none |
| 38 | 0.008 | 0.065 | none |
| 39 | 0.124 | 0.118 | none |
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).
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.
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))
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:
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.
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:
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:
- Label boundaries in several clips that resemble your material, including the distractors it contains.
- Split the clips. Tune on one part and report results on the other.
- 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.
- 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.
- 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.
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)
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
A four second timeline with four scenes, a dissolve, a flash and a brief object. Uniform sampling takes four frames and misses scene C; adaptive takes thirteen and reaches every scene; scene change takes four and misses scene C.
| lane | holds |
|---|---|
| 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) |
| event | lane | time | uniform | adaptive | scene_change |
|---|---|---|---|---|---|
| A | Scenes | 0 to 0.5 s | frame at 0 s | frame at 0 s | frame at 0 s |
| B, then pan | Scenes | 0.6 to 1.7 s | frame at 1 s | frame at 0.6, 1.2, 1.4 s and 1 more | frame at 0.6 s |
| C | Scenes | 2.4 to 2.7 s | missed | frame at 2.4 s | missed |
| D | Scenes | 2.8 to 3.9 s | frame at 3 s | frame at 2.8, 3.3, 3.6 s and 1 more | frame at 2.8, 3.3 s |
| dissolve | Transition and distractors | 1.8 to 2.3 s | frame at 2 s | frame at 1.8, 2, 2.2 s | missed |
| flash | Transition and distractors | 3.3 s | missed | frame at 3.3 s | frame at 3.3 s |
| object | Transition and distractors | 3.6 to 3.8 s | missed | frame at 3.6 s | missed |
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).
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:
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))
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
- Wang, Z., Bovik, A. C., Sheikh, H. R., Simoncelli, E. P. Image Quality Assessment: From Error Visibility to Structural Similarity. IEEE Transactions on Image Processing 13(4), 600-612, 2004.
- OpenCV tutorial: histogram comparison
- scikit-image example: structural similarity index
- PySceneDetect detectors
- AI-Powered Video Analyzer, source repository