68 lines
2.6 KiB
Python
68 lines
2.6 KiB
Python
import cv2
|
|
import numpy as np
|
|
from scipy import signal
|
|
import matplotlib.pyplot as plt
|
|
|
|
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
|
|
|
|
# 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 (BD 1080p HEVC Opus) [derpie]/[derpie] Anohana - The Flower We Saw That Day - S01E{i:02} (BD 1080p HEVC Opus) [Dual Audio].mkv"
|
|
|
|
# offset_frames = find_offset(video_a, video_b)
|
|
# print(f"{i}: Video B is offset by {offset_frames} frames relative to Video A.")
|
|
|
|
# print(f"{i:02}")
|
|
video_a = f"/home/honney/projects/mkv/output.mkv"
|
|
video_b = f"/home/honney/projects/mkv/Anohana - The Flower We Saw That Day - S01 (BD 1080p HEVC Opus) [derpie]/[derpie] Anohana - The Flower We Saw That Day - S01E01 (BD 1080p HEVC Opus) [Dual Audio].mkv"
|
|
|
|
offset_frames = find_offset(video_a, video_b)
|
|
print(f"Video B is offset by {offset_frames} frames relative to Video A.") |