Spaces:
Sleeping
Sleeping
import cv2 | |
import numpy as np | |
from skimage.metrics import structural_similarity | |
import matplotlib.pyplot as plt | |
import os | |
def compare_videos(video1_path, video2_path): | |
# Open video files | |
vidcap1 = cv2.VideoCapture(video1_path) | |
vidcap2 = cv2.VideoCapture(video2_path) | |
# Check if videos opened successfully | |
if not vidcap1.isOpened() or not vidcap2.isOpened(): | |
raise ValueError("Error opening video files.") | |
# Get video properties | |
fps1 = vidcap1.get(cv2.CAP_PROP_FPS) | |
fps2 = vidcap2.get(cv2.CAP_PROP_FPS) | |
frame_count1 = int(vidcap1.get(cv2.CAP_PROP_FRAME_COUNT)) | |
frame_count2 = int(vidcap2.get(cv2.CAP_PROP_FRAME_COUNT)) | |
# Ensure videos have same duration (frame count) | |
if frame_count1 != frame_count2 or abs(fps1 - fps2) > 0.1: | |
vidcap1.release() | |
vidcap2.release() | |
raise ValueError("Videos must have the same duration and frame rate.") | |
# Initialize lists for SSIM scores | |
ssim_scores = [] | |
frame_number = 0 | |
# Video writer for difference video | |
width = int(vidcap1.get(cv2.CAP_PROP_FRAME_WIDTH)) | |
height = int(vidcap1.get(cv2.CAP_PROP_FRAME_HEIGHT)) | |
out = cv2.VideoWriter( | |
"utils/output/difference_video.mp4", | |
cv2.VideoWriter_fourcc(*"mp4v"), | |
fps1, | |
(width, height), | |
isColor=True | |
) | |
while True: | |
success1, image1 = vidcap1.read() | |
success2, image2 = vidcap2.read() | |
if not success1 or not success2: | |
break | |
# Resize second video frame to match first video's resolution | |
image2 = cv2.resize(image2, (width, height)) | |
# Convert to grayscale | |
image1_gray = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY) | |
image2_gray = cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY) | |
# Compute SSIM | |
score, diff = structural_similarity(image1_gray, image2_gray, full=True) | |
ssim_scores.append((1 - score) * 100) # Convert to percentage difference | |
# Convert difference to 8-bit unsigned for visualization | |
diff = (diff * 255).astype("uint8") | |
diff_color = cv2.cvtColor(diff, cv2.COLOR_GRAY2BGR) | |
# Write to output video | |
out.write(diff_color) | |
frame_number += 1 | |
# Release resources | |
vidcap1.release() | |
vidcap2.release() | |
out.release() | |
# Plot differences | |
plt.figure(figsize=(10, 6)) | |
plt.plot(range(frame_number), ssim_scores, 'ro-', markersize=2) | |
plt.title("Frame-by-Frame Difference (SSIM)") | |
plt.xlabel("Frame Number") | |
plt.ylabel("Difference (%)") | |
plt.grid(True) | |
plot_path = "utils/output/difference_plot.png" | |
plt.savefig(plot_path) | |
plt.close() | |
return plot_path, "utils/output/difference_video.mp4" |