import cv2
import os
from skimage.metrics import structural_similarity as ssim
import numpy as np
from PIL import Image
# 视频路径
video_path = '/kaggle/input/202408282/vv1.mp4' # 请替换为你的视频文件路径
output_dir = '/kaggle/working/captured_frames'
output_dir2 = '/kaggle/working'
os.makedirs(output_dir, exist_ok=True)
def save_frame(frame, count):
"""保存当前帧为图像文件"""
img = Image.fromarray(frame)
img.save(os.path.join(output_dir, f'frame_{count}.png'))
def compare_frames(prev_frame, current_frame, region):
"""比较两帧中指定区域的相似度"""
x, y, w, h = region
prev_cropped = prev_frame[y:y+h, x:x+w]
curr_cropped = current_frame[y:y+h, x:x+w]
# 转换为灰度图
prev_gray = cv2.cvtColor(prev_cropped, cv2.COLOR_BGR2GRAY)
curr_gray = cv2.cvtColor(curr_cropped, cv2.COLOR_BGR2GRAY)
# 计算结构相似度 (SSIM)
score, _ = ssim(prev_gray, curr_gray, full=True)
return score
def capture_frames_with_changes(video_path, region, threshold=0.85):
cap = cv2.VideoCapture(video_path)
prev_frame = None
count = 0
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
if prev_frame is not None:
# 计算当前帧与上一帧中指定区域的相似度
similarity = compare_frames(prev_frame, frame, region)
print(f"Frame {count}: Similar = {similarity:.4f}")
# 如果相似度低于阈值,认为发生了显著变化,保存帧
if similarity < threshold:
print(f"Significant change detected at frame {count}")
save_frame(frame, count)
prev_frame = frame
count += 1
cap.release()
print(f"Finished processing. Total frames captured: {count}")
# 设置比较区域 (根据实际视频的内容调整)
# 请根据视频中需要比较的区域调整参数
compare_region = (260, 710, 940, 70) # x, y, width, height
# 运行程序
capture_frames_with_changes(video_path, compare_region)
import shutil
# 压缩文件夹
shutil.make_archive('/kaggle/working/captured_frames2', 'zip', output_dir)
# 清空输出文件夹
if os.path.exists(output_dir):
shutil.rmtree(output_dir) # 删除文件夹及其中的所有文件
os.makedirs(output_dir, exist_ok=True) # 重新创建空文件夹