86 lines
2.6 KiB
Python
86 lines
2.6 KiB
Python
import cv2
|
|
import numpy as np
|
|
from scipy import signal
|
|
import matplotlib.pyplot as plt
|
|
import sys
|
|
|
|
TARGET_FPS = 30 # common reference rate
|
|
|
|
def get_video_signal(path):
|
|
cap = cv2.VideoCapture(path)
|
|
fps = cap.get(cv2.CAP_PROP_FPS)
|
|
|
|
motion_signal = []
|
|
prev_gray = None
|
|
|
|
while True:
|
|
ret, frame = cap.read()
|
|
if not ret:
|
|
break
|
|
|
|
small_frame = cv2.resize(frame, (160, 90))
|
|
gray = cv2.cvtColor(small_frame, cv2.COLOR_BGR2GRAY)
|
|
|
|
if prev_gray is not None:
|
|
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), fps
|
|
|
|
|
|
def resample_signal(sig, original_fps, target_fps):
|
|
duration = len(sig) / original_fps
|
|
target_length = int(duration * target_fps)
|
|
|
|
return signal.resample(sig, target_length)
|
|
|
|
|
|
def find_offset(video_a, video_b):
|
|
|
|
sig_a, fps_a = get_video_signal(video_a)
|
|
sig_b, fps_b = get_video_signal(video_b)
|
|
|
|
# Resample both signals to common FPS
|
|
sig_a = resample_signal(sig_a, fps_a, TARGET_FPS)
|
|
sig_b = resample_signal(sig_b, fps_b, TARGET_FPS)
|
|
|
|
# Normalize
|
|
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)
|
|
|
|
correlation = signal.correlate(sig_a, sig_b, mode='full')
|
|
lags = signal.correlation_lags(len(sig_a), len(sig_b), mode='full')
|
|
|
|
best_lag = lags[np.argmax(correlation)]
|
|
|
|
# Convert lag to seconds
|
|
offset_seconds = best_lag / TARGET_FPS
|
|
|
|
return best_lag, offset_seconds
|
|
|
|
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/tmp/serien/ger_low_quality/Black Bullet/Black Bullet Season 01 E02 Die Maske des Wahnsinns.mp4"
|
|
video_b = f"/home/honney/mount/Media/tmp/serien/high_quality/Black Bullet (Season 1)/Season 01/Black Bullet - S01E02.mkv"
|
|
|
|
frames, seconds = find_offset(video_a, video_b)
|
|
print(f"Video B is offset by {frames} frames or {seconds} seconds relative to Video A.")
|
|
|
|
if __name__ == '__main__':
|
|
single() |