scenedetect Package¶
See also
For the scenedetect command, see the CLI reference.
The scenedetect API integrates into Python applications and supports custom detectors and video backends. See Usage below for common examples. The scenedetect package is organized into these submodules:
Functions: high-level functions such as
scenedetect.detect()to analyze a video with any detector (example) and return a list of timecode pairsDetectors: built-in detectors:
AdaptiveDetector: finds fast cuts using a rolling average of HSV content changes
ContentDetector: finds fast cuts using a weighted average of HSV color and optional edge changes
HashDetector: finds fast cuts using perceptual image hashing
HistogramDetector: finds fast cuts using Y-channel (brightness) histogram changes in YUV
ThresholdDetector: finds fades in and out using average RGB pixel brightnessOutput: output helpers:
split_video_ffmpegandsplit_video_mkvmergesplit a video into clips for each detected scene
save_imagessaves still frames from each scene
write_scene_listwrites scene lists as CSV,write_scene_list_htmlwrites HTML reports, and additional helpers export EDL, Final Cut Pro XML, and OpenTimelineIOVideo Backends: modular video input backends:
OpenCV:
VideoStreamCv2PyAV:
VideoStreamAvMoviePy:
VideoStreamMoviePyMultiple videos can be read as one continuous stream with
VideoStreamConcat(for example,open_video(["part1.mp4", "part2.mp4"]))Common: common types such as
FrameTimecodefor timecode handlingScene Manager:
SceneManagerruns scene detection on a video with one or more detectorsDetector Interface: the
SceneDetectorbase class for custom detectorsStream Interface: the
VideoStreambase class for custom video backendsStats Manager:
StatsManagerstores per-frame detection metrics and writes them to a CSV stats filePlatform & Logging: logging and utility functions
Most common types and functions can be imported directly from the top-level scenedetect package.
Warning
The PySceneDetect API may change before v1.0. Pin scenedetect to a minor release in your dependencies:
scenedetect~=0.7.0
Usage¶
Find scene cuts in a video with scenedetect.detect():
from scenedetect import detect, ContentDetector
path = "video.mp4"
scenes = detect(path, ContentDetector())
for (scene_start, scene_end) in scenes:
print(f"{scene_start}-{scene_end}")
scenes is a list of FrameTimecode pairs giving the start and end of each scene. Pass show_progress=True to detect to show a progress bar with estimated time remaining.
This example uses ContentDetector to find fast cuts. You can choose from several detectors for fast cuts and fades. PySceneDetect can also export scene lists in several formats and split the input video when ffmpeg is installed:
from scenedetect import detect, ContentDetector, split_video_ffmpeg
scene_list = detect("my_video.mp4", ContentDetector())
split_video_ffmpeg("my_video.mp4", scene_list)
See Examples for more tasks shown as both CLI commands and Python code. For advanced workflows, start with the SceneManager. Logging is covered under Platform & Logging.
Functions¶
The scenedetect module comes with helper functions to simplify common use cases.
detect() can be used to perform scene detection on a video by path. open_video()
can be used to open a video for a
SceneManager.
- detect(video_path, detector, stats_file_path=None, show_progress=False, start_time=None, end_time=None, start_in_scene=False, backend='opencv')¶
Perform scene detection on a given video
pathusing the specifieddetector.- Parameters:
video_path (StrPath | list[StrPath] | tuple[StrPath, ...]) – Path to input video (absolute or relative to working directory). May also be a list of paths, in which case the videos are concatenated and treated as a single continuous stream.
detector (SceneDetector) – A
SceneDetectorinstance (seescenedetect.detectorsfor a full list of detectors).stats_file_path (str | PathLike[str] | None) – Path to save per-frame metrics to for statistical analysis or to determine a better threshold value.
show_progress (bool) – Show a progress bar with estimated time remaining. Default is False.
start_time (int | float | str | Timecode | FrameTimecode | None) – Starting point in video, in the form of a timecode
HH:MM:SS[.nnn](str), number of seconds123.45(float), or number of frames200(int).end_time (int | float | str | Timecode | FrameTimecode | None) – Starting point in video, in the form of a timecode
HH:MM:SS[.nnn](str), number of seconds123.45(float), or number of frames200(int).start_in_scene (bool) – Assume the video begins in a scene. This means that when detecting fast cuts with
ContentDetector, if no cuts are found, the resulting scene list will contain a single scene spanning the entire video (instead of no scenes). When detecting fades withThresholdDetector, the beginning portion of the video will always be included until the first fade-out event is detected.backend (str) – Name of the backend to use for video decoding. See
scenedetect.backends.AVAILABLE_BACKENDSfor backends available on the current system. Defaults to OpenCV; falls back to OpenCV if the requested backend is unavailable or fails to open the video.
- Returns:
List of scenes as pairs of (start, end)
FrameTimecodeobjects.- Raises:
VideoOpenFailure –
video_pathcould not be opened.StatsFileCorrupt –
stats_file_pathis an invalid stats fileValueError –
start_timeorend_timeare incorrectly formatted.TypeError –
start_timeorend_timeare invalid types.
- Return type:
list[tuple[’FrameTimecode’, ’FrameTimecode’]]
- open_video(path, frame_rate=None, backend='opencv', framerate=None, **kwargs)¶
Open a video at the given path. If
backendis specified but not available on the current system, OpenCV (VideoStreamCv2) will be used as a fallback.- Parameters:
path (str | PathLike[str] | list[str | os.PathLike[str]] | tuple[str | os.PathLike[str], ...]) – Path to video file to open. May also be a list of paths, in which case the videos are concatenated and treated as a single continuous stream (see
VideoStreamConcat).frame_rate (float | Fraction | None) – Overrides detected frame rate if set. Takes precedence over
framerate.backend (str) – Name of specific backend to use, if possible. See
scenedetect.backends.AVAILABLE_BACKENDSfor backends available on the current system. If the backend fails to open the video, OpenCV will be used as a fallback.framerate (float | None) – [DEPRECATED] Use
frame_rateinstead. Retained as a deprecated alias for backwards compatibility; ignored whenframe_rateis provided.kwargs – Optional named arguments to pass to the specified
backendconstructor for overriding backend-specific options.
- Returns:
Backend object created with the specified video path.
- Raises:
VideoOpenFailure – Constructing the VideoStream fails. If multiple backends have been attempted, the error from the first backend will be returned.
- Return type: