feat: Refactor video processing script to use FFmpeg for output and remove moviepy dependency

This commit is contained in:
kamil 2025-08-19 12:38:05 +02:00
parent 946c9f51ba
commit 77af869412
2 changed files with 106 additions and 139 deletions

244
main.py
View file

@ -1,15 +1,17 @@
import cv2 import cv2
import scenedetect import scenedetect
import subprocess
from scenedetect import VideoManager, SceneManager from scenedetect import VideoManager, SceneManager
from scenedetect.detectors import ContentDetector from scenedetect.detectors import ContentDetector
from ultralytics import YOLO from ultralytics import YOLO
import torch import torch
from moviepy.editor import VideoFileClip, AudioFileClip import os
import numpy as np
# --- Constants --- # --- Constants ---
ASPECT_RATIO = 9 / 16 ASPECT_RATIO = 9 / 16
OUTPUT_WIDTH = 1080 OUTPUT_WIDTH = 360
OUTPUT_HEIGHT = 1920 OUTPUT_HEIGHT = 640
# Load the YOLO model once # Load the YOLO model once
model = YOLO('yolov8n.pt') model = YOLO('yolov8n.pt')
@ -41,17 +43,13 @@ def analyze_scene_content(video_path, scene_start_time, scene_end_time):
return [] return []
# --- Person Detection using YOLO --- # --- Person Detection using YOLO ---
# The model expects a list of images
results = model([frame], verbose=False) results = model([frame], verbose=False)
detected_objects = [] detected_objects = []
# Process results
for result in results: for result in results:
# We are interested in the bounding boxes
boxes = result.boxes boxes = result.boxes
for box in boxes: for box in boxes:
# class '0' is 'person' in the COCO dataset which yolov8n was trained on
if box.cls[0] == 0: if box.cls[0] == 0:
x1, y1, x2, y2 = [int(i) for i in box.xyxy[0]] x1, y1, x2, y2 = [int(i) for i in box.xyxy[0]]
person_box = [x1, y1, x2, y2] person_box = [x1, y1, x2, y2]
@ -62,9 +60,7 @@ def analyze_scene_content(video_path, scene_start_time, scene_end_time):
face_box = None face_box = None
if len(faces) > 0: if len(faces) > 0:
# We only care about the first (and likely largest) face found
fx, fy, fw, fh = faces[0] fx, fy, fw, fh = faces[0]
# The face coordinates are relative to the person crop, so we convert them back to frame coordinates
face_box = [x1 + fx, y1 + fy, x1 + fx + fw, y1 + fy + fh] face_box = [x1 + fx, y1 + fy, x1 + fx + fw, y1 + fy + fh]
detected_objects.append({'person_box': person_box, 'face_box': face_box}) detected_objects.append({'person_box': person_box, 'face_box': face_box})
@ -74,204 +70,176 @@ def analyze_scene_content(video_path, scene_start_time, scene_end_time):
def detect_scenes(video_path): def detect_scenes(video_path):
# Create a video manager and add the video to it
video_manager = VideoManager([video_path]) video_manager = VideoManager([video_path])
scene_manager = SceneManager() scene_manager = SceneManager()
# Add the ContentDetector algorithm to the scene_manager
scene_manager.add_detector(ContentDetector()) scene_manager.add_detector(ContentDetector())
# Base video manager is required to accurately split scenes
video_manager.set_downscale_factor() video_manager.set_downscale_factor()
video_manager.start() video_manager.start()
# Perform scene detection
scene_manager.detect_scenes(frame_source=video_manager) scene_manager.detect_scenes(frame_source=video_manager)
# Get the list of scenes
scene_list = scene_manager.get_scene_list() scene_list = scene_manager.get_scene_list()
# We also need the framerate for frame calculations
fps = video_manager.get_framerate() fps = video_manager.get_framerate()
print("Detected scenes:")
if not scene_list:
print("No scenes detected.")
else:
for i, scene in enumerate(scene_list):
print(
f"Scene {i+1}: "
f"Start {scene[0].get_timecode()} / "
f"End {scene[1].get_timecode()}"
)
video_manager.release() video_manager.release()
return scene_list, fps return scene_list, fps
def get_enclosing_box(boxes): def get_enclosing_box(boxes):
"""
Calculates a single bounding box that encloses a list of boxes.
"""
if not boxes: if not boxes:
return None return None
min_x = min(box[0] for box in boxes) min_x = min(box[0] for box in boxes)
min_y = min(box[1] for box in boxes) min_y = min(box[1] for box in boxes)
max_x = max(box[2] for box in boxes) max_x = max(box[2] for box in boxes)
max_y = max(box[3] for box in boxes) max_y = max(box[3] for box in boxes)
return [min_x, min_y, max_x, max_y] return [min_x, min_y, max_x, max_y]
def decide_cropping_strategy(scene_analysis, frame_height): def decide_cropping_strategy(scene_analysis, frame_height):
"""
Decides the cropping strategy based on the scene analysis.
Returns the strategy ('TRACK', 'LETTERBOX') and the target box.
"""
num_people = len(scene_analysis) num_people = len(scene_analysis)
if num_people == 0: if num_people == 0:
return 'LETTERBOX', None return 'LETTERBOX', None
if num_people == 1: if num_people == 1:
# If there's a face, track the face. Otherwise, track the person.
target_box = scene_analysis[0]['face_box'] or scene_analysis[0]['person_box'] target_box = scene_analysis[0]['face_box'] or scene_analysis[0]['person_box']
return 'TRACK', target_box return 'TRACK', target_box
# More than one person
person_boxes = [obj['person_box'] for obj in scene_analysis] person_boxes = [obj['person_box'] for obj in scene_analysis]
group_box = get_enclosing_box(person_boxes) group_box = get_enclosing_box(person_boxes)
group_width = group_box[2] - group_box[0] group_width = group_box[2] - group_box[0]
max_width_for_crop = frame_height * ASPECT_RATIO
# Heuristic: If the group width is less than ~80% of the vertical frame's
# width (which is frame_height * 9/16), we can probably fit them.
max_width_for_crop = (frame_height * ASPECT_RATIO) * 0.8
if group_width < max_width_for_crop: if group_width < max_width_for_crop:
return 'TRACK', group_box return 'TRACK', group_box
else: else:
return 'LETTERBOX', None return 'LETTERBOX', None
def calculate_crop_box(target_box, frame_width, frame_height): def calculate_crop_box(target_box, frame_width, frame_height):
"""
Calculates a 9:16 crop box centered on the target_box.
"""
target_center_x = (target_box[0] + target_box[2]) / 2 target_center_x = (target_box[0] + target_box[2]) / 2
crop_height = frame_height crop_height = frame_height
crop_width = int(crop_height * ASPECT_RATIO) crop_width = int(crop_height * ASPECT_RATIO)
# Calculate crop box coordinates
x1 = int(target_center_x - crop_width / 2) x1 = int(target_center_x - crop_width / 2)
y1 = 0 y1 = 0
x2 = int(target_center_x + crop_width / 2) x2 = int(target_center_x + crop_width / 2)
y2 = frame_height y2 = frame_height
# Ensure the crop box is within the frame bounds
if x1 < 0: if x1 < 0:
x1 = 0 x1 = 0
x2 = crop_width x2 = crop_width
if x2 > frame_width: if x2 > frame_width:
x2 = frame_width x2 = frame_width
x1 = frame_width - crop_width x1 = frame_width - crop_width
return x1, y1, x2, y2 return x1, y1, x2, y2
def process_video(input_path, output_path, scenes_analysis): def get_video_resolution(video_path):
cap = cv2.VideoCapture(input_path) cap = cv2.VideoCapture(video_path)
if not cap.isOpened(): if not cap.isOpened():
print(f"Error: Could not open video {input_path}") raise IOError(f"Could not open video file {video_path}")
return width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
cap.release()
return width, height
fps = cap.get(cv2.CAP_PROP_FPS) if __name__ == '__main__':
frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) input_video = 'video_churchil.mp4'
frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) temp_video_output = 'temp_video.mp4'
temp_audio_output = 'temp_audio.aac'
fourcc = cv2.VideoWriter_fourcc(*'mp4v') final_output_video = 'output.mp4'
out = cv2.VideoWriter(output_path, fourcc, fps, (OUTPUT_WIDTH, OUTPUT_HEIGHT))
# Clean up previous temp files if they exist
if os.path.exists(temp_video_output): os.remove(temp_video_output)
if os.path.exists(temp_audio_output): os.remove(temp_audio_output)
if os.path.exists(final_output_video): os.remove(final_output_video)
print("Step 1: Detecting scenes...")
scenes, fps = detect_scenes(input_video)
if not scenes:
print("No scenes were detected. Aborting.")
exit()
print("\nStep 2: Analyzing content of each scene...")
original_width, original_height = get_video_resolution(input_video)
scenes_analysis = []
for i, (start_time, end_time) in enumerate(scenes):
analysis = analyze_scene_content(input_video, start_time, end_time)
scenes_analysis.append({
'start_frame': start_time.get_frames(),
'end_frame': end_time.get_frames(),
'analysis': analysis
})
print(f" - Scene {i+1}: Found {len(analysis)} person(s).")
print("\nStep 3: Processing video frames and piping to FFmpeg...")
# FFmpeg command to receive frames from stdin
command = [
'ffmpeg',
'-y',
'-f', 'rawvideo',
'-vcodec', 'rawvideo',
'-s', f'{OUTPUT_WIDTH}x{OUTPUT_HEIGHT}',
'-pix_fmt', 'bgr24',
'-r', str(fps),
'-i', '-',
'-c:v', 'libx264',
'-preset', 'fast',
'-crf', '23',
'-an', # No audio in this temporary file
temp_video_output
]
# Open FFmpeg process
ffmpeg_process = subprocess.Popen(command, stdin=subprocess.PIPE)
cap = cv2.VideoCapture(input_video)
frame_number = 0 frame_number = 0
current_scene_index = 0 current_scene_index = 0
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
# Get the first scene's strategy
strategy, target_box = decide_cropping_strategy(scenes_analysis[0]['analysis'], frame_height)
if strategy == 'TRACK':
crop_box = calculate_crop_box(target_box, frame_width, frame_height)
print("Processing video with smart cropping...") while cap.isOpened():
while(cap.isOpened()):
ret, frame = cap.read() ret, frame = cap.read()
if not ret: if not ret:
break break
# Check if we have moved to a new scene if frame_number % 100 == 0:
if current_scene_index < len(scenes_analysis) - 1: print(f" - Processing frame {frame_number}/{total_frames}")
next_scene_start_frame = scenes_analysis[current_scene_index + 1]['start_frame']
if frame_number >= next_scene_start_frame: # Determine which scene this frame is in
current_scene_index += 1 if current_scene_index < len(scenes_analysis) - 1 and \
strategy, target_box = decide_cropping_strategy(scenes_analysis[current_scene_index]['analysis'], frame_height) frame_number >= scenes_analysis[current_scene_index + 1]['start_frame']:
print(f" - New Scene ({current_scene_index+1}): Strategy is {strategy}") current_scene_index += 1
if strategy == 'TRACK':
crop_box = calculate_crop_box(target_box, frame_width, frame_height) scene_data = scenes_analysis[current_scene_index]
strategy, target_box = decide_cropping_strategy(scene_data['analysis'], original_height)
# Apply the transformation for the current scene
if strategy == 'TRACK': if strategy == 'TRACK':
cropped_frame = frame[:, crop_box[0]:crop_box[2]] crop_box = calculate_crop_box(target_box, original_width, original_height)
output_frame = cv2.resize(cropped_frame, (OUTPUT_WIDTH, OUTPUT_HEIGHT)) processed_frame = frame[crop_box[1]:crop_box[3], crop_box[0]:crop_box[2]]
output_frame = cv2.resize(processed_frame, (OUTPUT_WIDTH, OUTPUT_HEIGHT))
else: # LETTERBOX else: # LETTERBOX
# Calculate letterbox dimensions scale_factor = OUTPUT_WIDTH / original_width
scale_factor = OUTPUT_WIDTH / frame_width scaled_height = int(original_height * scale_factor)
scaled_height = int(frame_height * scale_factor)
scaled_frame = cv2.resize(frame, (OUTPUT_WIDTH, scaled_height)) scaled_frame = cv2.resize(frame, (OUTPUT_WIDTH, scaled_height))
# Create a black canvas output_frame = np.zeros((OUTPUT_HEIGHT, OUTPUT_WIDTH, 3), dtype=np.uint8)
output_frame = torch.zeros((OUTPUT_HEIGHT, OUTPUT_WIDTH, 3), dtype=torch.uint8).numpy()
# Paste the scaled frame in the center
y_offset = (OUTPUT_HEIGHT - scaled_height) // 2 y_offset = (OUTPUT_HEIGHT - scaled_height) // 2
output_frame[y_offset:y_offset + scaled_height, :] = scaled_frame output_frame[y_offset:y_offset + scaled_height, :] = scaled_frame
out.write(output_frame) # Write frame to FFmpeg's stdin
ffmpeg_process.stdin.write(output_frame.tobytes())
frame_number += 1 frame_number += 1
ffmpeg_process.stdin.close()
ffmpeg_process.wait()
cap.release() cap.release()
out.release()
print("Video processing complete.")
if __name__ == '__main__':
input_video = 'video_churchil.mp4'
temp_output_video = 'temp_output.mp4'
final_output_video = 'output.mp4'
print("Step 1: Detecting scenes...") print("\nStep 4: Extracting original audio...")
scenes, fps = detect_scenes(input_video) audio_extract_command = [
'ffmpeg', '-y', '-i', input_video, '-vn', '-acodec', 'copy', temp_audio_output
scenes_analysis = [] ]
if scenes: subprocess.run(audio_extract_command, check=True, capture_output=True)
print("\nStep 2: Analyzing content of each scene...")
for i, (start_time, end_time) in enumerate(scenes): print("\nStep 5: Merging processed video and original audio...")
analysis = analyze_scene_content(input_video, start_time, end_time) merge_command = [
scenes_analysis.append({ 'ffmpeg', '-y', '-i', temp_video_output, '-i', temp_audio_output,
'scene': i+1, '-c:v', 'copy', '-c:a', 'copy', final_output_video
'start_frame': start_time.get_frames(), ]
'end_frame': end_time.get_frames(), subprocess.run(merge_command, check=True, capture_output=True)
'analysis': analysis
}) # Clean up temp files
print(f" - Scene {i+1}: Found {len(analysis)} person(s).") os.remove(temp_video_output)
os.remove(temp_audio_output)
print("\nStep 3: Processing video and applying smart cropping...")
process_video(input_video, temp_output_video, scenes_analysis) print(f"\nAll done! Final video saved to {final_output_video}")
print("\nStep 4: Merging audio...")
original_video_clip = VideoFileClip(input_video)
processed_video_clip = VideoFileClip(temp_output_video)
final_clip = processed_video_clip.set_audio(original_video_clip.audio)
final_clip.write_videofile(final_output_video, codec='libx264', audio_codec='aac')
print(f"\nAll done! Final video saved to {final_output_video}")
else:
print("No scenes were detected. Aborting.")

View file

@ -3,4 +3,3 @@ scenedetect[opencv]
ultralytics ultralytics
torch torch
torchvision torchvision
moviepy==1.0.3