Video Scence Detection with PySceneDetect

CK CK 3788 
Created at
Updated at  
2,339 0 0

PySceneDetect is a Python library for detecting scene changes in videos. It uses various algorithms, including content-aware methods like thresholding, color histogram analysis, and edge detection, to identify scene breaks. It provides tools for analyzing and exporting the detected scenes, and can be integrated into video editing workflows for tasks like creating chapter markers, summarizing videos, or detecting commercials. 

 

To detect scene changes in an MP4 file using Python, you can use the PySceneDetect library. PySceneDetect is specifically designed for detecting scene changes in video files and is relatively easy to set up and use.

 

Installation

pip install scenedetect[opencv]

The [opencv] option installs OpenCV as a backend, which is commonly used for video processing tasks.

 

If pip install scenedetect[opencv] doesn’t work, you can try installing PySceneDetect and OpenCV separately:

pip install scenedetect
pip install opencv-python

 

Basic Usage

Here's a basic example to detect scene changes:

from scenedetect import open_video, SceneManager
from scenedetect.detectors import ContentDetector

# Open the video file
video = open_video('path/to/video.mp4')

# Create a scene manager and add a content detector
scene_manager = SceneManager()
scene_manager.add_detector(ContentDetector())

# Perform scene detection
scene_manager.detect_scenes(video)

# Retrieve the list of detected scenes
scene_list = scene_manager.get_scene_list()

# Print the start and end timecodes of each scene
for i, scene in enumerate(scene_list):
    print(f"Scene {i+1}: Start {scene[0].get_timecode()} - End {scene[1].get_timecode()}")

 

You can adjust the detection threshold to be more or less sensitive by passing a threshold parameter to ContentDetector, such as ContentDetector(threshold=30).

 

You can also set the range before detect_scenes() if you don't need to scan full range

# Define the frame range for scene detection (e.g., from frame 5000 to frame 15000).
start_frame = 5000
end_frame = 15000

# Set the duration to the specific range of frames.
video_manager.set_duration(start_time=start_frame / video_manager.frame_rate, 
                           end_time=end_frame / video_manager.frame_rate)

 

Additional Features

PySceneDetect also supports other features, like:

  • Saving scenes to separate video files.
  • Exporting timestamps to text files.

This should give you a solid starting point for detecting scene changes in MP4 files using Python.

 

Saving scenes to separate video files

To save the detected scenes as separate video files, you can extend the previous code by using PySceneDetect's split_video function. This function will automatically split the video based on the scenes detected and save each scene as a separate file.

Here's the updated code:

import os
from scenedetect import open_video, SceneManager
from scenedetect.detectors import ContentDetector
from scenedetect.video_splitter import split_video_ffmpeg

# Path to your video file
video_path = 'path/to/video..mp4'
output_directory = 'output_scenes'  # Directory where scenes will be saved

# Open the video file
video = open_video(video_path)

# Create a scene manager and add a content detector
scene_manager = SceneManager()
scene_manager.add_detector(ContentDetector())

# Perform scene detection
scene_manager.detect_scenes(video)

# Get list of detected scenes
scene_list = scene_manager.get_scene_list()
print(f"Detected {len(scene_list)} scenes in {video_path}.")

# Print the start and end timecodes of each scene
for i, scene in enumerate(scene_list):
	print(f"Scene {i+1}: Start {scene[0].get_timecode()} - End {scene[1].get_timecode()}")

	# Generate a unique filename for each scene
	output_file = os.path.join(output_directory, f'{os.path.splitext(os.path.basename(video_path))[0]}-Scene-{i+1}.mp4')

	# Split and save the scene
	split_video_ffmpeg(
		video_path,  # Path to the input video file
		[(scene[0], scene[1])],  # Start and end time for the current scene
		output_dir=output_file  # Output path for the current scene
	)

print(f"Scenes have been saved in the '{output_directory}' directory.")

 

Above code create each of scences, so it is something uncomfortable, so I tried to find another approach with ffmpeg:

import os
import ffmpeg
from scenedetect import open_video, SceneManager
from scenedetect.detectors import ContentDetector

# Path to your video file
video_path = 'snowwhite.mp4'
output_directory = 'output_scenes'  # Directory where scenes will be saved

# Open the video file
video = open_video(video_path)

# Create a scene manager and add a content detector
scene_manager = SceneManager()
scene_manager.add_detector(ContentDetector())

# Perform scene detection
scene_manager.detect_scenes(video)

# Get list of detected scenes
scene_list = scene_manager.get_scene_list()
print(f"Detected {len(scene_list)} scenes in {video_path}.")

# Print the start and end timecodes of each scene
for i, scene in enumerate(scene_list):

        # Generate a unique filename for each scene
        output_file = os.path.join(output_directory, f'{os.path.splitext(os.path.basename(video_path))[0]}-Scene-{i+1:04}.mp4')

        print(f"Scene {i+1}: Start {scene[0].get_timecode()} - End {scene[1].get_timecode()} - {output_file}")

        # Split and save the scene
        ffmpeg.input( video_path, ss=scene[0], to=scene[1]).output(output_file).run(overwrite_output=True)

print(f"Scenes have been saved in the '{output_directory}' directory.")

This function uses ffmpeg-python, which provides an interface to ffmpeg. The function specifies the input video and the time range to trim, then exports the result to the specified output file. Make sure ffmpeg-python is installed:

pip install ffmpeg-python

 

This code will detect scenes in the video and save each scene as a separate MP4 file in the specified directory.
 

Tags MP4 Scene Detection OpenCV PySceneDetect Python Scene Detection Scene Detection Video Analysis Video Editing Video Processing Video Scene Detection Video Segmentation ffmpeg-python split_video_ffmpeg video_splitter Facebook X
Comments 0
Similar posts
  1. Approaches to Scene Detection in Video Processing
    651
  2. Mastering AI: A Beginner's Guide to Python Programming and Beyond
    1,040
  1. Automated API documentation for a Django REST Framework (DRF) project using drf-yasg (Yet Another Swagger Generator)
    1,032
  2. Uploading a file to a Google Drive Folder programmatically with Python
    3,309
  3. Garbage Collection when your system does not have enough memory in your Python App
    1,021
  4. Method to maximize full CPU performance with Python
    325
  5. How do I get the maximum available of thread in python?
    994
  6. Using Queue Algorithm with Redis - RPUSH and LPOP
    774
  7. Use cache concept with Redis : Let's do Redis programming with Python
    539
  8. Installing Python 3.8 in a venv environment on CentOS 7
    465
  9. CUDA versus OpenCL
    584
  10. Simple gRPC server based on Python
    398
  11. Python code to convert PDF file to Excel Spreadsheet
    705
  12. Python script to list files on your Google Drive and download one of them
    941
  13. Coinbase Python API - Basic Example
    464
  14. AWS Lambda Code Example based on Python
    334
  15. Python code using GPU on CentOS with AWS
    1,258
  16. Python Audio Separation Libraries allowing you to isolate individual tracks
    1,452
  17. Python Version Control for Library Compatibility with pyenv - Downgrading/Upgrading Python Version
    912
  18. Deleting a specific user voice from the original audio track with Python
    553
  19. Creating an MR from the original MP3 audio in Python - Deleting Voice Track from Audio File
    443
  20. Creating mp3 audio file based on the text input with Python
    469
  21. Implementing Text To Speech / Audio with Python3 and pyttsx3
    357
  22. Building Initial Virtual Environment at Python - The first step you should do for Python Programming
    560
  23. Python Simplified Assignment Operators
    535
  24. Trackback module used for Python Threading debugging
    847
  25. Python Flask with simple HTML files to server web pages along with API
    931
  26. Python Flask web server tutorial from the scratch
    626
  27. Simple Web Server based in Python
    381
  28. Thread Implementation in Python
    511
  29. A shell script that activates a Python virtual environment and then runs a specific Python script
    747
  30. Learning about Python Multiprocessing Technique
    594
Recently updated
  1. Google OAuth Token Expiration: Causes and Solutions
    29
  2. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    55
  3. Why SPF and DKIM Are Essential for Linux Email Servers?
    49
  4. How do I create animated background for Google Meet?
    22,838
  5. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    271
  6. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    103
  7. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    168
  8. Array of arguments passed to script in PHP
    97
  9. Invalid Auction Storms in Ad Tech
    106
  10. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    207
  11. The Two Clocks of Ad Server Architecture
    77
  12. Frequency Cap Architecture Overview
    526
  13. Collecting Proof-of-Play from 100,000 Screens
    152
  14. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    302
  15. What is RedisVL?
    114
  16. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    246
  17. TPU & GPU Cluster Management Tools
    257
  18. The Concept of Scaffolding in AI Agents
    244
  19. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    596
  20. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    267
  21. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    353
  22. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    206
  23. Machine Learning: Training vs. Ranking
    229
  24. The Continuous Learning Machine: Designing a Loop That Actually Turns
    228
  25. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    202
  26. Designing a Data Curation System Around a Vector Database
    230
  27. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    263
  28. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    671
  29. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    200
  30. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    232