Files
Merge-Anime-Lanuages/opencv_cross_correlation.py
T
2026-03-14 18:06:41 +01:00

71 lines
2.7 KiB
Python

import cv2
import numpy as np
from scipy import signal
import matplotlib.pyplot as plt
import sys
def get_video_signal(path):
cap = cv2.VideoCapture(path)
motion_signal = []
prev_gray = None
while True:
ret, frame = cap.read()
if not ret:
break
# 1. Shrink the frame (makes it faster and removes noise)
small_frame = cv2.resize(frame, (160, 90))
gray = cv2.cvtColor(small_frame, cv2.COLOR_BGR2GRAY)
if prev_gray is not None:
# 2. Calculate the difference between this frame and the last
# This detects the "movement" or "cuts"
diff = cv2.absdiff(gray, prev_gray)
motion_signal.append(np.sum(diff))
else:
motion_signal.append(0)
prev_gray = gray
cap.release()
return np.array(motion_signal)
def find_offset(video_a, video_b):
# print("Extracting signals (this may take a moment)...")
sig_a = get_video_signal(video_a)
# print("sig_a finished")
sig_b = get_video_signal(video_b)
# print("sig_b finished")
# Normalize signals (subtract mean, divide by std dev) to improve correlation
sig_a = (sig_a - np.mean(sig_a)) / (np.std(sig_a) + 1e-5)
sig_b = (sig_b - np.mean(sig_b)) / (np.std(sig_b) + 1e-5)
# Perform Cross-Correlation
correlation = signal.correlate(sig_a, sig_b, mode='full')
lags = signal.correlation_lags(len(sig_a), len(sig_b), mode='full')
# plt.plot(lags)
# The peak of the correlation is our offset in frames
best_lag = lags[np.argmax(correlation)]
return best_lag
def multiple():
# Usage
for i in range(1, 12):
# print(f"{i:02}")
video_a = f"/home/honney/projects/mkv/AnoHana The Flower We Saw That Day (2011-2011) [imdbid-tt1913273]/Season 01/AnoHana The Flower We Saw That Day S01E0{i:02}.mkv"
video_b = f"/home/honney/projects/mkv/Anohana - The Flower We Saw That Day/S01/AnoHana The Flower We Saw That Day S01E0{i:02}.mkv"
offset_frames = find_offset(video_a, video_b)
print(f"{i}: Video B is offset by {offset_frames} frames relative to Video A.")
sys.exit()
def single():
video_a = f"/home/honney/mount/Media/torent/[Anime Time] One Piece (0001-1071+Movies+Specials) [BD+CR] [Dual Audio] [1080p][HEVC 10bit x265][AAC][Multi Sub]/Season 01 - East Blue/[Anime Time] One Piece - 0001 - I'm Luffy! The Man Who's Gonna Be King of the Pirates!.mkv"
video_b = f"/home/honney/mount/Media/tmp/serien/complicated/One Piece (1999-2025) [imdbid-tt0388629]/Season 01/One Piece S01E001.mkv"
offset_frames = find_offset(video_a, video_b)
print(f"Video B is offset by {offset_frames} frames relative to Video A.")