:movie_camera: Python and OpenCV-based scene cut/transition detection program & library.
Repo Breakthrough/PySceneDetect, read from GitHub 4 min ago. Breakthrough has not joined Take My Repo.
PySceneDetect 0.7.3 adds scene-length based image export to save-images, a close() method and context manager support for VideoStream, and fixes several timing bugs: PyAV frame timing for videos without presentation timestamps, save-edl timecode drift at NTSC frame rates, OTIO source durations, and the last scene of variable framerate videos. Windows distributions ship updated dependencies.
-i/--interval to save-images to save images based on the length of each scene: one image per DURATION, with --min-images/--max-images to limit the number of images per scene, e.g. save-images -i 2s --max-images 10 (interval/min-images/max-images in the config file, and interval/min_images/max_images in save_images()) #280--help now prints [default: ...] and [setting: ...] values as they are written in a config file (merge, fcpx, yes/no instead of Mode.MERGE, FcpFormat.FCPX, True/on), the [backend-pyav] threading-mode config value is now validated, and the scenedetect.cfg template matches the real config keys and defaults (verbosity, downscale, default-detector, fade-bias, start-timecode, OTIO name, and removed stale filter-mode/luma-only entries) #589$VIDEO_NAME is now derived from the path component of URL inputs, ignoring the query string and fragment (e.g. https://host/clip.mp4?token=1.2 -> clip). URLs with no path use the host. Previously the query string leaked into output filenames, which fails on Windows. #197position on the last frame after reaching the end of a VFR video, so the last scene no longer ends early (or before it starts) #561save-html --no-images now writes to the global -o/--output directory instead of the working directory #583split-video with -o now logs the output folder instead of repeating the filename template #595-d/--downscale on the CLI and downscale in the config file to be set to 0 for automatic downscalingsave-edl timecodes now count frames at the nominal rate (24, 30, or 60 per timecode second for 23.976, 29.97, or 59.94 fps) as required for non-drop-frame timecode, instead of being derived from wall-clock seconds. Previously the EDL drifted by roughly 3.6 seconds per hour at these rates. --start-timecode is parsed the same way, so -s 01:00:00:00 now starts the first event at 01:00:00:00. Non-standard rates (e.g. the average rate of a VFR video) are unchanged. Thanks to @Cassian433 for the detailed report #593VideoStream has a new close() method to release the file handles and decoders a video holds, and can be used as a context manager (with open_video(path) as video:) to close it automatically. Calling close() more than once has no effect. Once an OpenCV, PyAV, MoviePy or concatenated stream is closed, read(), seek() and reset() raise ValueError, while properties describing the video (path, name, frame_rate, duration, frame_size, aspect_ratio) remain available. The default implementation does nothing, so existing VideoStream subclasses are unaffected, and VideoCaptureAdapter leaves the caller's VideoCapture open #568VideoStream.seek() now documents that the stream position is undefined after a SeekError is raised, and reset() must be called before reading furtherVideoStreamConcat no longer keeps its input videos open when they can't be concatenated (e.g. mismatched resolutions), and now closes each input explicitly once it is no longer needed instead of relying on garbage collection #568write_scene_list() now starts the cut list row with Timecode List: when no cut_list is passed, as it does when one is passed and as write_scene_list_html() doespyav backend timing for videos that lack presentation timestamps (e.g. AVI files, elementary H.264 streams), which could lead to frame positions being out of order or stuck at zero and shifting cuts by one or more frames (#590, PyAV#933, PyAV#2478)
genpts flag disabled.opencv backend.moviepy backend does for every frame).VideoStreamAv.seek() now raises SeekError on streams that cannot be seeked (e.g. elementary streams without timestamps) instead of a backend-specific exception.VideoStreamAv.seek() now falls back to reading from the start when the demuxer lands on a frame without a timestamp past the target, and seek(0) always re-opens the video, fixing wrong positions after seeking in some MPEG-TS files.PySceneDetect-0.7.3-win64.msi (installer) or PySceneDetect-0.7.3-win64.zip (portable); both signed, checksums in SHA256SUMS and PySceneDetect-0.7.3-win64.manifest.jsonpip install scenedetect==0.7.3 (or scenedetect-headless); wheels and sdists attachedThanks to @nikhiljangid120, @sungbin1015, @qwist1233-cpu, @vishal-tambi, @Rober1208, @ChandraChaan and @MuhammadBilalKhan267 for their contributions to this release.
PySceneDetect 0.7.2 ships improved defaults for the histogram and perceptual hash detectors, adds PyAV 19 support, and fixes several timing and output bugs. Default output of detect-hist and detect-hash will change in this release due to improved default values.
HistogramDetector (detect-hist) default threshold changed from 0.05 to 0.20 and default bins from 256 to 128, calibrated from the benchmarks. Output for this detector will change if you are not setting both parameters explicitly. #559
detect-hist -t 0.05 -b 256 or HistogramDetector(threshold=0.05, bins=256) to restore the previous behavior.HashDetector (detect-hash) default threshold changed from 0.395 to 0.35 and default size from 16 to 8, calibrated from the benchmarks. Output for this detector will change if you are not setting both parameters explicitly. #559
detect-hash -t 0.395 -s 16 or HashDetector(threshold=0.395, size=16) to restore the previous behavior.detect-threshold now ignores fade-outs shorter than 0.1s by default. Use --min-out-length 0 to restore the previous behavior. The API default remains 0 #278save-keyframes command to export detected cuts using # keyframe format v1 for Aegisub-compatible tools #534. Frame numbers are currently approximate for VFR input #569--min-out-length/min_out_length to detect-threshold/ThresholdDetector, which requires that fades stay below the threshold for the given duration #278-f, --frame-rate, and --framerate are now aliases of the same CLI option, and all forms appear in help and documentation. If multiple forms are given, the last value is used #548AdaptiveDetector / detect-adaptive emitting scenes shorter than min_scene_len when window_width is large, by applying the minimum-length check to the emitted (target) frame instead of the current frame #408framerate argument aliases in FrameTimecode, open_video(), and the video backends now emit a DeprecationWarning; use frame_rate instead. When both forms are provided, frame_rate takes precedence #548write_scene_list() now also accepts a path (str or pathlib.Path) as the first argument in addition to an open file handle; paths are opened and closed automatically #523pathlib.Path; paths are opened and closed automatically #567ThresholdDetector/detect-threshold with method CEILING now classifies the first frame with the CEILING rule instead of the FLOOR rule, which anchored a leading fade one frame late and could emit a spurious cut at the first frame (thanks @MuhammadBilalKhan267)min_scene_len given in frames dropping cuts that are exactly min_scene_len frames apart at NTSC framerates (e.g. 29.97 fps), by comparing frame counts instead of converting to seconds #577TypeError when opening videos with the pyav backend on PyAV 19.0 or newer (PyAV 19 is now supported)pyav backend duration calculation fallbackpyav backend not releasing the file handle it opened when the stream is garbage collected, which emitted a ResourceWarning under python -X dev #568opencv-python 4.14 or 5.0 (upstream: opencv/opencv#30017) #575scenedetect-core package introduced in 0.7.1 has been discontinued, and its only release (0.7.1) yanked from PyPI. Existing scenedetect-core installs keep working but will not receive updates. Install either scenedetect or scenedetect-headless. #558PySceneDetect 0.7.1 adds support for concatenating multiple videos, along with several stability and robustness fixes for the PyAV and OpenCV backends.
split-video has a new --expand flag: when scenes are detected within a time window (-s/-e), the first output clip is extended back to the start of the video and the last clip is extended forward to the end, so no footage outside the analysis window is dropped #115scenedetect.detect() now accepts a backend keyword argument ("opencv", "pyav", or "moviepy") similar to open_video. Defaults to "opencv", matching prior behavior.expand_scenes_to_bounds() helper in scenedetect.scene_manager to extend a scene list so the first scene starts at a given lower bound and the last scene ends at a given upper boundVideoStream now provides a public read-only decode_failures property reporting the number of frames that failed to decode and were skipped (defaults to 0; populated by the OpenCV and PyAV backends)VideoStreamConcat (scenedetect.backends.concat) which concatenates multiple videos into a single continuous stream with a monotonic PTS timeline; open_video() and detect() now accept a list of paths. VideoStreamConcat.map_span() maps spans of the global timeline back to per-source local timesVideoStreamAv) now skips corrupt frames during read() and continues decoding instead of failing, giving up only after 8 consecutive decode failures (matching the OpenCV backend's tolerance behavior)position 0, consistent with other backends and with seek()FrameTimecode objects that both carry exact presentation times (e.g. positions from VFR videos) and share the same frame rate are now performed exactly using pts and time_base instead of rounded frame numbers. Previously, distinct frames in VFR sections could compare equal or fail strict ordering when their times rounded to the same approximate frame number. Comparisons involving frame- or seconds-based timecodes, plain values (int/float/str), or differing frame rates are unchangedscenedetect and scenedetect-headless are unchanged: they continue to ship the full program (library + CLI) with opencv-python / opencv-python-headless respectively. Both packages provide the same scenedetect module (install or depend only one)docker run --rm -v "$(pwd):/files" ghcr.io/breakthrough/pyscenedetect -i /files/video.mp4 detect-adaptive split-video -o /filesPySceneDetect 0.7 is a major breaking release which overhauls how timestamps are handled. This allows PySceneDetect to properly process variable framerate (VFR) videos. A significant amount of technical debt has been addressed, including removal of deprecated or overly complicated APIs.
Care was taken to minimize changes for most common API uses, however more advanced use cases may run into breaking changes. Please review the Migration Guide when updating from v0.6. Minimum supported Python version is now Python 3.10.
0.6s) and timecodes (e.g. 00:00:00.600) #531save-fcp command allows exporting in Final Cut Pro format (FCP7/FCPX) #156save-qp command writes a QP file with scene boundary frame numbers, suitable for forcing keyframes at scene cuts in x264/x265 #448save-html command replaces the deprecated export-html; the prior command remains as an alias and emits a deprecation warning #518save-edl option --start-timecode/-s to providde a custom start timecode for generated EDLs, supports SMPTE HH:MM:SS:FF or 8-digit HHMMSSFF input #515save-otio output where frame values near integer boundaries (e.g. 90.00000000000001) were serialized with spurious precisionOSError in the MoviePy backend as it is susceptible to subprocess pipe races on slow or heavily loaded systems #496-f/--frame-rate (and the VideoStreamMoviePy(frame_rate=...) API), bringing it in line with the OpenCV and PyAV backendsdetect-threshold cut frame numbers are now backend-deterministic; previously the cut could differ by 1 frame between PyAV and OpenCV when the fade midpoint landed on a .5 rounding boundary (PyAV uses sub-microsecond PTS, OpenCV uses millisecond-truncated CAP_PROP_POS_MSEC)-d/--min-delta-hsv option from detect-adaptive command (use -c/--min-content-val instead)-f/--framerate to -f/--frame-rate as part of VFR overhaul (legacy --framerate form is preserved as a hidden alias but will be removed in v0.8)SCENEDETECT_DEBUG environment variable to control how exceptions and debugging are handled. Unhandled exceptions and Ctrl+C now produce a logger-formatted error message and exit cleanly with code 1 instead of dumping a raw Python traceback. Set SCENEDETECT_DEBUG=1 to ensure all exceptions are re-raised instead of being logged. In both cases, the program will exit with a non-zero exit code.write_scene_list_edl, write_scene_list_fcpx, write_scene_list_fcp7, and write_scene_list_otio to the scenedetect.output module so save-edl, save-fcp, and save-otio can be invoked directly from Python (previously CLI-only)write_scene_list_edl accepts an optional start_timecode parameter (SMPTE HH:MM:SS:FF or 8-digit HHMMSSFF) that is added to every event's source and record columns #515Timecode type to represent frame timings in terms of the video's source timebasetime_base and pts properties to FrameTimecode for more accurate timing informationVideoStream.positionVideoStream.frame_rate now returns Fraction instead of floatFraction values (e.g. Fraction(24000, 1001) instead of 23.976) to avoid float precision lossFrameTimecode.frame_num is now approximate for VFR video (based on PTS-derived time)frame_rate property (returns exact Fraction) as the canonical replacement for framerate (returns float) in FrameTimecode and VideoStream
time_base equals 1 / frame_rate for CFR sources #548frame_rate keyword argument to open_video() and the VideoStreamCv2, VideoCaptureAdapter, VideoStreamAv, and VideoStreamMoviePy constructors as the canonical replacement for framerate #548; accepts float | Fraction | None. The legacy framerate keyword is retained as a deprecated alias and is ignored when frame_rate is providedequal_frame_rate(other) method as the canonical replacement for equal_framerate(fps)opencv-python a requirement, add separate scenedetect-headless variant insteadframe_num parameter (int) with timecode (FrameTimecode) in SceneDetector interface #168:
SceneDetector.process_frame() and SceneDetector.post_process() (the post_process signature on the abstract base is now consistently typed as FrameTimecode to match its concrete-detector overrides; the prior int annotation did not reflect the actual runtime value)StatsManager.get_metrics(), StatsManager.set_metrics(), and StatsManager.metrics_exist() formally accept either FrameTimecode or int (the int form is retained for compatibility with the deprecated load_from_csv() path, which keys metrics by integer frame number)StatsManager.load_from_csv() and save_images() output_dir now accept os.PathLike (e.g. pathlib.Path) in addition to strSceneManager.detect_scenes() duration and end_time formally accept int (frames), float (seconds), str (timecode), or FrameTimecode - matching the documented and runtime-supported behaviorSceneDetector is now a Python abstract classSceneDetector instances can now assume they always have frame data to process when process_frame is calledSceneDetector.is_processing_required() methodSceneDetector.stats_manager_required property, no longer requiredSparseSceneDetector interfacemin_scene_len and save_images() frame_margin arguments now accept seconds (float) and timecode strings (e.g. "0.6s", "00:00:00.600") in addition to a frame count (int); these are evaluated using the source video's timing for correct behavior on VFR videos #531Module Reorganization:
scenedetect.scene_detector moved to scenedetect.detectorscenedetect.frame_timecode moved to scenedetect.commonscenedetect.scene_manager moved to scenedetect.output #463scenedetect.video_splitter moved to scenedetect.output.video #463frame_num, frame_rate, and seconds instead of getter methodsframe_num and frame_rate are now read-only properties (construct a new FrameTimecode to change them)FrameTimecode.previous_frame() methodwarnings module to emit runtime deprecation warnings, these features will be removed in v0.8framerate property and equal_framerate() method via docstring; the legacy forms will continue to work until v0.8 when they will be upgraded to DeprecationWarning before removal in v0.9scenedetect.video_manager, use the scenedetect.open_video() function insteadbase_timecode and video_manager from various functionsSceneManager.get_event_list() methodAdaptiveDetector.get_content_val() method (use StatsManager instead)AdaptiveDetector constructor arg min_delta_hsv (use min_content_val instead)advance parameter from VideoStream.read()SceneDetector.stats_manager_required property, no longer requiredSceneDetector is now a Python abstract classCtrl+C during scene detection in the bundled distribution now exits cleanly instead of surfacing the PyInstaller bootloader tracebackFixes issues with importing EDL files into DaVinci Resolve and other editors, update ffmpeg.
save-edl end timestamp being too short by 1 frame #516PySceneDetect v0.6.6 introduces new output formats, which improve compatibility with popular video editors (e.g. DaVinci Resolve).
save-otio command supports saving scenes in OTIO format #497save-edl command supports saving scenes in EDL format CMX 3600 #495split-video with -m/--mkvmerge option #473split-video command with -m/--mkvmerge optionsplit_video_mkvmerge()VideoStreamCv2 as workaround for opencv#26795export-html command is now deprecated, use save-html instead